PackageManagerService.java revision 9f2c93663c2de84f958eebef96a98458ebaf51a9
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_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
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. (Do this before scanning any apps.)
2289            // For security and version matching reason, only consider
2290            // overlay packages if they reside in the right directory.
2291            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2292            if (!overlayThemeDir.isEmpty()) {
2293                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2294                        | PackageParser.PARSE_IS_SYSTEM
2295                        | PackageParser.PARSE_IS_SYSTEM_DIR
2296                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2297            }
2298            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2299                    | PackageParser.PARSE_IS_SYSTEM
2300                    | PackageParser.PARSE_IS_SYSTEM_DIR
2301                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2302
2303            // Find base frameworks (resource packages without code).
2304            scanDirTracedLI(frameworkDir, mDefParseFlags
2305                    | PackageParser.PARSE_IS_SYSTEM
2306                    | PackageParser.PARSE_IS_SYSTEM_DIR
2307                    | PackageParser.PARSE_IS_PRIVILEGED,
2308                    scanFlags | SCAN_NO_DEX, 0);
2309
2310            // Collected privileged system packages.
2311            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2312            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2313                    | PackageParser.PARSE_IS_SYSTEM
2314                    | PackageParser.PARSE_IS_SYSTEM_DIR
2315                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2316
2317            // Collect ordinary system packages.
2318            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2319            scanDirTracedLI(systemAppDir, mDefParseFlags
2320                    | PackageParser.PARSE_IS_SYSTEM
2321                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2322
2323            // Collect all vendor packages.
2324            File vendorAppDir = new File("/vendor/app");
2325            try {
2326                vendorAppDir = vendorAppDir.getCanonicalFile();
2327            } catch (IOException e) {
2328                // failed to look up canonical path, continue with original one
2329            }
2330            scanDirTracedLI(vendorAppDir, mDefParseFlags
2331                    | PackageParser.PARSE_IS_SYSTEM
2332                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2333
2334            // Collect all OEM packages.
2335            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2336            scanDirTracedLI(oemAppDir, mDefParseFlags
2337                    | PackageParser.PARSE_IS_SYSTEM
2338                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2339
2340            // Prune any system packages that no longer exist.
2341            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2342            if (!mOnlyCore) {
2343                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2344                while (psit.hasNext()) {
2345                    PackageSetting ps = psit.next();
2346
2347                    /*
2348                     * If this is not a system app, it can't be a
2349                     * disable system app.
2350                     */
2351                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2352                        continue;
2353                    }
2354
2355                    /*
2356                     * If the package is scanned, it's not erased.
2357                     */
2358                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2359                    if (scannedPkg != null) {
2360                        /*
2361                         * If the system app is both scanned and in the
2362                         * disabled packages list, then it must have been
2363                         * added via OTA. Remove it from the currently
2364                         * scanned package so the previously user-installed
2365                         * application can be scanned.
2366                         */
2367                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2368                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2369                                    + ps.name + "; removing system app.  Last known codePath="
2370                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2371                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2372                                    + scannedPkg.mVersionCode);
2373                            removePackageLI(scannedPkg, true);
2374                            mExpectingBetter.put(ps.name, ps.codePath);
2375                        }
2376
2377                        continue;
2378                    }
2379
2380                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2381                        psit.remove();
2382                        logCriticalInfo(Log.WARN, "System package " + ps.name
2383                                + " no longer exists; it's data will be wiped");
2384                        // Actual deletion of code and data will be handled by later
2385                        // reconciliation step
2386                    } else {
2387                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2388                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2389                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2390                        }
2391                    }
2392                }
2393            }
2394
2395            //look for any incomplete package installations
2396            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2397            for (int i = 0; i < deletePkgsList.size(); i++) {
2398                // Actual deletion of code and data will be handled by later
2399                // reconciliation step
2400                final String packageName = deletePkgsList.get(i).name;
2401                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2402                synchronized (mPackages) {
2403                    mSettings.removePackageLPw(packageName);
2404                }
2405            }
2406
2407            //delete tmp files
2408            deleteTempPackageFiles();
2409
2410            // Remove any shared userIDs that have no associated packages
2411            mSettings.pruneSharedUsersLPw();
2412
2413            if (!mOnlyCore) {
2414                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2415                        SystemClock.uptimeMillis());
2416                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2417
2418                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2419                        | PackageParser.PARSE_FORWARD_LOCK,
2420                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2421
2422                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2423                        | PackageParser.PARSE_IS_EPHEMERAL,
2424                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2425
2426                /**
2427                 * Remove disable package settings for any updated system
2428                 * apps that were removed via an OTA. If they're not a
2429                 * previously-updated app, remove them completely.
2430                 * Otherwise, just revoke their system-level permissions.
2431                 */
2432                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2433                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2434                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2435
2436                    String msg;
2437                    if (deletedPkg == null) {
2438                        msg = "Updated system package " + deletedAppName
2439                                + " no longer exists; it's data will be wiped";
2440                        // Actual deletion of code and data will be handled by later
2441                        // reconciliation step
2442                    } else {
2443                        msg = "Updated system app + " + deletedAppName
2444                                + " no longer present; removing system privileges for "
2445                                + deletedAppName;
2446
2447                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2448
2449                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2450                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2451                    }
2452                    logCriticalInfo(Log.WARN, msg);
2453                }
2454
2455                /**
2456                 * Make sure all system apps that we expected to appear on
2457                 * the userdata partition actually showed up. If they never
2458                 * appeared, crawl back and revive the system version.
2459                 */
2460                for (int i = 0; i < mExpectingBetter.size(); i++) {
2461                    final String packageName = mExpectingBetter.keyAt(i);
2462                    if (!mPackages.containsKey(packageName)) {
2463                        final File scanFile = mExpectingBetter.valueAt(i);
2464
2465                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2466                                + " but never showed up; reverting to system");
2467
2468                        int reparseFlags = mDefParseFlags;
2469                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2470                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2471                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2472                                    | PackageParser.PARSE_IS_PRIVILEGED;
2473                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2474                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2475                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2476                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2477                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2478                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2479                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2480                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2481                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2482                        } else {
2483                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2484                            continue;
2485                        }
2486
2487                        mSettings.enableSystemPackageLPw(packageName);
2488
2489                        try {
2490                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2491                        } catch (PackageManagerException e) {
2492                            Slog.e(TAG, "Failed to parse original system package: "
2493                                    + e.getMessage());
2494                        }
2495                    }
2496                }
2497            }
2498            mExpectingBetter.clear();
2499
2500            // Resolve the storage manager.
2501            mStorageManagerPackage = getStorageManagerPackageName();
2502
2503            // Resolve protected action filters. Only the setup wizard is allowed to
2504            // have a high priority filter for these actions.
2505            mSetupWizardPackage = getSetupWizardPackageName();
2506            if (mProtectedFilters.size() > 0) {
2507                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2508                    Slog.i(TAG, "No setup wizard;"
2509                        + " All protected intents capped to priority 0");
2510                }
2511                for (ActivityIntentInfo filter : mProtectedFilters) {
2512                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2513                        if (DEBUG_FILTERS) {
2514                            Slog.i(TAG, "Found setup wizard;"
2515                                + " allow priority " + filter.getPriority() + ";"
2516                                + " package: " + filter.activity.info.packageName
2517                                + " activity: " + filter.activity.className
2518                                + " priority: " + filter.getPriority());
2519                        }
2520                        // skip setup wizard; allow it to keep the high priority filter
2521                        continue;
2522                    }
2523                    Slog.w(TAG, "Protected action; cap priority to 0;"
2524                            + " package: " + filter.activity.info.packageName
2525                            + " activity: " + filter.activity.className
2526                            + " origPrio: " + filter.getPriority());
2527                    filter.setPriority(0);
2528                }
2529            }
2530            mDeferProtectedFilters = false;
2531            mProtectedFilters.clear();
2532
2533            // Now that we know all of the shared libraries, update all clients to have
2534            // the correct library paths.
2535            updateAllSharedLibrariesLPw();
2536
2537            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2538                // NOTE: We ignore potential failures here during a system scan (like
2539                // the rest of the commands above) because there's precious little we
2540                // can do about it. A settings error is reported, though.
2541                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2542            }
2543
2544            // Now that we know all the packages we are keeping,
2545            // read and update their last usage times.
2546            mPackageUsage.read(mPackages);
2547            mCompilerStats.read();
2548
2549            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2550                    SystemClock.uptimeMillis());
2551            Slog.i(TAG, "Time to scan packages: "
2552                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2553                    + " seconds");
2554
2555            // If the platform SDK has changed since the last time we booted,
2556            // we need to re-grant app permission to catch any new ones that
2557            // appear.  This is really a hack, and means that apps can in some
2558            // cases get permissions that the user didn't initially explicitly
2559            // allow...  it would be nice to have some better way to handle
2560            // this situation.
2561            int updateFlags = UPDATE_PERMISSIONS_ALL;
2562            if (ver.sdkVersion != mSdkVersion) {
2563                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2564                        + mSdkVersion + "; regranting permissions for internal storage");
2565                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2566            }
2567            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2568            ver.sdkVersion = mSdkVersion;
2569
2570            // If this is the first boot or an update from pre-M, and it is a normal
2571            // boot, then we need to initialize the default preferred apps across
2572            // all defined users.
2573            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2574                for (UserInfo user : sUserManager.getUsers(true)) {
2575                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2576                    applyFactoryDefaultBrowserLPw(user.id);
2577                    primeDomainVerificationsLPw(user.id);
2578                }
2579            }
2580
2581            // Prepare storage for system user really early during boot,
2582            // since core system apps like SettingsProvider and SystemUI
2583            // can't wait for user to start
2584            final int storageFlags;
2585            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2586                storageFlags = StorageManager.FLAG_STORAGE_DE;
2587            } else {
2588                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2589            }
2590            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2591                    storageFlags, true /* migrateAppData */);
2592
2593            // If this is first boot after an OTA, and a normal boot, then
2594            // we need to clear code cache directories.
2595            // Note that we do *not* clear the application profiles. These remain valid
2596            // across OTAs and are used to drive profile verification (post OTA) and
2597            // profile compilation (without waiting to collect a fresh set of profiles).
2598            if (mIsUpgrade && !onlyCore) {
2599                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2600                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2601                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2602                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2603                        // No apps are running this early, so no need to freeze
2604                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2605                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2606                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2607                    }
2608                }
2609                ver.fingerprint = Build.FINGERPRINT;
2610            }
2611
2612            checkDefaultBrowser();
2613
2614            // clear only after permissions and other defaults have been updated
2615            mExistingSystemPackages.clear();
2616            mPromoteSystemApps = false;
2617
2618            // All the changes are done during package scanning.
2619            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2620
2621            // can downgrade to reader
2622            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2623            mSettings.writeLPr();
2624            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2625
2626            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2627            // early on (before the package manager declares itself as early) because other
2628            // components in the system server might ask for package contexts for these apps.
2629            //
2630            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2631            // (i.e, that the data partition is unavailable).
2632            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2633                long start = System.nanoTime();
2634                List<PackageParser.Package> coreApps = new ArrayList<>();
2635                for (PackageParser.Package pkg : mPackages.values()) {
2636                    if (pkg.coreApp) {
2637                        coreApps.add(pkg);
2638                    }
2639                }
2640
2641                int[] stats = performDexOptUpgrade(coreApps, false,
2642                        getCompilerFilterForReason(REASON_CORE_APP));
2643
2644                final int elapsedTimeSeconds =
2645                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2646                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2647
2648                if (DEBUG_DEXOPT) {
2649                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2650                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2651                }
2652
2653
2654                // TODO: Should we log these stats to tron too ?
2655                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2656                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2657                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2658                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2659            }
2660
2661            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2662                    SystemClock.uptimeMillis());
2663
2664            if (!mOnlyCore) {
2665                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2666                mRequiredInstallerPackage = getRequiredInstallerLPr();
2667                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2668                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2669                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2670                        mIntentFilterVerifierComponent);
2671                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2672                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2673                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2674                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2675            } else {
2676                mRequiredVerifierPackage = null;
2677                mRequiredInstallerPackage = null;
2678                mRequiredUninstallerPackage = null;
2679                mIntentFilterVerifierComponent = null;
2680                mIntentFilterVerifier = null;
2681                mServicesSystemSharedLibraryPackageName = null;
2682                mSharedSystemSharedLibraryPackageName = null;
2683            }
2684
2685            mInstallerService = new PackageInstallerService(context, this);
2686
2687            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2688            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2689            // both the installer and resolver must be present to enable ephemeral
2690            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2691                if (DEBUG_EPHEMERAL) {
2692                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2693                            + " installer:" + ephemeralInstallerComponent);
2694                }
2695                mEphemeralResolverComponent = ephemeralResolverComponent;
2696                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2697                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2698                mEphemeralResolverConnection =
2699                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2700            } else {
2701                if (DEBUG_EPHEMERAL) {
2702                    final String missingComponent =
2703                            (ephemeralResolverComponent == null)
2704                            ? (ephemeralInstallerComponent == null)
2705                                    ? "resolver and installer"
2706                                    : "resolver"
2707                            : "installer";
2708                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2709                }
2710                mEphemeralResolverComponent = null;
2711                mEphemeralInstallerComponent = null;
2712                mEphemeralResolverConnection = null;
2713            }
2714
2715            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2716        } // synchronized (mPackages)
2717        } // synchronized (mInstallLock)
2718
2719        // Now after opening every single application zip, make sure they
2720        // are all flushed.  Not really needed, but keeps things nice and
2721        // tidy.
2722        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2723        Runtime.getRuntime().gc();
2724        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2725
2726        // The initial scanning above does many calls into installd while
2727        // holding the mPackages lock, but we're mostly interested in yelling
2728        // once we have a booted system.
2729        mInstaller.setWarnIfHeld(mPackages);
2730
2731        // Expose private service for system components to use.
2732        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2733        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2734    }
2735
2736    @Override
2737    public boolean isFirstBoot() {
2738        return mFirstBoot;
2739    }
2740
2741    @Override
2742    public boolean isOnlyCoreApps() {
2743        return mOnlyCore;
2744    }
2745
2746    @Override
2747    public boolean isUpgrade() {
2748        return mIsUpgrade;
2749    }
2750
2751    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2752        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2753
2754        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2755                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2756                UserHandle.USER_SYSTEM);
2757        if (matches.size() == 1) {
2758            return matches.get(0).getComponentInfo().packageName;
2759        } else if (matches.size() == 0) {
2760            Log.e(TAG, "There should probably be a verifier, but, none were found");
2761            return null;
2762        }
2763        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2764    }
2765
2766    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2767        synchronized (mPackages) {
2768            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2769            if (libraryEntry == null) {
2770                throw new IllegalStateException("Missing required shared library:" + libraryName);
2771            }
2772            return libraryEntry.apk;
2773        }
2774    }
2775
2776    private @NonNull String getRequiredInstallerLPr() {
2777        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2778        intent.addCategory(Intent.CATEGORY_DEFAULT);
2779        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2780
2781        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2782                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2783                UserHandle.USER_SYSTEM);
2784        if (matches.size() == 1) {
2785            ResolveInfo resolveInfo = matches.get(0);
2786            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2787                throw new RuntimeException("The installer must be a privileged app");
2788            }
2789            return matches.get(0).getComponentInfo().packageName;
2790        } else {
2791            throw new RuntimeException("There must be exactly one installer; found " + matches);
2792        }
2793    }
2794
2795    private @NonNull String getRequiredUninstallerLPr() {
2796        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2797        intent.addCategory(Intent.CATEGORY_DEFAULT);
2798        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2799
2800        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2801                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2802                UserHandle.USER_SYSTEM);
2803        if (resolveInfo == null ||
2804                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2805            throw new RuntimeException("There must be exactly one uninstaller; found "
2806                    + resolveInfo);
2807        }
2808        return resolveInfo.getComponentInfo().packageName;
2809    }
2810
2811    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2812        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2813
2814        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2815                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2816                UserHandle.USER_SYSTEM);
2817        ResolveInfo best = null;
2818        final int N = matches.size();
2819        for (int i = 0; i < N; i++) {
2820            final ResolveInfo cur = matches.get(i);
2821            final String packageName = cur.getComponentInfo().packageName;
2822            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2823                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2824                continue;
2825            }
2826
2827            if (best == null || cur.priority > best.priority) {
2828                best = cur;
2829            }
2830        }
2831
2832        if (best != null) {
2833            return best.getComponentInfo().getComponentName();
2834        } else {
2835            throw new RuntimeException("There must be at least one intent filter verifier");
2836        }
2837    }
2838
2839    private @Nullable ComponentName getEphemeralResolverLPr() {
2840        final String[] packageArray =
2841                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2842        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2843            if (DEBUG_EPHEMERAL) {
2844                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2845            }
2846            return null;
2847        }
2848
2849        final int resolveFlags =
2850                MATCH_DIRECT_BOOT_AWARE
2851                | MATCH_DIRECT_BOOT_UNAWARE
2852                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2853        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2854        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2855                resolveFlags, UserHandle.USER_SYSTEM);
2856
2857        final int N = resolvers.size();
2858        if (N == 0) {
2859            if (DEBUG_EPHEMERAL) {
2860                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2861            }
2862            return null;
2863        }
2864
2865        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2866        for (int i = 0; i < N; i++) {
2867            final ResolveInfo info = resolvers.get(i);
2868
2869            if (info.serviceInfo == null) {
2870                continue;
2871            }
2872
2873            final String packageName = info.serviceInfo.packageName;
2874            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2875                if (DEBUG_EPHEMERAL) {
2876                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2877                            + " pkg: " + packageName + ", info:" + info);
2878                }
2879                continue;
2880            }
2881
2882            if (DEBUG_EPHEMERAL) {
2883                Slog.v(TAG, "Ephemeral resolver found;"
2884                        + " pkg: " + packageName + ", info:" + info);
2885            }
2886            return new ComponentName(packageName, info.serviceInfo.name);
2887        }
2888        if (DEBUG_EPHEMERAL) {
2889            Slog.v(TAG, "Ephemeral resolver NOT found");
2890        }
2891        return null;
2892    }
2893
2894    private @Nullable ComponentName getEphemeralInstallerLPr() {
2895        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2896        intent.addCategory(Intent.CATEGORY_DEFAULT);
2897        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2898
2899        final int resolveFlags =
2900                MATCH_DIRECT_BOOT_AWARE
2901                | MATCH_DIRECT_BOOT_UNAWARE
2902                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2903        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2904                resolveFlags, UserHandle.USER_SYSTEM);
2905        if (matches.size() == 0) {
2906            return null;
2907        } else if (matches.size() == 1) {
2908            return matches.get(0).getComponentInfo().getComponentName();
2909        } else {
2910            throw new RuntimeException(
2911                    "There must be at most one ephemeral installer; found " + matches);
2912        }
2913    }
2914
2915    private void primeDomainVerificationsLPw(int userId) {
2916        if (DEBUG_DOMAIN_VERIFICATION) {
2917            Slog.d(TAG, "Priming domain verifications in user " + userId);
2918        }
2919
2920        SystemConfig systemConfig = SystemConfig.getInstance();
2921        ArraySet<String> packages = systemConfig.getLinkedApps();
2922
2923        for (String packageName : packages) {
2924            PackageParser.Package pkg = mPackages.get(packageName);
2925            if (pkg != null) {
2926                if (!pkg.isSystemApp()) {
2927                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2928                    continue;
2929                }
2930
2931                ArraySet<String> domains = null;
2932                for (PackageParser.Activity a : pkg.activities) {
2933                    for (ActivityIntentInfo filter : a.intents) {
2934                        if (hasValidDomains(filter)) {
2935                            if (domains == null) {
2936                                domains = new ArraySet<String>();
2937                            }
2938                            domains.addAll(filter.getHostsList());
2939                        }
2940                    }
2941                }
2942
2943                if (domains != null && domains.size() > 0) {
2944                    if (DEBUG_DOMAIN_VERIFICATION) {
2945                        Slog.v(TAG, "      + " + packageName);
2946                    }
2947                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2948                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2949                    // and then 'always' in the per-user state actually used for intent resolution.
2950                    final IntentFilterVerificationInfo ivi;
2951                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2952                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2953                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2954                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2955                } else {
2956                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2957                            + "' does not handle web links");
2958                }
2959            } else {
2960                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2961            }
2962        }
2963
2964        scheduleWritePackageRestrictionsLocked(userId);
2965        scheduleWriteSettingsLocked();
2966    }
2967
2968    private void applyFactoryDefaultBrowserLPw(int userId) {
2969        // The default browser app's package name is stored in a string resource,
2970        // with a product-specific overlay used for vendor customization.
2971        String browserPkg = mContext.getResources().getString(
2972                com.android.internal.R.string.default_browser);
2973        if (!TextUtils.isEmpty(browserPkg)) {
2974            // non-empty string => required to be a known package
2975            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2976            if (ps == null) {
2977                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2978                browserPkg = null;
2979            } else {
2980                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2981            }
2982        }
2983
2984        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2985        // default.  If there's more than one, just leave everything alone.
2986        if (browserPkg == null) {
2987            calculateDefaultBrowserLPw(userId);
2988        }
2989    }
2990
2991    private void calculateDefaultBrowserLPw(int userId) {
2992        List<String> allBrowsers = resolveAllBrowserApps(userId);
2993        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2994        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2995    }
2996
2997    private List<String> resolveAllBrowserApps(int userId) {
2998        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2999        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3000                PackageManager.MATCH_ALL, userId);
3001
3002        final int count = list.size();
3003        List<String> result = new ArrayList<String>(count);
3004        for (int i=0; i<count; i++) {
3005            ResolveInfo info = list.get(i);
3006            if (info.activityInfo == null
3007                    || !info.handleAllWebDataURI
3008                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3009                    || result.contains(info.activityInfo.packageName)) {
3010                continue;
3011            }
3012            result.add(info.activityInfo.packageName);
3013        }
3014
3015        return result;
3016    }
3017
3018    private boolean packageIsBrowser(String packageName, int userId) {
3019        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3020                PackageManager.MATCH_ALL, userId);
3021        final int N = list.size();
3022        for (int i = 0; i < N; i++) {
3023            ResolveInfo info = list.get(i);
3024            if (packageName.equals(info.activityInfo.packageName)) {
3025                return true;
3026            }
3027        }
3028        return false;
3029    }
3030
3031    private void checkDefaultBrowser() {
3032        final int myUserId = UserHandle.myUserId();
3033        final String packageName = getDefaultBrowserPackageName(myUserId);
3034        if (packageName != null) {
3035            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3036            if (info == null) {
3037                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3038                synchronized (mPackages) {
3039                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3040                }
3041            }
3042        }
3043    }
3044
3045    @Override
3046    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3047            throws RemoteException {
3048        try {
3049            return super.onTransact(code, data, reply, flags);
3050        } catch (RuntimeException e) {
3051            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3052                Slog.wtf(TAG, "Package Manager Crash", e);
3053            }
3054            throw e;
3055        }
3056    }
3057
3058    static int[] appendInts(int[] cur, int[] add) {
3059        if (add == null) return cur;
3060        if (cur == null) return add;
3061        final int N = add.length;
3062        for (int i=0; i<N; i++) {
3063            cur = appendInt(cur, add[i]);
3064        }
3065        return cur;
3066    }
3067
3068    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3069        if (!sUserManager.exists(userId)) return null;
3070        if (ps == null) {
3071            return null;
3072        }
3073        final PackageParser.Package p = ps.pkg;
3074        if (p == null) {
3075            return null;
3076        }
3077
3078        final PermissionsState permissionsState = ps.getPermissionsState();
3079
3080        // Compute GIDs only if requested
3081        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3082                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3083        // Compute granted permissions only if package has requested permissions
3084        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3085                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3086        final PackageUserState state = ps.readUserState(userId);
3087
3088        return PackageParser.generatePackageInfo(p, gids, flags,
3089                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3090    }
3091
3092    @Override
3093    public void checkPackageStartable(String packageName, int userId) {
3094        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3095
3096        synchronized (mPackages) {
3097            final PackageSetting ps = mSettings.mPackages.get(packageName);
3098            if (ps == null) {
3099                throw new SecurityException("Package " + packageName + " was not found!");
3100            }
3101
3102            if (!ps.getInstalled(userId)) {
3103                throw new SecurityException(
3104                        "Package " + packageName + " was not installed for user " + userId + "!");
3105            }
3106
3107            if (mSafeMode && !ps.isSystem()) {
3108                throw new SecurityException("Package " + packageName + " not a system app!");
3109            }
3110
3111            if (mFrozenPackages.contains(packageName)) {
3112                throw new SecurityException("Package " + packageName + " is currently frozen!");
3113            }
3114
3115            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3116                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3117                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3118            }
3119        }
3120    }
3121
3122    @Override
3123    public boolean isPackageAvailable(String packageName, int userId) {
3124        if (!sUserManager.exists(userId)) return false;
3125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3126                false /* requireFullPermission */, false /* checkShell */, "is package available");
3127        synchronized (mPackages) {
3128            PackageParser.Package p = mPackages.get(packageName);
3129            if (p != null) {
3130                final PackageSetting ps = (PackageSetting) p.mExtras;
3131                if (ps != null) {
3132                    final PackageUserState state = ps.readUserState(userId);
3133                    if (state != null) {
3134                        return PackageParser.isAvailable(state);
3135                    }
3136                }
3137            }
3138        }
3139        return false;
3140    }
3141
3142    @Override
3143    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3144        if (!sUserManager.exists(userId)) return null;
3145        flags = updateFlagsForPackage(flags, userId, packageName);
3146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3147                false /* requireFullPermission */, false /* checkShell */, "get package info");
3148        // reader
3149        synchronized (mPackages) {
3150            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3151            PackageParser.Package p = null;
3152            if (matchFactoryOnly) {
3153                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3154                if (ps != null) {
3155                    return generatePackageInfo(ps, flags, userId);
3156                }
3157            }
3158            if (p == null) {
3159                p = mPackages.get(packageName);
3160                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3161                    return null;
3162                }
3163            }
3164            if (DEBUG_PACKAGE_INFO)
3165                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3166            if (p != null) {
3167                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3168            }
3169            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3170                final PackageSetting ps = mSettings.mPackages.get(packageName);
3171                return generatePackageInfo(ps, flags, userId);
3172            }
3173        }
3174        return null;
3175    }
3176
3177    @Override
3178    public String[] currentToCanonicalPackageNames(String[] names) {
3179        String[] out = new String[names.length];
3180        // reader
3181        synchronized (mPackages) {
3182            for (int i=names.length-1; i>=0; i--) {
3183                PackageSetting ps = mSettings.mPackages.get(names[i]);
3184                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3185            }
3186        }
3187        return out;
3188    }
3189
3190    @Override
3191    public String[] canonicalToCurrentPackageNames(String[] names) {
3192        String[] out = new String[names.length];
3193        // reader
3194        synchronized (mPackages) {
3195            for (int i=names.length-1; i>=0; i--) {
3196                String cur = mSettings.getRenamedPackageLPr(names[i]);
3197                out[i] = cur != null ? cur : names[i];
3198            }
3199        }
3200        return out;
3201    }
3202
3203    @Override
3204    public int getPackageUid(String packageName, int flags, int userId) {
3205        if (!sUserManager.exists(userId)) return -1;
3206        flags = updateFlagsForPackage(flags, userId, packageName);
3207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3208                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3209
3210        // reader
3211        synchronized (mPackages) {
3212            final PackageParser.Package p = mPackages.get(packageName);
3213            if (p != null && p.isMatch(flags)) {
3214                return UserHandle.getUid(userId, p.applicationInfo.uid);
3215            }
3216            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3217                final PackageSetting ps = mSettings.mPackages.get(packageName);
3218                if (ps != null && ps.isMatch(flags)) {
3219                    return UserHandle.getUid(userId, ps.appId);
3220                }
3221            }
3222        }
3223
3224        return -1;
3225    }
3226
3227    @Override
3228    public int[] getPackageGids(String packageName, int flags, int userId) {
3229        if (!sUserManager.exists(userId)) return null;
3230        flags = updateFlagsForPackage(flags, userId, packageName);
3231        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3232                false /* requireFullPermission */, false /* checkShell */,
3233                "getPackageGids");
3234
3235        // reader
3236        synchronized (mPackages) {
3237            final PackageParser.Package p = mPackages.get(packageName);
3238            if (p != null && p.isMatch(flags)) {
3239                PackageSetting ps = (PackageSetting) p.mExtras;
3240                return ps.getPermissionsState().computeGids(userId);
3241            }
3242            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3243                final PackageSetting ps = mSettings.mPackages.get(packageName);
3244                if (ps != null && ps.isMatch(flags)) {
3245                    return ps.getPermissionsState().computeGids(userId);
3246                }
3247            }
3248        }
3249
3250        return null;
3251    }
3252
3253    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3254        if (bp.perm != null) {
3255            return PackageParser.generatePermissionInfo(bp.perm, flags);
3256        }
3257        PermissionInfo pi = new PermissionInfo();
3258        pi.name = bp.name;
3259        pi.packageName = bp.sourcePackage;
3260        pi.nonLocalizedLabel = bp.name;
3261        pi.protectionLevel = bp.protectionLevel;
3262        return pi;
3263    }
3264
3265    @Override
3266    public PermissionInfo getPermissionInfo(String name, int flags) {
3267        // reader
3268        synchronized (mPackages) {
3269            final BasePermission p = mSettings.mPermissions.get(name);
3270            if (p != null) {
3271                return generatePermissionInfo(p, flags);
3272            }
3273            return null;
3274        }
3275    }
3276
3277    @Override
3278    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3279            int flags) {
3280        // reader
3281        synchronized (mPackages) {
3282            if (group != null && !mPermissionGroups.containsKey(group)) {
3283                // This is thrown as NameNotFoundException
3284                return null;
3285            }
3286
3287            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3288            for (BasePermission p : mSettings.mPermissions.values()) {
3289                if (group == null) {
3290                    if (p.perm == null || p.perm.info.group == null) {
3291                        out.add(generatePermissionInfo(p, flags));
3292                    }
3293                } else {
3294                    if (p.perm != null && group.equals(p.perm.info.group)) {
3295                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3296                    }
3297                }
3298            }
3299            return new ParceledListSlice<>(out);
3300        }
3301    }
3302
3303    @Override
3304    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3305        // reader
3306        synchronized (mPackages) {
3307            return PackageParser.generatePermissionGroupInfo(
3308                    mPermissionGroups.get(name), flags);
3309        }
3310    }
3311
3312    @Override
3313    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3314        // reader
3315        synchronized (mPackages) {
3316            final int N = mPermissionGroups.size();
3317            ArrayList<PermissionGroupInfo> out
3318                    = new ArrayList<PermissionGroupInfo>(N);
3319            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3320                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3321            }
3322            return new ParceledListSlice<>(out);
3323        }
3324    }
3325
3326    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3327            int userId) {
3328        if (!sUserManager.exists(userId)) return null;
3329        PackageSetting ps = mSettings.mPackages.get(packageName);
3330        if (ps != null) {
3331            if (ps.pkg == null) {
3332                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3333                if (pInfo != null) {
3334                    return pInfo.applicationInfo;
3335                }
3336                return null;
3337            }
3338            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3339                    ps.readUserState(userId), userId);
3340        }
3341        return null;
3342    }
3343
3344    @Override
3345    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3346        if (!sUserManager.exists(userId)) return null;
3347        flags = updateFlagsForApplication(flags, userId, packageName);
3348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3349                false /* requireFullPermission */, false /* checkShell */, "get application info");
3350        // writer
3351        synchronized (mPackages) {
3352            PackageParser.Package p = mPackages.get(packageName);
3353            if (DEBUG_PACKAGE_INFO) Log.v(
3354                    TAG, "getApplicationInfo " + packageName
3355                    + ": " + p);
3356            if (p != null) {
3357                PackageSetting ps = mSettings.mPackages.get(packageName);
3358                if (ps == null) return null;
3359                // Note: isEnabledLP() does not apply here - always return info
3360                return PackageParser.generateApplicationInfo(
3361                        p, flags, ps.readUserState(userId), userId);
3362            }
3363            if ("android".equals(packageName)||"system".equals(packageName)) {
3364                return mAndroidApplication;
3365            }
3366            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3367                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3368            }
3369        }
3370        return null;
3371    }
3372
3373    @Override
3374    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3375            final IPackageDataObserver observer) {
3376        mContext.enforceCallingOrSelfPermission(
3377                android.Manifest.permission.CLEAR_APP_CACHE, null);
3378        // Queue up an async operation since clearing cache may take a little while.
3379        mHandler.post(new Runnable() {
3380            public void run() {
3381                mHandler.removeCallbacks(this);
3382                boolean success = true;
3383                synchronized (mInstallLock) {
3384                    try {
3385                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3386                    } catch (InstallerException e) {
3387                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3388                        success = false;
3389                    }
3390                }
3391                if (observer != null) {
3392                    try {
3393                        observer.onRemoveCompleted(null, success);
3394                    } catch (RemoteException e) {
3395                        Slog.w(TAG, "RemoveException when invoking call back");
3396                    }
3397                }
3398            }
3399        });
3400    }
3401
3402    @Override
3403    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3404            final IntentSender pi) {
3405        mContext.enforceCallingOrSelfPermission(
3406                android.Manifest.permission.CLEAR_APP_CACHE, null);
3407        // Queue up an async operation since clearing cache may take a little while.
3408        mHandler.post(new Runnable() {
3409            public void run() {
3410                mHandler.removeCallbacks(this);
3411                boolean success = true;
3412                synchronized (mInstallLock) {
3413                    try {
3414                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3415                    } catch (InstallerException e) {
3416                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3417                        success = false;
3418                    }
3419                }
3420                if(pi != null) {
3421                    try {
3422                        // Callback via pending intent
3423                        int code = success ? 1 : 0;
3424                        pi.sendIntent(null, code, null,
3425                                null, null);
3426                    } catch (SendIntentException e1) {
3427                        Slog.i(TAG, "Failed to send pending intent");
3428                    }
3429                }
3430            }
3431        });
3432    }
3433
3434    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3435        synchronized (mInstallLock) {
3436            try {
3437                mInstaller.freeCache(volumeUuid, freeStorageSize);
3438            } catch (InstallerException e) {
3439                throw new IOException("Failed to free enough space", e);
3440            }
3441        }
3442    }
3443
3444    /**
3445     * Update given flags based on encryption status of current user.
3446     */
3447    private int updateFlags(int flags, int userId) {
3448        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3449                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3450            // Caller expressed an explicit opinion about what encryption
3451            // aware/unaware components they want to see, so fall through and
3452            // give them what they want
3453        } else {
3454            // Caller expressed no opinion, so match based on user state
3455            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3456                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3457            } else {
3458                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3459            }
3460        }
3461        return flags;
3462    }
3463
3464    private UserManagerInternal getUserManagerInternal() {
3465        if (mUserManagerInternal == null) {
3466            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3467        }
3468        return mUserManagerInternal;
3469    }
3470
3471    /**
3472     * Update given flags when being used to request {@link PackageInfo}.
3473     */
3474    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3475        boolean triaged = true;
3476        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3477                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3478            // Caller is asking for component details, so they'd better be
3479            // asking for specific encryption matching behavior, or be triaged
3480            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3481                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3482                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3483                triaged = false;
3484            }
3485        }
3486        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3487                | PackageManager.MATCH_SYSTEM_ONLY
3488                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3489            triaged = false;
3490        }
3491        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3492            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3493                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3494        }
3495        return updateFlags(flags, userId);
3496    }
3497
3498    /**
3499     * Update given flags when being used to request {@link ApplicationInfo}.
3500     */
3501    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3502        return updateFlagsForPackage(flags, userId, cookie);
3503    }
3504
3505    /**
3506     * Update given flags when being used to request {@link ComponentInfo}.
3507     */
3508    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3509        if (cookie instanceof Intent) {
3510            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3511                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3512            }
3513        }
3514
3515        boolean triaged = true;
3516        // Caller is asking for component details, so they'd better be
3517        // asking for specific encryption matching behavior, or be triaged
3518        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3519                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3520                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3521            triaged = false;
3522        }
3523        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3524            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3525                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3526        }
3527
3528        return updateFlags(flags, userId);
3529    }
3530
3531    /**
3532     * Update given flags when being used to request {@link ResolveInfo}.
3533     */
3534    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3535        // Safe mode means we shouldn't match any third-party components
3536        if (mSafeMode) {
3537            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3538        }
3539
3540        return updateFlagsForComponent(flags, userId, cookie);
3541    }
3542
3543    @Override
3544    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        flags = updateFlagsForComponent(flags, userId, component);
3547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3548                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3549        synchronized (mPackages) {
3550            PackageParser.Activity a = mActivities.mActivities.get(component);
3551
3552            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3553            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3554                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3555                if (ps == null) return null;
3556                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3557                        userId);
3558            }
3559            if (mResolveComponentName.equals(component)) {
3560                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3561                        new PackageUserState(), userId);
3562            }
3563        }
3564        return null;
3565    }
3566
3567    @Override
3568    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3569            String resolvedType) {
3570        synchronized (mPackages) {
3571            if (component.equals(mResolveComponentName)) {
3572                // The resolver supports EVERYTHING!
3573                return true;
3574            }
3575            PackageParser.Activity a = mActivities.mActivities.get(component);
3576            if (a == null) {
3577                return false;
3578            }
3579            for (int i=0; i<a.intents.size(); i++) {
3580                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3581                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3582                    return true;
3583                }
3584            }
3585            return false;
3586        }
3587    }
3588
3589    @Override
3590    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3591        if (!sUserManager.exists(userId)) return null;
3592        flags = updateFlagsForComponent(flags, userId, component);
3593        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3594                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3595        synchronized (mPackages) {
3596            PackageParser.Activity a = mReceivers.mActivities.get(component);
3597            if (DEBUG_PACKAGE_INFO) Log.v(
3598                TAG, "getReceiverInfo " + component + ": " + a);
3599            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3600                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3601                if (ps == null) return null;
3602                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3603                        userId);
3604            }
3605        }
3606        return null;
3607    }
3608
3609    @Override
3610    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3611        if (!sUserManager.exists(userId)) return null;
3612        flags = updateFlagsForComponent(flags, userId, component);
3613        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3614                false /* requireFullPermission */, false /* checkShell */, "get service info");
3615        synchronized (mPackages) {
3616            PackageParser.Service s = mServices.mServices.get(component);
3617            if (DEBUG_PACKAGE_INFO) Log.v(
3618                TAG, "getServiceInfo " + component + ": " + s);
3619            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3620                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3621                if (ps == null) return null;
3622                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3623                        userId);
3624            }
3625        }
3626        return null;
3627    }
3628
3629    @Override
3630    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3631        if (!sUserManager.exists(userId)) return null;
3632        flags = updateFlagsForComponent(flags, userId, component);
3633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3634                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3635        synchronized (mPackages) {
3636            PackageParser.Provider p = mProviders.mProviders.get(component);
3637            if (DEBUG_PACKAGE_INFO) Log.v(
3638                TAG, "getProviderInfo " + component + ": " + p);
3639            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3640                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3641                if (ps == null) return null;
3642                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3643                        userId);
3644            }
3645        }
3646        return null;
3647    }
3648
3649    @Override
3650    public String[] getSystemSharedLibraryNames() {
3651        Set<String> libSet;
3652        synchronized (mPackages) {
3653            libSet = mSharedLibraries.keySet();
3654            int size = libSet.size();
3655            if (size > 0) {
3656                String[] libs = new String[size];
3657                libSet.toArray(libs);
3658                return libs;
3659            }
3660        }
3661        return null;
3662    }
3663
3664    @Override
3665    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3666        synchronized (mPackages) {
3667            return mServicesSystemSharedLibraryPackageName;
3668        }
3669    }
3670
3671    @Override
3672    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3673        synchronized (mPackages) {
3674            return mSharedSystemSharedLibraryPackageName;
3675        }
3676    }
3677
3678    @Override
3679    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3680        synchronized (mPackages) {
3681            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3682
3683            final FeatureInfo fi = new FeatureInfo();
3684            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3685                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3686            res.add(fi);
3687
3688            return new ParceledListSlice<>(res);
3689        }
3690    }
3691
3692    @Override
3693    public boolean hasSystemFeature(String name, int version) {
3694        synchronized (mPackages) {
3695            final FeatureInfo feat = mAvailableFeatures.get(name);
3696            if (feat == null) {
3697                return false;
3698            } else {
3699                return feat.version >= version;
3700            }
3701        }
3702    }
3703
3704    @Override
3705    public int checkPermission(String permName, String pkgName, int userId) {
3706        if (!sUserManager.exists(userId)) {
3707            return PackageManager.PERMISSION_DENIED;
3708        }
3709
3710        synchronized (mPackages) {
3711            final PackageParser.Package p = mPackages.get(pkgName);
3712            if (p != null && p.mExtras != null) {
3713                final PackageSetting ps = (PackageSetting) p.mExtras;
3714                final PermissionsState permissionsState = ps.getPermissionsState();
3715                if (permissionsState.hasPermission(permName, userId)) {
3716                    return PackageManager.PERMISSION_GRANTED;
3717                }
3718                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3719                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3720                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3721                    return PackageManager.PERMISSION_GRANTED;
3722                }
3723            }
3724        }
3725
3726        return PackageManager.PERMISSION_DENIED;
3727    }
3728
3729    @Override
3730    public int checkUidPermission(String permName, int uid) {
3731        final int userId = UserHandle.getUserId(uid);
3732
3733        if (!sUserManager.exists(userId)) {
3734            return PackageManager.PERMISSION_DENIED;
3735        }
3736
3737        synchronized (mPackages) {
3738            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3739            if (obj != null) {
3740                final SettingBase ps = (SettingBase) obj;
3741                final PermissionsState permissionsState = ps.getPermissionsState();
3742                if (permissionsState.hasPermission(permName, userId)) {
3743                    return PackageManager.PERMISSION_GRANTED;
3744                }
3745                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3746                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3747                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3748                    return PackageManager.PERMISSION_GRANTED;
3749                }
3750            } else {
3751                ArraySet<String> perms = mSystemPermissions.get(uid);
3752                if (perms != null) {
3753                    if (perms.contains(permName)) {
3754                        return PackageManager.PERMISSION_GRANTED;
3755                    }
3756                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3757                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3758                        return PackageManager.PERMISSION_GRANTED;
3759                    }
3760                }
3761            }
3762        }
3763
3764        return PackageManager.PERMISSION_DENIED;
3765    }
3766
3767    @Override
3768    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3769        if (UserHandle.getCallingUserId() != userId) {
3770            mContext.enforceCallingPermission(
3771                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3772                    "isPermissionRevokedByPolicy for user " + userId);
3773        }
3774
3775        if (checkPermission(permission, packageName, userId)
3776                == PackageManager.PERMISSION_GRANTED) {
3777            return false;
3778        }
3779
3780        final long identity = Binder.clearCallingIdentity();
3781        try {
3782            final int flags = getPermissionFlags(permission, packageName, userId);
3783            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3784        } finally {
3785            Binder.restoreCallingIdentity(identity);
3786        }
3787    }
3788
3789    @Override
3790    public String getPermissionControllerPackageName() {
3791        synchronized (mPackages) {
3792            return mRequiredInstallerPackage;
3793        }
3794    }
3795
3796    /**
3797     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3798     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3799     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3800     * @param message the message to log on security exception
3801     */
3802    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3803            boolean checkShell, String message) {
3804        if (userId < 0) {
3805            throw new IllegalArgumentException("Invalid userId " + userId);
3806        }
3807        if (checkShell) {
3808            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3809        }
3810        if (userId == UserHandle.getUserId(callingUid)) return;
3811        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3812            if (requireFullPermission) {
3813                mContext.enforceCallingOrSelfPermission(
3814                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3815            } else {
3816                try {
3817                    mContext.enforceCallingOrSelfPermission(
3818                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3819                } catch (SecurityException se) {
3820                    mContext.enforceCallingOrSelfPermission(
3821                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3822                }
3823            }
3824        }
3825    }
3826
3827    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3828        if (callingUid == Process.SHELL_UID) {
3829            if (userHandle >= 0
3830                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3831                throw new SecurityException("Shell does not have permission to access user "
3832                        + userHandle);
3833            } else if (userHandle < 0) {
3834                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3835                        + Debug.getCallers(3));
3836            }
3837        }
3838    }
3839
3840    private BasePermission findPermissionTreeLP(String permName) {
3841        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3842            if (permName.startsWith(bp.name) &&
3843                    permName.length() > bp.name.length() &&
3844                    permName.charAt(bp.name.length()) == '.') {
3845                return bp;
3846            }
3847        }
3848        return null;
3849    }
3850
3851    private BasePermission checkPermissionTreeLP(String permName) {
3852        if (permName != null) {
3853            BasePermission bp = findPermissionTreeLP(permName);
3854            if (bp != null) {
3855                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3856                    return bp;
3857                }
3858                throw new SecurityException("Calling uid "
3859                        + Binder.getCallingUid()
3860                        + " is not allowed to add to permission tree "
3861                        + bp.name + " owned by uid " + bp.uid);
3862            }
3863        }
3864        throw new SecurityException("No permission tree found for " + permName);
3865    }
3866
3867    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3868        if (s1 == null) {
3869            return s2 == null;
3870        }
3871        if (s2 == null) {
3872            return false;
3873        }
3874        if (s1.getClass() != s2.getClass()) {
3875            return false;
3876        }
3877        return s1.equals(s2);
3878    }
3879
3880    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3881        if (pi1.icon != pi2.icon) return false;
3882        if (pi1.logo != pi2.logo) return false;
3883        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3884        if (!compareStrings(pi1.name, pi2.name)) return false;
3885        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3886        // We'll take care of setting this one.
3887        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3888        // These are not currently stored in settings.
3889        //if (!compareStrings(pi1.group, pi2.group)) return false;
3890        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3891        //if (pi1.labelRes != pi2.labelRes) return false;
3892        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3893        return true;
3894    }
3895
3896    int permissionInfoFootprint(PermissionInfo info) {
3897        int size = info.name.length();
3898        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3899        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3900        return size;
3901    }
3902
3903    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3904        int size = 0;
3905        for (BasePermission perm : mSettings.mPermissions.values()) {
3906            if (perm.uid == tree.uid) {
3907                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3908            }
3909        }
3910        return size;
3911    }
3912
3913    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3914        // We calculate the max size of permissions defined by this uid and throw
3915        // if that plus the size of 'info' would exceed our stated maximum.
3916        if (tree.uid != Process.SYSTEM_UID) {
3917            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3918            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3919                throw new SecurityException("Permission tree size cap exceeded");
3920            }
3921        }
3922    }
3923
3924    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3925        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3926            throw new SecurityException("Label must be specified in permission");
3927        }
3928        BasePermission tree = checkPermissionTreeLP(info.name);
3929        BasePermission bp = mSettings.mPermissions.get(info.name);
3930        boolean added = bp == null;
3931        boolean changed = true;
3932        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3933        if (added) {
3934            enforcePermissionCapLocked(info, tree);
3935            bp = new BasePermission(info.name, tree.sourcePackage,
3936                    BasePermission.TYPE_DYNAMIC);
3937        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3938            throw new SecurityException(
3939                    "Not allowed to modify non-dynamic permission "
3940                    + info.name);
3941        } else {
3942            if (bp.protectionLevel == fixedLevel
3943                    && bp.perm.owner.equals(tree.perm.owner)
3944                    && bp.uid == tree.uid
3945                    && comparePermissionInfos(bp.perm.info, info)) {
3946                changed = false;
3947            }
3948        }
3949        bp.protectionLevel = fixedLevel;
3950        info = new PermissionInfo(info);
3951        info.protectionLevel = fixedLevel;
3952        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3953        bp.perm.info.packageName = tree.perm.info.packageName;
3954        bp.uid = tree.uid;
3955        if (added) {
3956            mSettings.mPermissions.put(info.name, bp);
3957        }
3958        if (changed) {
3959            if (!async) {
3960                mSettings.writeLPr();
3961            } else {
3962                scheduleWriteSettingsLocked();
3963            }
3964        }
3965        return added;
3966    }
3967
3968    @Override
3969    public boolean addPermission(PermissionInfo info) {
3970        synchronized (mPackages) {
3971            return addPermissionLocked(info, false);
3972        }
3973    }
3974
3975    @Override
3976    public boolean addPermissionAsync(PermissionInfo info) {
3977        synchronized (mPackages) {
3978            return addPermissionLocked(info, true);
3979        }
3980    }
3981
3982    @Override
3983    public void removePermission(String name) {
3984        synchronized (mPackages) {
3985            checkPermissionTreeLP(name);
3986            BasePermission bp = mSettings.mPermissions.get(name);
3987            if (bp != null) {
3988                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3989                    throw new SecurityException(
3990                            "Not allowed to modify non-dynamic permission "
3991                            + name);
3992                }
3993                mSettings.mPermissions.remove(name);
3994                mSettings.writeLPr();
3995            }
3996        }
3997    }
3998
3999    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4000            BasePermission bp) {
4001        int index = pkg.requestedPermissions.indexOf(bp.name);
4002        if (index == -1) {
4003            throw new SecurityException("Package " + pkg.packageName
4004                    + " has not requested permission " + bp.name);
4005        }
4006        if (!bp.isRuntime() && !bp.isDevelopment()) {
4007            throw new SecurityException("Permission " + bp.name
4008                    + " is not a changeable permission type");
4009        }
4010    }
4011
4012    @Override
4013    public void grantRuntimePermission(String packageName, String name, final int userId) {
4014        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4015    }
4016
4017    private void grantRuntimePermission(String packageName, String name, final int userId,
4018            boolean overridePolicy) {
4019        if (!sUserManager.exists(userId)) {
4020            Log.e(TAG, "No such user:" + userId);
4021            return;
4022        }
4023
4024        mContext.enforceCallingOrSelfPermission(
4025                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4026                "grantRuntimePermission");
4027
4028        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4029                true /* requireFullPermission */, true /* checkShell */,
4030                "grantRuntimePermission");
4031
4032        final int uid;
4033        final SettingBase sb;
4034
4035        synchronized (mPackages) {
4036            final PackageParser.Package pkg = mPackages.get(packageName);
4037            if (pkg == null) {
4038                throw new IllegalArgumentException("Unknown package: " + packageName);
4039            }
4040
4041            final BasePermission bp = mSettings.mPermissions.get(name);
4042            if (bp == null) {
4043                throw new IllegalArgumentException("Unknown permission: " + name);
4044            }
4045
4046            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4047
4048            // If a permission review is required for legacy apps we represent
4049            // their permissions as always granted runtime ones since we need
4050            // to keep the review required permission flag per user while an
4051            // install permission's state is shared across all users.
4052            if (mPermissionReviewRequired
4053                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4054                    && bp.isRuntime()) {
4055                return;
4056            }
4057
4058            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4059            sb = (SettingBase) pkg.mExtras;
4060            if (sb == null) {
4061                throw new IllegalArgumentException("Unknown package: " + packageName);
4062            }
4063
4064            final PermissionsState permissionsState = sb.getPermissionsState();
4065
4066            final int flags = permissionsState.getPermissionFlags(name, userId);
4067            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4068                throw new SecurityException("Cannot grant system fixed permission "
4069                        + name + " for package " + packageName);
4070            }
4071            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4072                throw new SecurityException("Cannot grant policy fixed permission "
4073                        + name + " for package " + packageName);
4074            }
4075
4076            if (bp.isDevelopment()) {
4077                // Development permissions must be handled specially, since they are not
4078                // normal runtime permissions.  For now they apply to all users.
4079                if (permissionsState.grantInstallPermission(bp) !=
4080                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4081                    scheduleWriteSettingsLocked();
4082                }
4083                return;
4084            }
4085
4086            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4087                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4088                return;
4089            }
4090
4091            final int result = permissionsState.grantRuntimePermission(bp, userId);
4092            switch (result) {
4093                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4094                    return;
4095                }
4096
4097                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4098                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4099                    mHandler.post(new Runnable() {
4100                        @Override
4101                        public void run() {
4102                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4103                        }
4104                    });
4105                }
4106                break;
4107            }
4108
4109            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4110
4111            // Not critical if that is lost - app has to request again.
4112            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4113        }
4114
4115        // Only need to do this if user is initialized. Otherwise it's a new user
4116        // and there are no processes running as the user yet and there's no need
4117        // to make an expensive call to remount processes for the changed permissions.
4118        if (READ_EXTERNAL_STORAGE.equals(name)
4119                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4120            final long token = Binder.clearCallingIdentity();
4121            try {
4122                if (sUserManager.isInitialized(userId)) {
4123                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4124                            MountServiceInternal.class);
4125                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4126                }
4127            } finally {
4128                Binder.restoreCallingIdentity(token);
4129            }
4130        }
4131    }
4132
4133    @Override
4134    public void revokeRuntimePermission(String packageName, String name, int userId) {
4135        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4136    }
4137
4138    private void revokeRuntimePermission(String packageName, String name, int userId,
4139            boolean overridePolicy) {
4140        if (!sUserManager.exists(userId)) {
4141            Log.e(TAG, "No such user:" + userId);
4142            return;
4143        }
4144
4145        mContext.enforceCallingOrSelfPermission(
4146                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4147                "revokeRuntimePermission");
4148
4149        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4150                true /* requireFullPermission */, true /* checkShell */,
4151                "revokeRuntimePermission");
4152
4153        final int appId;
4154
4155        synchronized (mPackages) {
4156            final PackageParser.Package pkg = mPackages.get(packageName);
4157            if (pkg == null) {
4158                throw new IllegalArgumentException("Unknown package: " + packageName);
4159            }
4160
4161            final BasePermission bp = mSettings.mPermissions.get(name);
4162            if (bp == null) {
4163                throw new IllegalArgumentException("Unknown permission: " + name);
4164            }
4165
4166            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4167
4168            // If a permission review is required for legacy apps we represent
4169            // their permissions as always granted runtime ones since we need
4170            // to keep the review required permission flag per user while an
4171            // install permission's state is shared across all users.
4172            if (mPermissionReviewRequired
4173                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4174                    && bp.isRuntime()) {
4175                return;
4176            }
4177
4178            SettingBase sb = (SettingBase) pkg.mExtras;
4179            if (sb == null) {
4180                throw new IllegalArgumentException("Unknown package: " + packageName);
4181            }
4182
4183            final PermissionsState permissionsState = sb.getPermissionsState();
4184
4185            final int flags = permissionsState.getPermissionFlags(name, userId);
4186            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4187                throw new SecurityException("Cannot revoke system fixed permission "
4188                        + name + " for package " + packageName);
4189            }
4190            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4191                throw new SecurityException("Cannot revoke policy fixed permission "
4192                        + name + " for package " + packageName);
4193            }
4194
4195            if (bp.isDevelopment()) {
4196                // Development permissions must be handled specially, since they are not
4197                // normal runtime permissions.  For now they apply to all users.
4198                if (permissionsState.revokeInstallPermission(bp) !=
4199                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4200                    scheduleWriteSettingsLocked();
4201                }
4202                return;
4203            }
4204
4205            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4206                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4207                return;
4208            }
4209
4210            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4211
4212            // Critical, after this call app should never have the permission.
4213            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4214
4215            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4216        }
4217
4218        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4219    }
4220
4221    @Override
4222    public void resetRuntimePermissions() {
4223        mContext.enforceCallingOrSelfPermission(
4224                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4225                "revokeRuntimePermission");
4226
4227        int callingUid = Binder.getCallingUid();
4228        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4229            mContext.enforceCallingOrSelfPermission(
4230                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4231                    "resetRuntimePermissions");
4232        }
4233
4234        synchronized (mPackages) {
4235            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4236            for (int userId : UserManagerService.getInstance().getUserIds()) {
4237                final int packageCount = mPackages.size();
4238                for (int i = 0; i < packageCount; i++) {
4239                    PackageParser.Package pkg = mPackages.valueAt(i);
4240                    if (!(pkg.mExtras instanceof PackageSetting)) {
4241                        continue;
4242                    }
4243                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4244                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4245                }
4246            }
4247        }
4248    }
4249
4250    @Override
4251    public int getPermissionFlags(String name, String packageName, int userId) {
4252        if (!sUserManager.exists(userId)) {
4253            return 0;
4254        }
4255
4256        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4257
4258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4259                true /* requireFullPermission */, false /* checkShell */,
4260                "getPermissionFlags");
4261
4262        synchronized (mPackages) {
4263            final PackageParser.Package pkg = mPackages.get(packageName);
4264            if (pkg == null) {
4265                return 0;
4266            }
4267
4268            final BasePermission bp = mSettings.mPermissions.get(name);
4269            if (bp == null) {
4270                return 0;
4271            }
4272
4273            SettingBase sb = (SettingBase) pkg.mExtras;
4274            if (sb == null) {
4275                return 0;
4276            }
4277
4278            PermissionsState permissionsState = sb.getPermissionsState();
4279            return permissionsState.getPermissionFlags(name, userId);
4280        }
4281    }
4282
4283    @Override
4284    public void updatePermissionFlags(String name, String packageName, int flagMask,
4285            int flagValues, int userId) {
4286        if (!sUserManager.exists(userId)) {
4287            return;
4288        }
4289
4290        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4291
4292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4293                true /* requireFullPermission */, true /* checkShell */,
4294                "updatePermissionFlags");
4295
4296        // Only the system can change these flags and nothing else.
4297        if (getCallingUid() != Process.SYSTEM_UID) {
4298            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4299            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4300            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4301            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4302            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4303        }
4304
4305        synchronized (mPackages) {
4306            final PackageParser.Package pkg = mPackages.get(packageName);
4307            if (pkg == null) {
4308                throw new IllegalArgumentException("Unknown package: " + packageName);
4309            }
4310
4311            final BasePermission bp = mSettings.mPermissions.get(name);
4312            if (bp == null) {
4313                throw new IllegalArgumentException("Unknown permission: " + name);
4314            }
4315
4316            SettingBase sb = (SettingBase) pkg.mExtras;
4317            if (sb == null) {
4318                throw new IllegalArgumentException("Unknown package: " + packageName);
4319            }
4320
4321            PermissionsState permissionsState = sb.getPermissionsState();
4322
4323            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4324
4325            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4326                // Install and runtime permissions are stored in different places,
4327                // so figure out what permission changed and persist the change.
4328                if (permissionsState.getInstallPermissionState(name) != null) {
4329                    scheduleWriteSettingsLocked();
4330                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4331                        || hadState) {
4332                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4333                }
4334            }
4335        }
4336    }
4337
4338    /**
4339     * Update the permission flags for all packages and runtime permissions of a user in order
4340     * to allow device or profile owner to remove POLICY_FIXED.
4341     */
4342    @Override
4343    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4344        if (!sUserManager.exists(userId)) {
4345            return;
4346        }
4347
4348        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4349
4350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4351                true /* requireFullPermission */, true /* checkShell */,
4352                "updatePermissionFlagsForAllApps");
4353
4354        // Only the system can change system fixed flags.
4355        if (getCallingUid() != Process.SYSTEM_UID) {
4356            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4357            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4358        }
4359
4360        synchronized (mPackages) {
4361            boolean changed = false;
4362            final int packageCount = mPackages.size();
4363            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4364                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4365                SettingBase sb = (SettingBase) pkg.mExtras;
4366                if (sb == null) {
4367                    continue;
4368                }
4369                PermissionsState permissionsState = sb.getPermissionsState();
4370                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4371                        userId, flagMask, flagValues);
4372            }
4373            if (changed) {
4374                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4375            }
4376        }
4377    }
4378
4379    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4380        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4381                != PackageManager.PERMISSION_GRANTED
4382            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4383                != PackageManager.PERMISSION_GRANTED) {
4384            throw new SecurityException(message + " requires "
4385                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4386                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4387        }
4388    }
4389
4390    @Override
4391    public boolean shouldShowRequestPermissionRationale(String permissionName,
4392            String packageName, int userId) {
4393        if (UserHandle.getCallingUserId() != userId) {
4394            mContext.enforceCallingPermission(
4395                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4396                    "canShowRequestPermissionRationale for user " + userId);
4397        }
4398
4399        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4400        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4401            return false;
4402        }
4403
4404        if (checkPermission(permissionName, packageName, userId)
4405                == PackageManager.PERMISSION_GRANTED) {
4406            return false;
4407        }
4408
4409        final int flags;
4410
4411        final long identity = Binder.clearCallingIdentity();
4412        try {
4413            flags = getPermissionFlags(permissionName,
4414                    packageName, userId);
4415        } finally {
4416            Binder.restoreCallingIdentity(identity);
4417        }
4418
4419        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4420                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4421                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4422
4423        if ((flags & fixedFlags) != 0) {
4424            return false;
4425        }
4426
4427        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4428    }
4429
4430    @Override
4431    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4432        mContext.enforceCallingOrSelfPermission(
4433                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4434                "addOnPermissionsChangeListener");
4435
4436        synchronized (mPackages) {
4437            mOnPermissionChangeListeners.addListenerLocked(listener);
4438        }
4439    }
4440
4441    @Override
4442    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4443        synchronized (mPackages) {
4444            mOnPermissionChangeListeners.removeListenerLocked(listener);
4445        }
4446    }
4447
4448    @Override
4449    public boolean isProtectedBroadcast(String actionName) {
4450        synchronized (mPackages) {
4451            if (mProtectedBroadcasts.contains(actionName)) {
4452                return true;
4453            } else if (actionName != null) {
4454                // TODO: remove these terrible hacks
4455                if (actionName.startsWith("android.net.netmon.lingerExpired")
4456                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4457                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4458                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4459                    return true;
4460                }
4461            }
4462        }
4463        return false;
4464    }
4465
4466    @Override
4467    public int checkSignatures(String pkg1, String pkg2) {
4468        synchronized (mPackages) {
4469            final PackageParser.Package p1 = mPackages.get(pkg1);
4470            final PackageParser.Package p2 = mPackages.get(pkg2);
4471            if (p1 == null || p1.mExtras == null
4472                    || p2 == null || p2.mExtras == null) {
4473                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4474            }
4475            return compareSignatures(p1.mSignatures, p2.mSignatures);
4476        }
4477    }
4478
4479    @Override
4480    public int checkUidSignatures(int uid1, int uid2) {
4481        // Map to base uids.
4482        uid1 = UserHandle.getAppId(uid1);
4483        uid2 = UserHandle.getAppId(uid2);
4484        // reader
4485        synchronized (mPackages) {
4486            Signature[] s1;
4487            Signature[] s2;
4488            Object obj = mSettings.getUserIdLPr(uid1);
4489            if (obj != null) {
4490                if (obj instanceof SharedUserSetting) {
4491                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4492                } else if (obj instanceof PackageSetting) {
4493                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4494                } else {
4495                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4496                }
4497            } else {
4498                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4499            }
4500            obj = mSettings.getUserIdLPr(uid2);
4501            if (obj != null) {
4502                if (obj instanceof SharedUserSetting) {
4503                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4504                } else if (obj instanceof PackageSetting) {
4505                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4506                } else {
4507                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4508                }
4509            } else {
4510                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4511            }
4512            return compareSignatures(s1, s2);
4513        }
4514    }
4515
4516    /**
4517     * This method should typically only be used when granting or revoking
4518     * permissions, since the app may immediately restart after this call.
4519     * <p>
4520     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4521     * guard your work against the app being relaunched.
4522     */
4523    private void killUid(int appId, int userId, String reason) {
4524        final long identity = Binder.clearCallingIdentity();
4525        try {
4526            IActivityManager am = ActivityManagerNative.getDefault();
4527            if (am != null) {
4528                try {
4529                    am.killUid(appId, userId, reason);
4530                } catch (RemoteException e) {
4531                    /* ignore - same process */
4532                }
4533            }
4534        } finally {
4535            Binder.restoreCallingIdentity(identity);
4536        }
4537    }
4538
4539    /**
4540     * Compares two sets of signatures. Returns:
4541     * <br />
4542     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4543     * <br />
4544     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4545     * <br />
4546     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4547     * <br />
4548     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4551     */
4552    static int compareSignatures(Signature[] s1, Signature[] s2) {
4553        if (s1 == null) {
4554            return s2 == null
4555                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4556                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4557        }
4558
4559        if (s2 == null) {
4560            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4561        }
4562
4563        if (s1.length != s2.length) {
4564            return PackageManager.SIGNATURE_NO_MATCH;
4565        }
4566
4567        // Since both signature sets are of size 1, we can compare without HashSets.
4568        if (s1.length == 1) {
4569            return s1[0].equals(s2[0]) ?
4570                    PackageManager.SIGNATURE_MATCH :
4571                    PackageManager.SIGNATURE_NO_MATCH;
4572        }
4573
4574        ArraySet<Signature> set1 = new ArraySet<Signature>();
4575        for (Signature sig : s1) {
4576            set1.add(sig);
4577        }
4578        ArraySet<Signature> set2 = new ArraySet<Signature>();
4579        for (Signature sig : s2) {
4580            set2.add(sig);
4581        }
4582        // Make sure s2 contains all signatures in s1.
4583        if (set1.equals(set2)) {
4584            return PackageManager.SIGNATURE_MATCH;
4585        }
4586        return PackageManager.SIGNATURE_NO_MATCH;
4587    }
4588
4589    /**
4590     * If the database version for this type of package (internal storage or
4591     * external storage) is less than the version where package signatures
4592     * were updated, return true.
4593     */
4594    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4595        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4596        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4597    }
4598
4599    /**
4600     * Used for backward compatibility to make sure any packages with
4601     * certificate chains get upgraded to the new style. {@code existingSigs}
4602     * will be in the old format (since they were stored on disk from before the
4603     * system upgrade) and {@code scannedSigs} will be in the newer format.
4604     */
4605    private int compareSignaturesCompat(PackageSignatures existingSigs,
4606            PackageParser.Package scannedPkg) {
4607        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4608            return PackageManager.SIGNATURE_NO_MATCH;
4609        }
4610
4611        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4612        for (Signature sig : existingSigs.mSignatures) {
4613            existingSet.add(sig);
4614        }
4615        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4616        for (Signature sig : scannedPkg.mSignatures) {
4617            try {
4618                Signature[] chainSignatures = sig.getChainSignatures();
4619                for (Signature chainSig : chainSignatures) {
4620                    scannedCompatSet.add(chainSig);
4621                }
4622            } catch (CertificateEncodingException e) {
4623                scannedCompatSet.add(sig);
4624            }
4625        }
4626        /*
4627         * Make sure the expanded scanned set contains all signatures in the
4628         * existing one.
4629         */
4630        if (scannedCompatSet.equals(existingSet)) {
4631            // Migrate the old signatures to the new scheme.
4632            existingSigs.assignSignatures(scannedPkg.mSignatures);
4633            // The new KeySets will be re-added later in the scanning process.
4634            synchronized (mPackages) {
4635                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4636            }
4637            return PackageManager.SIGNATURE_MATCH;
4638        }
4639        return PackageManager.SIGNATURE_NO_MATCH;
4640    }
4641
4642    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4643        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4644        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4645    }
4646
4647    private int compareSignaturesRecover(PackageSignatures existingSigs,
4648            PackageParser.Package scannedPkg) {
4649        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4650            return PackageManager.SIGNATURE_NO_MATCH;
4651        }
4652
4653        String msg = null;
4654        try {
4655            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4656                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4657                        + scannedPkg.packageName);
4658                return PackageManager.SIGNATURE_MATCH;
4659            }
4660        } catch (CertificateException e) {
4661            msg = e.getMessage();
4662        }
4663
4664        logCriticalInfo(Log.INFO,
4665                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4666        return PackageManager.SIGNATURE_NO_MATCH;
4667    }
4668
4669    @Override
4670    public List<String> getAllPackages() {
4671        synchronized (mPackages) {
4672            return new ArrayList<String>(mPackages.keySet());
4673        }
4674    }
4675
4676    @Override
4677    public String[] getPackagesForUid(int uid) {
4678        final int userId = UserHandle.getUserId(uid);
4679        uid = UserHandle.getAppId(uid);
4680        // reader
4681        synchronized (mPackages) {
4682            Object obj = mSettings.getUserIdLPr(uid);
4683            if (obj instanceof SharedUserSetting) {
4684                final SharedUserSetting sus = (SharedUserSetting) obj;
4685                final int N = sus.packages.size();
4686                String[] res = new String[N];
4687                final Iterator<PackageSetting> it = sus.packages.iterator();
4688                int i = 0;
4689                while (it.hasNext()) {
4690                    PackageSetting ps = it.next();
4691                    if (ps.getInstalled(userId)) {
4692                        res[i++] = ps.name;
4693                    } else {
4694                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4695                    }
4696                }
4697                return res;
4698            } else if (obj instanceof PackageSetting) {
4699                final PackageSetting ps = (PackageSetting) obj;
4700                return new String[] { ps.name };
4701            }
4702        }
4703        return null;
4704    }
4705
4706    @Override
4707    public String getNameForUid(int uid) {
4708        // reader
4709        synchronized (mPackages) {
4710            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4711            if (obj instanceof SharedUserSetting) {
4712                final SharedUserSetting sus = (SharedUserSetting) obj;
4713                return sus.name + ":" + sus.userId;
4714            } else if (obj instanceof PackageSetting) {
4715                final PackageSetting ps = (PackageSetting) obj;
4716                return ps.name;
4717            }
4718        }
4719        return null;
4720    }
4721
4722    @Override
4723    public int getUidForSharedUser(String sharedUserName) {
4724        if(sharedUserName == null) {
4725            return -1;
4726        }
4727        // reader
4728        synchronized (mPackages) {
4729            SharedUserSetting suid;
4730            try {
4731                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4732                if (suid != null) {
4733                    return suid.userId;
4734                }
4735            } catch (PackageManagerException ignore) {
4736                // can't happen, but, still need to catch it
4737            }
4738            return -1;
4739        }
4740    }
4741
4742    @Override
4743    public int getFlagsForUid(int uid) {
4744        synchronized (mPackages) {
4745            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4746            if (obj instanceof SharedUserSetting) {
4747                final SharedUserSetting sus = (SharedUserSetting) obj;
4748                return sus.pkgFlags;
4749            } else if (obj instanceof PackageSetting) {
4750                final PackageSetting ps = (PackageSetting) obj;
4751                return ps.pkgFlags;
4752            }
4753        }
4754        return 0;
4755    }
4756
4757    @Override
4758    public int getPrivateFlagsForUid(int uid) {
4759        synchronized (mPackages) {
4760            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4761            if (obj instanceof SharedUserSetting) {
4762                final SharedUserSetting sus = (SharedUserSetting) obj;
4763                return sus.pkgPrivateFlags;
4764            } else if (obj instanceof PackageSetting) {
4765                final PackageSetting ps = (PackageSetting) obj;
4766                return ps.pkgPrivateFlags;
4767            }
4768        }
4769        return 0;
4770    }
4771
4772    @Override
4773    public boolean isUidPrivileged(int uid) {
4774        uid = UserHandle.getAppId(uid);
4775        // reader
4776        synchronized (mPackages) {
4777            Object obj = mSettings.getUserIdLPr(uid);
4778            if (obj instanceof SharedUserSetting) {
4779                final SharedUserSetting sus = (SharedUserSetting) obj;
4780                final Iterator<PackageSetting> it = sus.packages.iterator();
4781                while (it.hasNext()) {
4782                    if (it.next().isPrivileged()) {
4783                        return true;
4784                    }
4785                }
4786            } else if (obj instanceof PackageSetting) {
4787                final PackageSetting ps = (PackageSetting) obj;
4788                return ps.isPrivileged();
4789            }
4790        }
4791        return false;
4792    }
4793
4794    @Override
4795    public String[] getAppOpPermissionPackages(String permissionName) {
4796        synchronized (mPackages) {
4797            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4798            if (pkgs == null) {
4799                return null;
4800            }
4801            return pkgs.toArray(new String[pkgs.size()]);
4802        }
4803    }
4804
4805    @Override
4806    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4807            int flags, int userId) {
4808        try {
4809            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4810
4811            if (!sUserManager.exists(userId)) return null;
4812            flags = updateFlagsForResolve(flags, userId, intent);
4813            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4814                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4815
4816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4817            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4818                    flags, userId);
4819            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4820
4821            final ResolveInfo bestChoice =
4822                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4823            return bestChoice;
4824        } finally {
4825            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4826        }
4827    }
4828
4829    @Override
4830    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4831            IntentFilter filter, int match, ComponentName activity) {
4832        final int userId = UserHandle.getCallingUserId();
4833        if (DEBUG_PREFERRED) {
4834            Log.v(TAG, "setLastChosenActivity intent=" + intent
4835                + " resolvedType=" + resolvedType
4836                + " flags=" + flags
4837                + " filter=" + filter
4838                + " match=" + match
4839                + " activity=" + activity);
4840            filter.dump(new PrintStreamPrinter(System.out), "    ");
4841        }
4842        intent.setComponent(null);
4843        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4844                userId);
4845        // Find any earlier preferred or last chosen entries and nuke them
4846        findPreferredActivity(intent, resolvedType,
4847                flags, query, 0, false, true, false, userId);
4848        // Add the new activity as the last chosen for this filter
4849        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4850                "Setting last chosen");
4851    }
4852
4853    @Override
4854    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4855        final int userId = UserHandle.getCallingUserId();
4856        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4857        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4858                userId);
4859        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4860                false, false, false, userId);
4861    }
4862
4863    private boolean isEphemeralDisabled() {
4864        // ephemeral apps have been disabled across the board
4865        if (DISABLE_EPHEMERAL_APPS) {
4866            return true;
4867        }
4868        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4869        if (!mSystemReady) {
4870            return true;
4871        }
4872        // we can't get a content resolver until the system is ready; these checks must happen last
4873        final ContentResolver resolver = mContext.getContentResolver();
4874        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4875            return true;
4876        }
4877        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4878    }
4879
4880    private boolean isEphemeralAllowed(
4881            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4882            boolean skipPackageCheck) {
4883        // Short circuit and return early if possible.
4884        if (isEphemeralDisabled()) {
4885            return false;
4886        }
4887        final int callingUser = UserHandle.getCallingUserId();
4888        if (callingUser != UserHandle.USER_SYSTEM) {
4889            return false;
4890        }
4891        if (mEphemeralResolverConnection == null) {
4892            return false;
4893        }
4894        if (intent.getComponent() != null) {
4895            return false;
4896        }
4897        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4898            return false;
4899        }
4900        if (!skipPackageCheck && intent.getPackage() != null) {
4901            return false;
4902        }
4903        final boolean isWebUri = hasWebURI(intent);
4904        if (!isWebUri || intent.getData().getHost() == null) {
4905            return false;
4906        }
4907        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4908        synchronized (mPackages) {
4909            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4910            for (int n = 0; n < count; n++) {
4911                ResolveInfo info = resolvedActivities.get(n);
4912                String packageName = info.activityInfo.packageName;
4913                PackageSetting ps = mSettings.mPackages.get(packageName);
4914                if (ps != null) {
4915                    // Try to get the status from User settings first
4916                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4917                    int status = (int) (packedStatus >> 32);
4918                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4919                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4920                        if (DEBUG_EPHEMERAL) {
4921                            Slog.v(TAG, "DENY ephemeral apps;"
4922                                + " pkg: " + packageName + ", status: " + status);
4923                        }
4924                        return false;
4925                    }
4926                }
4927            }
4928        }
4929        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4930        return true;
4931    }
4932
4933    private static EphemeralResolveInfo getEphemeralResolveInfo(
4934            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4935            String resolvedType, int userId, String packageName) {
4936        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4937                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4938        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4939                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4940        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4941                ephemeralPrefixCount);
4942        final int[] shaPrefix = digest.getDigestPrefix();
4943        final byte[][] digestBytes = digest.getDigestBytes();
4944        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4945                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4946        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4947            // No hash prefix match; there are no ephemeral apps for this domain.
4948            return null;
4949        }
4950
4951        // Go in reverse order so we match the narrowest scope first.
4952        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4953            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4954                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4955                    continue;
4956                }
4957                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4958                // No filters; this should never happen.
4959                if (filters.isEmpty()) {
4960                    continue;
4961                }
4962                if (packageName != null
4963                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4964                    continue;
4965                }
4966                // We have a domain match; resolve the filters to see if anything matches.
4967                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4968                for (int j = filters.size() - 1; j >= 0; --j) {
4969                    final EphemeralResolveIntentInfo intentInfo =
4970                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4971                    ephemeralResolver.addFilter(intentInfo);
4972                }
4973                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4974                        intent, resolvedType, false /*defaultOnly*/, userId);
4975                if (!matchedResolveInfoList.isEmpty()) {
4976                    return matchedResolveInfoList.get(0);
4977                }
4978            }
4979        }
4980        // Hash or filter mis-match; no ephemeral apps for this domain.
4981        return null;
4982    }
4983
4984    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4985            int flags, List<ResolveInfo> query, int userId) {
4986        if (query != null) {
4987            final int N = query.size();
4988            if (N == 1) {
4989                return query.get(0);
4990            } else if (N > 1) {
4991                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4992                // If there is more than one activity with the same priority,
4993                // then let the user decide between them.
4994                ResolveInfo r0 = query.get(0);
4995                ResolveInfo r1 = query.get(1);
4996                if (DEBUG_INTENT_MATCHING || debug) {
4997                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4998                            + r1.activityInfo.name + "=" + r1.priority);
4999                }
5000                // If the first activity has a higher priority, or a different
5001                // default, then it is always desirable to pick it.
5002                if (r0.priority != r1.priority
5003                        || r0.preferredOrder != r1.preferredOrder
5004                        || r0.isDefault != r1.isDefault) {
5005                    return query.get(0);
5006                }
5007                // If we have saved a preference for a preferred activity for
5008                // this Intent, use that.
5009                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5010                        flags, query, r0.priority, true, false, debug, userId);
5011                if (ri != null) {
5012                    return ri;
5013                }
5014                ri = new ResolveInfo(mResolveInfo);
5015                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5016                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5017                // If all of the options come from the same package, show the application's
5018                // label and icon instead of the generic resolver's.
5019                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5020                // and then throw away the ResolveInfo itself, meaning that the caller loses
5021                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5022                // a fallback for this case; we only set the target package's resources on
5023                // the ResolveInfo, not the ActivityInfo.
5024                final String intentPackage = intent.getPackage();
5025                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5026                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5027                    ri.resolvePackageName = intentPackage;
5028                    if (userNeedsBadging(userId)) {
5029                        ri.noResourceId = true;
5030                    } else {
5031                        ri.icon = appi.icon;
5032                    }
5033                    ri.iconResourceId = appi.icon;
5034                    ri.labelRes = appi.labelRes;
5035                }
5036                ri.activityInfo.applicationInfo = new ApplicationInfo(
5037                        ri.activityInfo.applicationInfo);
5038                if (userId != 0) {
5039                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5040                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5041                }
5042                // Make sure that the resolver is displayable in car mode
5043                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5044                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5045                return ri;
5046            }
5047        }
5048        return null;
5049    }
5050
5051    /**
5052     * Return true if the given list is not empty and all of its contents have
5053     * an activityInfo with the given package name.
5054     */
5055    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5056        if (ArrayUtils.isEmpty(list)) {
5057            return false;
5058        }
5059        for (int i = 0, N = list.size(); i < N; i++) {
5060            final ResolveInfo ri = list.get(i);
5061            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5062            if (ai == null || !packageName.equals(ai.packageName)) {
5063                return false;
5064            }
5065        }
5066        return true;
5067    }
5068
5069    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5070            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5071        final int N = query.size();
5072        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5073                .get(userId);
5074        // Get the list of persistent preferred activities that handle the intent
5075        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5076        List<PersistentPreferredActivity> pprefs = ppir != null
5077                ? ppir.queryIntent(intent, resolvedType,
5078                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5079                : null;
5080        if (pprefs != null && pprefs.size() > 0) {
5081            final int M = pprefs.size();
5082            for (int i=0; i<M; i++) {
5083                final PersistentPreferredActivity ppa = pprefs.get(i);
5084                if (DEBUG_PREFERRED || debug) {
5085                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5086                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5087                            + "\n  component=" + ppa.mComponent);
5088                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5089                }
5090                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5091                        flags | MATCH_DISABLED_COMPONENTS, userId);
5092                if (DEBUG_PREFERRED || debug) {
5093                    Slog.v(TAG, "Found persistent preferred activity:");
5094                    if (ai != null) {
5095                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5096                    } else {
5097                        Slog.v(TAG, "  null");
5098                    }
5099                }
5100                if (ai == null) {
5101                    // This previously registered persistent preferred activity
5102                    // component is no longer known. Ignore it and do NOT remove it.
5103                    continue;
5104                }
5105                for (int j=0; j<N; j++) {
5106                    final ResolveInfo ri = query.get(j);
5107                    if (!ri.activityInfo.applicationInfo.packageName
5108                            .equals(ai.applicationInfo.packageName)) {
5109                        continue;
5110                    }
5111                    if (!ri.activityInfo.name.equals(ai.name)) {
5112                        continue;
5113                    }
5114                    //  Found a persistent preference that can handle the intent.
5115                    if (DEBUG_PREFERRED || debug) {
5116                        Slog.v(TAG, "Returning persistent preferred activity: " +
5117                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5118                    }
5119                    return ri;
5120                }
5121            }
5122        }
5123        return null;
5124    }
5125
5126    // TODO: handle preferred activities missing while user has amnesia
5127    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5128            List<ResolveInfo> query, int priority, boolean always,
5129            boolean removeMatches, boolean debug, int userId) {
5130        if (!sUserManager.exists(userId)) return null;
5131        flags = updateFlagsForResolve(flags, userId, intent);
5132        // writer
5133        synchronized (mPackages) {
5134            if (intent.getSelector() != null) {
5135                intent = intent.getSelector();
5136            }
5137            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5138
5139            // Try to find a matching persistent preferred activity.
5140            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5141                    debug, userId);
5142
5143            // If a persistent preferred activity matched, use it.
5144            if (pri != null) {
5145                return pri;
5146            }
5147
5148            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5149            // Get the list of preferred activities that handle the intent
5150            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5151            List<PreferredActivity> prefs = pir != null
5152                    ? pir.queryIntent(intent, resolvedType,
5153                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5154                    : null;
5155            if (prefs != null && prefs.size() > 0) {
5156                boolean changed = false;
5157                try {
5158                    // First figure out how good the original match set is.
5159                    // We will only allow preferred activities that came
5160                    // from the same match quality.
5161                    int match = 0;
5162
5163                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5164
5165                    final int N = query.size();
5166                    for (int j=0; j<N; j++) {
5167                        final ResolveInfo ri = query.get(j);
5168                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5169                                + ": 0x" + Integer.toHexString(match));
5170                        if (ri.match > match) {
5171                            match = ri.match;
5172                        }
5173                    }
5174
5175                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5176                            + Integer.toHexString(match));
5177
5178                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5179                    final int M = prefs.size();
5180                    for (int i=0; i<M; i++) {
5181                        final PreferredActivity pa = prefs.get(i);
5182                        if (DEBUG_PREFERRED || debug) {
5183                            Slog.v(TAG, "Checking PreferredActivity ds="
5184                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5185                                    + "\n  component=" + pa.mPref.mComponent);
5186                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5187                        }
5188                        if (pa.mPref.mMatch != match) {
5189                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5190                                    + Integer.toHexString(pa.mPref.mMatch));
5191                            continue;
5192                        }
5193                        // If it's not an "always" type preferred activity and that's what we're
5194                        // looking for, skip it.
5195                        if (always && !pa.mPref.mAlways) {
5196                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5197                            continue;
5198                        }
5199                        final ActivityInfo ai = getActivityInfo(
5200                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5201                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5202                                userId);
5203                        if (DEBUG_PREFERRED || debug) {
5204                            Slog.v(TAG, "Found preferred activity:");
5205                            if (ai != null) {
5206                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5207                            } else {
5208                                Slog.v(TAG, "  null");
5209                            }
5210                        }
5211                        if (ai == null) {
5212                            // This previously registered preferred activity
5213                            // component is no longer known.  Most likely an update
5214                            // to the app was installed and in the new version this
5215                            // component no longer exists.  Clean it up by removing
5216                            // it from the preferred activities list, and skip it.
5217                            Slog.w(TAG, "Removing dangling preferred activity: "
5218                                    + pa.mPref.mComponent);
5219                            pir.removeFilter(pa);
5220                            changed = true;
5221                            continue;
5222                        }
5223                        for (int j=0; j<N; j++) {
5224                            final ResolveInfo ri = query.get(j);
5225                            if (!ri.activityInfo.applicationInfo.packageName
5226                                    .equals(ai.applicationInfo.packageName)) {
5227                                continue;
5228                            }
5229                            if (!ri.activityInfo.name.equals(ai.name)) {
5230                                continue;
5231                            }
5232
5233                            if (removeMatches) {
5234                                pir.removeFilter(pa);
5235                                changed = true;
5236                                if (DEBUG_PREFERRED) {
5237                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5238                                }
5239                                break;
5240                            }
5241
5242                            // Okay we found a previously set preferred or last chosen app.
5243                            // If the result set is different from when this
5244                            // was created, we need to clear it and re-ask the
5245                            // user their preference, if we're looking for an "always" type entry.
5246                            if (always && !pa.mPref.sameSet(query)) {
5247                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5248                                        + intent + " type " + resolvedType);
5249                                if (DEBUG_PREFERRED) {
5250                                    Slog.v(TAG, "Removing preferred activity since set changed "
5251                                            + pa.mPref.mComponent);
5252                                }
5253                                pir.removeFilter(pa);
5254                                // Re-add the filter as a "last chosen" entry (!always)
5255                                PreferredActivity lastChosen = new PreferredActivity(
5256                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5257                                pir.addFilter(lastChosen);
5258                                changed = true;
5259                                return null;
5260                            }
5261
5262                            // Yay! Either the set matched or we're looking for the last chosen
5263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5264                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5265                            return ri;
5266                        }
5267                    }
5268                } finally {
5269                    if (changed) {
5270                        if (DEBUG_PREFERRED) {
5271                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5272                        }
5273                        scheduleWritePackageRestrictionsLocked(userId);
5274                    }
5275                }
5276            }
5277        }
5278        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5279        return null;
5280    }
5281
5282    /*
5283     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5284     */
5285    @Override
5286    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5287            int targetUserId) {
5288        mContext.enforceCallingOrSelfPermission(
5289                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5290        List<CrossProfileIntentFilter> matches =
5291                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5292        if (matches != null) {
5293            int size = matches.size();
5294            for (int i = 0; i < size; i++) {
5295                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5296            }
5297        }
5298        if (hasWebURI(intent)) {
5299            // cross-profile app linking works only towards the parent.
5300            final UserInfo parent = getProfileParent(sourceUserId);
5301            synchronized(mPackages) {
5302                int flags = updateFlagsForResolve(0, parent.id, intent);
5303                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5304                        intent, resolvedType, flags, sourceUserId, parent.id);
5305                return xpDomainInfo != null;
5306            }
5307        }
5308        return false;
5309    }
5310
5311    private UserInfo getProfileParent(int userId) {
5312        final long identity = Binder.clearCallingIdentity();
5313        try {
5314            return sUserManager.getProfileParent(userId);
5315        } finally {
5316            Binder.restoreCallingIdentity(identity);
5317        }
5318    }
5319
5320    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5321            String resolvedType, int userId) {
5322        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5323        if (resolver != null) {
5324            return resolver.queryIntent(intent, resolvedType, false, userId);
5325        }
5326        return null;
5327    }
5328
5329    @Override
5330    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5331            String resolvedType, int flags, int userId) {
5332        try {
5333            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5334
5335            return new ParceledListSlice<>(
5336                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5337        } finally {
5338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5339        }
5340    }
5341
5342    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5343            String resolvedType, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return Collections.emptyList();
5345        flags = updateFlagsForResolve(flags, userId, intent);
5346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5347                false /* requireFullPermission */, false /* checkShell */,
5348                "query intent activities");
5349        ComponentName comp = intent.getComponent();
5350        if (comp == null) {
5351            if (intent.getSelector() != null) {
5352                intent = intent.getSelector();
5353                comp = intent.getComponent();
5354            }
5355        }
5356
5357        if (comp != null) {
5358            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5359            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5360            if (ai != null) {
5361                final ResolveInfo ri = new ResolveInfo();
5362                ri.activityInfo = ai;
5363                list.add(ri);
5364            }
5365            return list;
5366        }
5367
5368        // reader
5369        boolean sortResult = false;
5370        boolean addEphemeral = false;
5371        boolean matchEphemeralPackage = false;
5372        List<ResolveInfo> result;
5373        final String pkgName = intent.getPackage();
5374        synchronized (mPackages) {
5375            if (pkgName == null) {
5376                List<CrossProfileIntentFilter> matchingFilters =
5377                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5378                // Check for results that need to skip the current profile.
5379                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5380                        resolvedType, flags, userId);
5381                if (xpResolveInfo != null) {
5382                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5383                    xpResult.add(xpResolveInfo);
5384                    return filterIfNotSystemUser(xpResult, userId);
5385                }
5386
5387                // Check for results in the current profile.
5388                result = filterIfNotSystemUser(mActivities.queryIntent(
5389                        intent, resolvedType, flags, userId), userId);
5390                addEphemeral =
5391                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5392
5393                // Check for cross profile results.
5394                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5395                xpResolveInfo = queryCrossProfileIntents(
5396                        matchingFilters, intent, resolvedType, flags, userId,
5397                        hasNonNegativePriorityResult);
5398                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5399                    boolean isVisibleToUser = filterIfNotSystemUser(
5400                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5401                    if (isVisibleToUser) {
5402                        result.add(xpResolveInfo);
5403                        sortResult = true;
5404                    }
5405                }
5406                if (hasWebURI(intent)) {
5407                    CrossProfileDomainInfo xpDomainInfo = null;
5408                    final UserInfo parent = getProfileParent(userId);
5409                    if (parent != null) {
5410                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5411                                flags, userId, parent.id);
5412                    }
5413                    if (xpDomainInfo != null) {
5414                        if (xpResolveInfo != null) {
5415                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5416                            // in the result.
5417                            result.remove(xpResolveInfo);
5418                        }
5419                        if (result.size() == 0 && !addEphemeral) {
5420                            // No result in current profile, but found candidate in parent user.
5421                            // And we are not going to add emphemeral app, so we can return the
5422                            // result straight away.
5423                            result.add(xpDomainInfo.resolveInfo);
5424                            return result;
5425                        }
5426                    } else if (result.size() <= 1 && !addEphemeral) {
5427                        // No result in parent user and <= 1 result in current profile, and we
5428                        // are not going to add emphemeral app, so we can return the result without
5429                        // further processing.
5430                        return result;
5431                    }
5432                    // We have more than one candidate (combining results from current and parent
5433                    // profile), so we need filtering and sorting.
5434                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5435                            intent, flags, result, xpDomainInfo, userId);
5436                    sortResult = true;
5437                }
5438            } else {
5439                final PackageParser.Package pkg = mPackages.get(pkgName);
5440                if (pkg != null) {
5441                    result = filterIfNotSystemUser(
5442                            mActivities.queryIntentForPackage(
5443                                    intent, resolvedType, flags, pkg.activities, userId),
5444                            userId);
5445                } else {
5446                    // the caller wants to resolve for a particular package; however, there
5447                    // were no installed results, so, try to find an ephemeral result
5448                    addEphemeral = isEphemeralAllowed(
5449                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5450                    matchEphemeralPackage = true;
5451                    result = new ArrayList<ResolveInfo>();
5452                }
5453            }
5454        }
5455        if (addEphemeral) {
5456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5457            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5458                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5459                    matchEphemeralPackage ? pkgName : null);
5460            if (ai != null) {
5461                if (DEBUG_EPHEMERAL) {
5462                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5463                }
5464                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5465                ephemeralInstaller.ephemeralResolveInfo = ai;
5466                // make sure this resolver is the default
5467                ephemeralInstaller.isDefault = true;
5468                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5469                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5470                // add a non-generic filter
5471                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5472                ephemeralInstaller.filter.addDataPath(
5473                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5474                result.add(ephemeralInstaller);
5475            }
5476            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5477        }
5478        if (sortResult) {
5479            Collections.sort(result, mResolvePrioritySorter);
5480        }
5481        return result;
5482    }
5483
5484    private static class CrossProfileDomainInfo {
5485        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5486        ResolveInfo resolveInfo;
5487        /* Best domain verification status of the activities found in the other profile */
5488        int bestDomainVerificationStatus;
5489    }
5490
5491    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5492            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5493        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5494                sourceUserId)) {
5495            return null;
5496        }
5497        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5498                resolvedType, flags, parentUserId);
5499
5500        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5501            return null;
5502        }
5503        CrossProfileDomainInfo result = null;
5504        int size = resultTargetUser.size();
5505        for (int i = 0; i < size; i++) {
5506            ResolveInfo riTargetUser = resultTargetUser.get(i);
5507            // Intent filter verification is only for filters that specify a host. So don't return
5508            // those that handle all web uris.
5509            if (riTargetUser.handleAllWebDataURI) {
5510                continue;
5511            }
5512            String packageName = riTargetUser.activityInfo.packageName;
5513            PackageSetting ps = mSettings.mPackages.get(packageName);
5514            if (ps == null) {
5515                continue;
5516            }
5517            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5518            int status = (int)(verificationState >> 32);
5519            if (result == null) {
5520                result = new CrossProfileDomainInfo();
5521                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5522                        sourceUserId, parentUserId);
5523                result.bestDomainVerificationStatus = status;
5524            } else {
5525                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5526                        result.bestDomainVerificationStatus);
5527            }
5528        }
5529        // Don't consider matches with status NEVER across profiles.
5530        if (result != null && result.bestDomainVerificationStatus
5531                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5532            return null;
5533        }
5534        return result;
5535    }
5536
5537    /**
5538     * Verification statuses are ordered from the worse to the best, except for
5539     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5540     */
5541    private int bestDomainVerificationStatus(int status1, int status2) {
5542        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5543            return status2;
5544        }
5545        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5546            return status1;
5547        }
5548        return (int) MathUtils.max(status1, status2);
5549    }
5550
5551    private boolean isUserEnabled(int userId) {
5552        long callingId = Binder.clearCallingIdentity();
5553        try {
5554            UserInfo userInfo = sUserManager.getUserInfo(userId);
5555            return userInfo != null && userInfo.isEnabled();
5556        } finally {
5557            Binder.restoreCallingIdentity(callingId);
5558        }
5559    }
5560
5561    /**
5562     * Filter out activities with systemUserOnly flag set, when current user is not System.
5563     *
5564     * @return filtered list
5565     */
5566    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5567        if (userId == UserHandle.USER_SYSTEM) {
5568            return resolveInfos;
5569        }
5570        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5571            ResolveInfo info = resolveInfos.get(i);
5572            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5573                resolveInfos.remove(i);
5574            }
5575        }
5576        return resolveInfos;
5577    }
5578
5579    /**
5580     * @param resolveInfos list of resolve infos in descending priority order
5581     * @return if the list contains a resolve info with non-negative priority
5582     */
5583    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5584        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5585    }
5586
5587    private static boolean hasWebURI(Intent intent) {
5588        if (intent.getData() == null) {
5589            return false;
5590        }
5591        final String scheme = intent.getScheme();
5592        if (TextUtils.isEmpty(scheme)) {
5593            return false;
5594        }
5595        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5596    }
5597
5598    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5599            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5600            int userId) {
5601        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5602
5603        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5604            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5605                    candidates.size());
5606        }
5607
5608        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5609        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5610        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5611        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5612        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5613        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5614
5615        synchronized (mPackages) {
5616            final int count = candidates.size();
5617            // First, try to use linked apps. Partition the candidates into four lists:
5618            // one for the final results, one for the "do not use ever", one for "undefined status"
5619            // and finally one for "browser app type".
5620            for (int n=0; n<count; n++) {
5621                ResolveInfo info = candidates.get(n);
5622                String packageName = info.activityInfo.packageName;
5623                PackageSetting ps = mSettings.mPackages.get(packageName);
5624                if (ps != null) {
5625                    // Add to the special match all list (Browser use case)
5626                    if (info.handleAllWebDataURI) {
5627                        matchAllList.add(info);
5628                        continue;
5629                    }
5630                    // Try to get the status from User settings first
5631                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5632                    int status = (int)(packedStatus >> 32);
5633                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5634                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5635                        if (DEBUG_DOMAIN_VERIFICATION) {
5636                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5637                                    + " : linkgen=" + linkGeneration);
5638                        }
5639                        // Use link-enabled generation as preferredOrder, i.e.
5640                        // prefer newly-enabled over earlier-enabled.
5641                        info.preferredOrder = linkGeneration;
5642                        alwaysList.add(info);
5643                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5644                        if (DEBUG_DOMAIN_VERIFICATION) {
5645                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5646                        }
5647                        neverList.add(info);
5648                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5649                        if (DEBUG_DOMAIN_VERIFICATION) {
5650                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5651                        }
5652                        alwaysAskList.add(info);
5653                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5654                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5655                        if (DEBUG_DOMAIN_VERIFICATION) {
5656                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5657                        }
5658                        undefinedList.add(info);
5659                    }
5660                }
5661            }
5662
5663            // We'll want to include browser possibilities in a few cases
5664            boolean includeBrowser = false;
5665
5666            // First try to add the "always" resolution(s) for the current user, if any
5667            if (alwaysList.size() > 0) {
5668                result.addAll(alwaysList);
5669            } else {
5670                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5671                result.addAll(undefinedList);
5672                // Maybe add one for the other profile.
5673                if (xpDomainInfo != null && (
5674                        xpDomainInfo.bestDomainVerificationStatus
5675                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5676                    result.add(xpDomainInfo.resolveInfo);
5677                }
5678                includeBrowser = true;
5679            }
5680
5681            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5682            // If there were 'always' entries their preferred order has been set, so we also
5683            // back that off to make the alternatives equivalent
5684            if (alwaysAskList.size() > 0) {
5685                for (ResolveInfo i : result) {
5686                    i.preferredOrder = 0;
5687                }
5688                result.addAll(alwaysAskList);
5689                includeBrowser = true;
5690            }
5691
5692            if (includeBrowser) {
5693                // Also add browsers (all of them or only the default one)
5694                if (DEBUG_DOMAIN_VERIFICATION) {
5695                    Slog.v(TAG, "   ...including browsers in candidate set");
5696                }
5697                if ((matchFlags & MATCH_ALL) != 0) {
5698                    result.addAll(matchAllList);
5699                } else {
5700                    // Browser/generic handling case.  If there's a default browser, go straight
5701                    // to that (but only if there is no other higher-priority match).
5702                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5703                    int maxMatchPrio = 0;
5704                    ResolveInfo defaultBrowserMatch = null;
5705                    final int numCandidates = matchAllList.size();
5706                    for (int n = 0; n < numCandidates; n++) {
5707                        ResolveInfo info = matchAllList.get(n);
5708                        // track the highest overall match priority...
5709                        if (info.priority > maxMatchPrio) {
5710                            maxMatchPrio = info.priority;
5711                        }
5712                        // ...and the highest-priority default browser match
5713                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5714                            if (defaultBrowserMatch == null
5715                                    || (defaultBrowserMatch.priority < info.priority)) {
5716                                if (debug) {
5717                                    Slog.v(TAG, "Considering default browser match " + info);
5718                                }
5719                                defaultBrowserMatch = info;
5720                            }
5721                        }
5722                    }
5723                    if (defaultBrowserMatch != null
5724                            && defaultBrowserMatch.priority >= maxMatchPrio
5725                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5726                    {
5727                        if (debug) {
5728                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5729                        }
5730                        result.add(defaultBrowserMatch);
5731                    } else {
5732                        result.addAll(matchAllList);
5733                    }
5734                }
5735
5736                // If there is nothing selected, add all candidates and remove the ones that the user
5737                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5738                if (result.size() == 0) {
5739                    result.addAll(candidates);
5740                    result.removeAll(neverList);
5741                }
5742            }
5743        }
5744        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5745            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5746                    result.size());
5747            for (ResolveInfo info : result) {
5748                Slog.v(TAG, "  + " + info.activityInfo);
5749            }
5750        }
5751        return result;
5752    }
5753
5754    // Returns a packed value as a long:
5755    //
5756    // high 'int'-sized word: link status: undefined/ask/never/always.
5757    // low 'int'-sized word: relative priority among 'always' results.
5758    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5759        long result = ps.getDomainVerificationStatusForUser(userId);
5760        // if none available, get the master status
5761        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5762            if (ps.getIntentFilterVerificationInfo() != null) {
5763                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5764            }
5765        }
5766        return result;
5767    }
5768
5769    private ResolveInfo querySkipCurrentProfileIntents(
5770            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5771            int flags, int sourceUserId) {
5772        if (matchingFilters != null) {
5773            int size = matchingFilters.size();
5774            for (int i = 0; i < size; i ++) {
5775                CrossProfileIntentFilter filter = matchingFilters.get(i);
5776                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5777                    // Checking if there are activities in the target user that can handle the
5778                    // intent.
5779                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5780                            resolvedType, flags, sourceUserId);
5781                    if (resolveInfo != null) {
5782                        return resolveInfo;
5783                    }
5784                }
5785            }
5786        }
5787        return null;
5788    }
5789
5790    // Return matching ResolveInfo in target user if any.
5791    private ResolveInfo queryCrossProfileIntents(
5792            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5793            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5794        if (matchingFilters != null) {
5795            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5796            // match the same intent. For performance reasons, it is better not to
5797            // run queryIntent twice for the same userId
5798            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5799            int size = matchingFilters.size();
5800            for (int i = 0; i < size; i++) {
5801                CrossProfileIntentFilter filter = matchingFilters.get(i);
5802                int targetUserId = filter.getTargetUserId();
5803                boolean skipCurrentProfile =
5804                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5805                boolean skipCurrentProfileIfNoMatchFound =
5806                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5807                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5808                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5809                    // Checking if there are activities in the target user that can handle the
5810                    // intent.
5811                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5812                            resolvedType, flags, sourceUserId);
5813                    if (resolveInfo != null) return resolveInfo;
5814                    alreadyTriedUserIds.put(targetUserId, true);
5815                }
5816            }
5817        }
5818        return null;
5819    }
5820
5821    /**
5822     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5823     * will forward the intent to the filter's target user.
5824     * Otherwise, returns null.
5825     */
5826    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5827            String resolvedType, int flags, int sourceUserId) {
5828        int targetUserId = filter.getTargetUserId();
5829        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5830                resolvedType, flags, targetUserId);
5831        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5832            // If all the matches in the target profile are suspended, return null.
5833            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5834                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5835                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5836                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5837                            targetUserId);
5838                }
5839            }
5840        }
5841        return null;
5842    }
5843
5844    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5845            int sourceUserId, int targetUserId) {
5846        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5847        long ident = Binder.clearCallingIdentity();
5848        boolean targetIsProfile;
5849        try {
5850            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5851        } finally {
5852            Binder.restoreCallingIdentity(ident);
5853        }
5854        String className;
5855        if (targetIsProfile) {
5856            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5857        } else {
5858            className = FORWARD_INTENT_TO_PARENT;
5859        }
5860        ComponentName forwardingActivityComponentName = new ComponentName(
5861                mAndroidApplication.packageName, className);
5862        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5863                sourceUserId);
5864        if (!targetIsProfile) {
5865            forwardingActivityInfo.showUserIcon = targetUserId;
5866            forwardingResolveInfo.noResourceId = true;
5867        }
5868        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5869        forwardingResolveInfo.priority = 0;
5870        forwardingResolveInfo.preferredOrder = 0;
5871        forwardingResolveInfo.match = 0;
5872        forwardingResolveInfo.isDefault = true;
5873        forwardingResolveInfo.filter = filter;
5874        forwardingResolveInfo.targetUserId = targetUserId;
5875        return forwardingResolveInfo;
5876    }
5877
5878    @Override
5879    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5880            Intent[] specifics, String[] specificTypes, Intent intent,
5881            String resolvedType, int flags, int userId) {
5882        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5883                specificTypes, intent, resolvedType, flags, userId));
5884    }
5885
5886    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5887            Intent[] specifics, String[] specificTypes, Intent intent,
5888            String resolvedType, int flags, int userId) {
5889        if (!sUserManager.exists(userId)) return Collections.emptyList();
5890        flags = updateFlagsForResolve(flags, userId, intent);
5891        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5892                false /* requireFullPermission */, false /* checkShell */,
5893                "query intent activity options");
5894        final String resultsAction = intent.getAction();
5895
5896        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5897                | PackageManager.GET_RESOLVED_FILTER, userId);
5898
5899        if (DEBUG_INTENT_MATCHING) {
5900            Log.v(TAG, "Query " + intent + ": " + results);
5901        }
5902
5903        int specificsPos = 0;
5904        int N;
5905
5906        // todo: note that the algorithm used here is O(N^2).  This
5907        // isn't a problem in our current environment, but if we start running
5908        // into situations where we have more than 5 or 10 matches then this
5909        // should probably be changed to something smarter...
5910
5911        // First we go through and resolve each of the specific items
5912        // that were supplied, taking care of removing any corresponding
5913        // duplicate items in the generic resolve list.
5914        if (specifics != null) {
5915            for (int i=0; i<specifics.length; i++) {
5916                final Intent sintent = specifics[i];
5917                if (sintent == null) {
5918                    continue;
5919                }
5920
5921                if (DEBUG_INTENT_MATCHING) {
5922                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5923                }
5924
5925                String action = sintent.getAction();
5926                if (resultsAction != null && resultsAction.equals(action)) {
5927                    // If this action was explicitly requested, then don't
5928                    // remove things that have it.
5929                    action = null;
5930                }
5931
5932                ResolveInfo ri = null;
5933                ActivityInfo ai = null;
5934
5935                ComponentName comp = sintent.getComponent();
5936                if (comp == null) {
5937                    ri = resolveIntent(
5938                        sintent,
5939                        specificTypes != null ? specificTypes[i] : null,
5940                            flags, userId);
5941                    if (ri == null) {
5942                        continue;
5943                    }
5944                    if (ri == mResolveInfo) {
5945                        // ACK!  Must do something better with this.
5946                    }
5947                    ai = ri.activityInfo;
5948                    comp = new ComponentName(ai.applicationInfo.packageName,
5949                            ai.name);
5950                } else {
5951                    ai = getActivityInfo(comp, flags, userId);
5952                    if (ai == null) {
5953                        continue;
5954                    }
5955                }
5956
5957                // Look for any generic query activities that are duplicates
5958                // of this specific one, and remove them from the results.
5959                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5960                N = results.size();
5961                int j;
5962                for (j=specificsPos; j<N; j++) {
5963                    ResolveInfo sri = results.get(j);
5964                    if ((sri.activityInfo.name.equals(comp.getClassName())
5965                            && sri.activityInfo.applicationInfo.packageName.equals(
5966                                    comp.getPackageName()))
5967                        || (action != null && sri.filter.matchAction(action))) {
5968                        results.remove(j);
5969                        if (DEBUG_INTENT_MATCHING) Log.v(
5970                            TAG, "Removing duplicate item from " + j
5971                            + " due to specific " + specificsPos);
5972                        if (ri == null) {
5973                            ri = sri;
5974                        }
5975                        j--;
5976                        N--;
5977                    }
5978                }
5979
5980                // Add this specific item to its proper place.
5981                if (ri == null) {
5982                    ri = new ResolveInfo();
5983                    ri.activityInfo = ai;
5984                }
5985                results.add(specificsPos, ri);
5986                ri.specificIndex = i;
5987                specificsPos++;
5988            }
5989        }
5990
5991        // Now we go through the remaining generic results and remove any
5992        // duplicate actions that are found here.
5993        N = results.size();
5994        for (int i=specificsPos; i<N-1; i++) {
5995            final ResolveInfo rii = results.get(i);
5996            if (rii.filter == null) {
5997                continue;
5998            }
5999
6000            // Iterate over all of the actions of this result's intent
6001            // filter...  typically this should be just one.
6002            final Iterator<String> it = rii.filter.actionsIterator();
6003            if (it == null) {
6004                continue;
6005            }
6006            while (it.hasNext()) {
6007                final String action = it.next();
6008                if (resultsAction != null && resultsAction.equals(action)) {
6009                    // If this action was explicitly requested, then don't
6010                    // remove things that have it.
6011                    continue;
6012                }
6013                for (int j=i+1; j<N; j++) {
6014                    final ResolveInfo rij = results.get(j);
6015                    if (rij.filter != null && rij.filter.hasAction(action)) {
6016                        results.remove(j);
6017                        if (DEBUG_INTENT_MATCHING) Log.v(
6018                            TAG, "Removing duplicate item from " + j
6019                            + " due to action " + action + " at " + i);
6020                        j--;
6021                        N--;
6022                    }
6023                }
6024            }
6025
6026            // If the caller didn't request filter information, drop it now
6027            // so we don't have to marshall/unmarshall it.
6028            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6029                rii.filter = null;
6030            }
6031        }
6032
6033        // Filter out the caller activity if so requested.
6034        if (caller != null) {
6035            N = results.size();
6036            for (int i=0; i<N; i++) {
6037                ActivityInfo ainfo = results.get(i).activityInfo;
6038                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6039                        && caller.getClassName().equals(ainfo.name)) {
6040                    results.remove(i);
6041                    break;
6042                }
6043            }
6044        }
6045
6046        // If the caller didn't request filter information,
6047        // drop them now so we don't have to
6048        // marshall/unmarshall it.
6049        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6050            N = results.size();
6051            for (int i=0; i<N; i++) {
6052                results.get(i).filter = null;
6053            }
6054        }
6055
6056        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6057        return results;
6058    }
6059
6060    @Override
6061    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6062            String resolvedType, int flags, int userId) {
6063        return new ParceledListSlice<>(
6064                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6065    }
6066
6067    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6068            String resolvedType, int flags, int userId) {
6069        if (!sUserManager.exists(userId)) return Collections.emptyList();
6070        flags = updateFlagsForResolve(flags, userId, intent);
6071        ComponentName comp = intent.getComponent();
6072        if (comp == null) {
6073            if (intent.getSelector() != null) {
6074                intent = intent.getSelector();
6075                comp = intent.getComponent();
6076            }
6077        }
6078        if (comp != null) {
6079            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6080            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6081            if (ai != null) {
6082                ResolveInfo ri = new ResolveInfo();
6083                ri.activityInfo = ai;
6084                list.add(ri);
6085            }
6086            return list;
6087        }
6088
6089        // reader
6090        synchronized (mPackages) {
6091            String pkgName = intent.getPackage();
6092            if (pkgName == null) {
6093                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6094            }
6095            final PackageParser.Package pkg = mPackages.get(pkgName);
6096            if (pkg != null) {
6097                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6098                        userId);
6099            }
6100            return Collections.emptyList();
6101        }
6102    }
6103
6104    @Override
6105    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6106        if (!sUserManager.exists(userId)) return null;
6107        flags = updateFlagsForResolve(flags, userId, intent);
6108        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6109        if (query != null) {
6110            if (query.size() >= 1) {
6111                // If there is more than one service with the same priority,
6112                // just arbitrarily pick the first one.
6113                return query.get(0);
6114            }
6115        }
6116        return null;
6117    }
6118
6119    @Override
6120    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6121            String resolvedType, int flags, int userId) {
6122        return new ParceledListSlice<>(
6123                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6124    }
6125
6126    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6127            String resolvedType, int flags, int userId) {
6128        if (!sUserManager.exists(userId)) return Collections.emptyList();
6129        flags = updateFlagsForResolve(flags, userId, intent);
6130        ComponentName comp = intent.getComponent();
6131        if (comp == null) {
6132            if (intent.getSelector() != null) {
6133                intent = intent.getSelector();
6134                comp = intent.getComponent();
6135            }
6136        }
6137        if (comp != null) {
6138            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6139            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6140            if (si != null) {
6141                final ResolveInfo ri = new ResolveInfo();
6142                ri.serviceInfo = si;
6143                list.add(ri);
6144            }
6145            return list;
6146        }
6147
6148        // reader
6149        synchronized (mPackages) {
6150            String pkgName = intent.getPackage();
6151            if (pkgName == null) {
6152                return mServices.queryIntent(intent, resolvedType, flags, userId);
6153            }
6154            final PackageParser.Package pkg = mPackages.get(pkgName);
6155            if (pkg != null) {
6156                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6157                        userId);
6158            }
6159            return Collections.emptyList();
6160        }
6161    }
6162
6163    @Override
6164    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6165            String resolvedType, int flags, int userId) {
6166        return new ParceledListSlice<>(
6167                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6168    }
6169
6170    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6171            Intent intent, String resolvedType, int flags, int userId) {
6172        if (!sUserManager.exists(userId)) return Collections.emptyList();
6173        flags = updateFlagsForResolve(flags, userId, intent);
6174        ComponentName comp = intent.getComponent();
6175        if (comp == null) {
6176            if (intent.getSelector() != null) {
6177                intent = intent.getSelector();
6178                comp = intent.getComponent();
6179            }
6180        }
6181        if (comp != null) {
6182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6183            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6184            if (pi != null) {
6185                final ResolveInfo ri = new ResolveInfo();
6186                ri.providerInfo = pi;
6187                list.add(ri);
6188            }
6189            return list;
6190        }
6191
6192        // reader
6193        synchronized (mPackages) {
6194            String pkgName = intent.getPackage();
6195            if (pkgName == null) {
6196                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6197            }
6198            final PackageParser.Package pkg = mPackages.get(pkgName);
6199            if (pkg != null) {
6200                return mProviders.queryIntentForPackage(
6201                        intent, resolvedType, flags, pkg.providers, userId);
6202            }
6203            return Collections.emptyList();
6204        }
6205    }
6206
6207    @Override
6208    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6209        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6210        flags = updateFlagsForPackage(flags, userId, null);
6211        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6212        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6213                true /* requireFullPermission */, false /* checkShell */,
6214                "get installed packages");
6215
6216        // writer
6217        synchronized (mPackages) {
6218            ArrayList<PackageInfo> list;
6219            if (listUninstalled) {
6220                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6221                for (PackageSetting ps : mSettings.mPackages.values()) {
6222                    final PackageInfo pi;
6223                    if (ps.pkg != null) {
6224                        pi = generatePackageInfo(ps, flags, userId);
6225                    } else {
6226                        pi = generatePackageInfo(ps, flags, userId);
6227                    }
6228                    if (pi != null) {
6229                        list.add(pi);
6230                    }
6231                }
6232            } else {
6233                list = new ArrayList<PackageInfo>(mPackages.size());
6234                for (PackageParser.Package p : mPackages.values()) {
6235                    final PackageInfo pi =
6236                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6237                    if (pi != null) {
6238                        list.add(pi);
6239                    }
6240                }
6241            }
6242
6243            return new ParceledListSlice<PackageInfo>(list);
6244        }
6245    }
6246
6247    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6248            String[] permissions, boolean[] tmp, int flags, int userId) {
6249        int numMatch = 0;
6250        final PermissionsState permissionsState = ps.getPermissionsState();
6251        for (int i=0; i<permissions.length; i++) {
6252            final String permission = permissions[i];
6253            if (permissionsState.hasPermission(permission, userId)) {
6254                tmp[i] = true;
6255                numMatch++;
6256            } else {
6257                tmp[i] = false;
6258            }
6259        }
6260        if (numMatch == 0) {
6261            return;
6262        }
6263        final PackageInfo pi;
6264        if (ps.pkg != null) {
6265            pi = generatePackageInfo(ps, flags, userId);
6266        } else {
6267            pi = generatePackageInfo(ps, flags, userId);
6268        }
6269        // The above might return null in cases of uninstalled apps or install-state
6270        // skew across users/profiles.
6271        if (pi != null) {
6272            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6273                if (numMatch == permissions.length) {
6274                    pi.requestedPermissions = permissions;
6275                } else {
6276                    pi.requestedPermissions = new String[numMatch];
6277                    numMatch = 0;
6278                    for (int i=0; i<permissions.length; i++) {
6279                        if (tmp[i]) {
6280                            pi.requestedPermissions[numMatch] = permissions[i];
6281                            numMatch++;
6282                        }
6283                    }
6284                }
6285            }
6286            list.add(pi);
6287        }
6288    }
6289
6290    @Override
6291    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6292            String[] permissions, int flags, int userId) {
6293        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6294        flags = updateFlagsForPackage(flags, userId, permissions);
6295        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6296
6297        // writer
6298        synchronized (mPackages) {
6299            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6300            boolean[] tmpBools = new boolean[permissions.length];
6301            if (listUninstalled) {
6302                for (PackageSetting ps : mSettings.mPackages.values()) {
6303                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6304                }
6305            } else {
6306                for (PackageParser.Package pkg : mPackages.values()) {
6307                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6308                    if (ps != null) {
6309                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6310                                userId);
6311                    }
6312                }
6313            }
6314
6315            return new ParceledListSlice<PackageInfo>(list);
6316        }
6317    }
6318
6319    @Override
6320    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6321        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6322        flags = updateFlagsForApplication(flags, userId, null);
6323        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6324
6325        // writer
6326        synchronized (mPackages) {
6327            ArrayList<ApplicationInfo> list;
6328            if (listUninstalled) {
6329                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6330                for (PackageSetting ps : mSettings.mPackages.values()) {
6331                    ApplicationInfo ai;
6332                    if (ps.pkg != null) {
6333                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6334                                ps.readUserState(userId), userId);
6335                    } else {
6336                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6337                    }
6338                    if (ai != null) {
6339                        list.add(ai);
6340                    }
6341                }
6342            } else {
6343                list = new ArrayList<ApplicationInfo>(mPackages.size());
6344                for (PackageParser.Package p : mPackages.values()) {
6345                    if (p.mExtras != null) {
6346                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6347                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6348                        if (ai != null) {
6349                            list.add(ai);
6350                        }
6351                    }
6352                }
6353            }
6354
6355            return new ParceledListSlice<ApplicationInfo>(list);
6356        }
6357    }
6358
6359    @Override
6360    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6361        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6362            return null;
6363        }
6364
6365        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6366                "getEphemeralApplications");
6367        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6368                true /* requireFullPermission */, false /* checkShell */,
6369                "getEphemeralApplications");
6370        synchronized (mPackages) {
6371            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6372                    .getEphemeralApplicationsLPw(userId);
6373            if (ephemeralApps != null) {
6374                return new ParceledListSlice<>(ephemeralApps);
6375            }
6376        }
6377        return null;
6378    }
6379
6380    @Override
6381    public boolean isEphemeralApplication(String packageName, int userId) {
6382        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6383                true /* requireFullPermission */, false /* checkShell */,
6384                "isEphemeral");
6385        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6386            return false;
6387        }
6388
6389        if (!isCallerSameApp(packageName)) {
6390            return false;
6391        }
6392        synchronized (mPackages) {
6393            PackageParser.Package pkg = mPackages.get(packageName);
6394            if (pkg != null) {
6395                return pkg.applicationInfo.isEphemeralApp();
6396            }
6397        }
6398        return false;
6399    }
6400
6401    @Override
6402    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6403        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6404            return null;
6405        }
6406
6407        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6408                true /* requireFullPermission */, false /* checkShell */,
6409                "getCookie");
6410        if (!isCallerSameApp(packageName)) {
6411            return null;
6412        }
6413        synchronized (mPackages) {
6414            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6415                    packageName, userId);
6416        }
6417    }
6418
6419    @Override
6420    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6421        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6422            return true;
6423        }
6424
6425        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6426                true /* requireFullPermission */, true /* checkShell */,
6427                "setCookie");
6428        if (!isCallerSameApp(packageName)) {
6429            return false;
6430        }
6431        synchronized (mPackages) {
6432            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6433                    packageName, cookie, userId);
6434        }
6435    }
6436
6437    @Override
6438    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6439        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6440            return null;
6441        }
6442
6443        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6444                "getEphemeralApplicationIcon");
6445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6446                true /* requireFullPermission */, false /* checkShell */,
6447                "getEphemeralApplicationIcon");
6448        synchronized (mPackages) {
6449            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6450                    packageName, userId);
6451        }
6452    }
6453
6454    private boolean isCallerSameApp(String packageName) {
6455        PackageParser.Package pkg = mPackages.get(packageName);
6456        return pkg != null
6457                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6458    }
6459
6460    @Override
6461    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6462        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6463    }
6464
6465    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6466        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6467
6468        // reader
6469        synchronized (mPackages) {
6470            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6471            final int userId = UserHandle.getCallingUserId();
6472            while (i.hasNext()) {
6473                final PackageParser.Package p = i.next();
6474                if (p.applicationInfo == null) continue;
6475
6476                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6477                        && !p.applicationInfo.isDirectBootAware();
6478                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6479                        && p.applicationInfo.isDirectBootAware();
6480
6481                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6482                        && (!mSafeMode || isSystemApp(p))
6483                        && (matchesUnaware || matchesAware)) {
6484                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6485                    if (ps != null) {
6486                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6487                                ps.readUserState(userId), userId);
6488                        if (ai != null) {
6489                            finalList.add(ai);
6490                        }
6491                    }
6492                }
6493            }
6494        }
6495
6496        return finalList;
6497    }
6498
6499    @Override
6500    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6501        if (!sUserManager.exists(userId)) return null;
6502        flags = updateFlagsForComponent(flags, userId, name);
6503        // reader
6504        synchronized (mPackages) {
6505            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6506            PackageSetting ps = provider != null
6507                    ? mSettings.mPackages.get(provider.owner.packageName)
6508                    : null;
6509            return ps != null
6510                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6511                    ? PackageParser.generateProviderInfo(provider, flags,
6512                            ps.readUserState(userId), userId)
6513                    : null;
6514        }
6515    }
6516
6517    /**
6518     * @deprecated
6519     */
6520    @Deprecated
6521    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6522        // reader
6523        synchronized (mPackages) {
6524            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6525                    .entrySet().iterator();
6526            final int userId = UserHandle.getCallingUserId();
6527            while (i.hasNext()) {
6528                Map.Entry<String, PackageParser.Provider> entry = i.next();
6529                PackageParser.Provider p = entry.getValue();
6530                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6531
6532                if (ps != null && p.syncable
6533                        && (!mSafeMode || (p.info.applicationInfo.flags
6534                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6535                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6536                            ps.readUserState(userId), userId);
6537                    if (info != null) {
6538                        outNames.add(entry.getKey());
6539                        outInfo.add(info);
6540                    }
6541                }
6542            }
6543        }
6544    }
6545
6546    @Override
6547    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6548            int uid, int flags) {
6549        final int userId = processName != null ? UserHandle.getUserId(uid)
6550                : UserHandle.getCallingUserId();
6551        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6552        flags = updateFlagsForComponent(flags, userId, processName);
6553
6554        ArrayList<ProviderInfo> finalList = null;
6555        // reader
6556        synchronized (mPackages) {
6557            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6558            while (i.hasNext()) {
6559                final PackageParser.Provider p = i.next();
6560                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6561                if (ps != null && p.info.authority != null
6562                        && (processName == null
6563                                || (p.info.processName.equals(processName)
6564                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6565                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6566                    if (finalList == null) {
6567                        finalList = new ArrayList<ProviderInfo>(3);
6568                    }
6569                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6570                            ps.readUserState(userId), userId);
6571                    if (info != null) {
6572                        finalList.add(info);
6573                    }
6574                }
6575            }
6576        }
6577
6578        if (finalList != null) {
6579            Collections.sort(finalList, mProviderInitOrderSorter);
6580            return new ParceledListSlice<ProviderInfo>(finalList);
6581        }
6582
6583        return ParceledListSlice.emptyList();
6584    }
6585
6586    @Override
6587    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6588        // reader
6589        synchronized (mPackages) {
6590            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6591            return PackageParser.generateInstrumentationInfo(i, flags);
6592        }
6593    }
6594
6595    @Override
6596    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6597            String targetPackage, int flags) {
6598        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6599    }
6600
6601    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6602            int flags) {
6603        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6604
6605        // reader
6606        synchronized (mPackages) {
6607            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6608            while (i.hasNext()) {
6609                final PackageParser.Instrumentation p = i.next();
6610                if (targetPackage == null
6611                        || targetPackage.equals(p.info.targetPackage)) {
6612                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6613                            flags);
6614                    if (ii != null) {
6615                        finalList.add(ii);
6616                    }
6617                }
6618            }
6619        }
6620
6621        return finalList;
6622    }
6623
6624    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6625        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6626        if (overlays == null) {
6627            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6628            return;
6629        }
6630        for (PackageParser.Package opkg : overlays.values()) {
6631            // Not much to do if idmap fails: we already logged the error
6632            // and we certainly don't want to abort installation of pkg simply
6633            // because an overlay didn't fit properly. For these reasons,
6634            // ignore the return value of createIdmapForPackagePairLI.
6635            createIdmapForPackagePairLI(pkg, opkg);
6636        }
6637    }
6638
6639    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6640            PackageParser.Package opkg) {
6641        if (!opkg.mTrustedOverlay) {
6642            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6643                    opkg.baseCodePath + ": overlay not trusted");
6644            return false;
6645        }
6646        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6647        if (overlaySet == null) {
6648            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6649                    opkg.baseCodePath + " but target package has no known overlays");
6650            return false;
6651        }
6652        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6653        // TODO: generate idmap for split APKs
6654        try {
6655            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6656        } catch (InstallerException e) {
6657            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6658                    + opkg.baseCodePath);
6659            return false;
6660        }
6661        PackageParser.Package[] overlayArray =
6662            overlaySet.values().toArray(new PackageParser.Package[0]);
6663        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6664            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6665                return p1.mOverlayPriority - p2.mOverlayPriority;
6666            }
6667        };
6668        Arrays.sort(overlayArray, cmp);
6669
6670        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6671        int i = 0;
6672        for (PackageParser.Package p : overlayArray) {
6673            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6674        }
6675        return true;
6676    }
6677
6678    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6679        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6680        try {
6681            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6682        } finally {
6683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6684        }
6685    }
6686
6687    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6688        final File[] files = dir.listFiles();
6689        if (ArrayUtils.isEmpty(files)) {
6690            Log.d(TAG, "No files in app dir " + dir);
6691            return;
6692        }
6693
6694        if (DEBUG_PACKAGE_SCANNING) {
6695            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6696                    + " flags=0x" + Integer.toHexString(parseFlags));
6697        }
6698
6699        for (File file : files) {
6700            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6701                    && !PackageInstallerService.isStageName(file.getName());
6702            if (!isPackage) {
6703                // Ignore entries which are not packages
6704                continue;
6705            }
6706            try {
6707                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6708                        scanFlags, currentTime, null);
6709            } catch (PackageManagerException e) {
6710                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6711
6712                // Delete invalid userdata apps
6713                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6714                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6715                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6716                    removeCodePathLI(file);
6717                }
6718            }
6719        }
6720    }
6721
6722    private static File getSettingsProblemFile() {
6723        File dataDir = Environment.getDataDirectory();
6724        File systemDir = new File(dataDir, "system");
6725        File fname = new File(systemDir, "uiderrors.txt");
6726        return fname;
6727    }
6728
6729    static void reportSettingsProblem(int priority, String msg) {
6730        logCriticalInfo(priority, msg);
6731    }
6732
6733    static void logCriticalInfo(int priority, String msg) {
6734        Slog.println(priority, TAG, msg);
6735        EventLogTags.writePmCriticalInfo(msg);
6736        try {
6737            File fname = getSettingsProblemFile();
6738            FileOutputStream out = new FileOutputStream(fname, true);
6739            PrintWriter pw = new FastPrintWriter(out);
6740            SimpleDateFormat formatter = new SimpleDateFormat();
6741            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6742            pw.println(dateString + ": " + msg);
6743            pw.close();
6744            FileUtils.setPermissions(
6745                    fname.toString(),
6746                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6747                    -1, -1);
6748        } catch (java.io.IOException e) {
6749        }
6750    }
6751
6752    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6753        if (srcFile.isDirectory()) {
6754            final File baseFile = new File(pkg.baseCodePath);
6755            long maxModifiedTime = baseFile.lastModified();
6756            if (pkg.splitCodePaths != null) {
6757                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6758                    final File splitFile = new File(pkg.splitCodePaths[i]);
6759                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6760                }
6761            }
6762            return maxModifiedTime;
6763        }
6764        return srcFile.lastModified();
6765    }
6766
6767    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6768            final int policyFlags) throws PackageManagerException {
6769        // When upgrading from pre-N MR1, verify the package time stamp using the package
6770        // directory and not the APK file.
6771        final long lastModifiedTime = mIsPreNMR1Upgrade
6772                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6773        if (ps != null
6774                && ps.codePath.equals(srcFile)
6775                && ps.timeStamp == lastModifiedTime
6776                && !isCompatSignatureUpdateNeeded(pkg)
6777                && !isRecoverSignatureUpdateNeeded(pkg)) {
6778            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6779            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6780            ArraySet<PublicKey> signingKs;
6781            synchronized (mPackages) {
6782                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6783            }
6784            if (ps.signatures.mSignatures != null
6785                    && ps.signatures.mSignatures.length != 0
6786                    && signingKs != null) {
6787                // Optimization: reuse the existing cached certificates
6788                // if the package appears to be unchanged.
6789                pkg.mSignatures = ps.signatures.mSignatures;
6790                pkg.mSigningKeys = signingKs;
6791                return;
6792            }
6793
6794            Slog.w(TAG, "PackageSetting for " + ps.name
6795                    + " is missing signatures.  Collecting certs again to recover them.");
6796        } else {
6797            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6798        }
6799
6800        try {
6801            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6802            PackageParser.collectCertificates(pkg, policyFlags);
6803        } catch (PackageParserException e) {
6804            throw PackageManagerException.from(e);
6805        } finally {
6806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6807        }
6808    }
6809
6810    /**
6811     *  Traces a package scan.
6812     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6813     */
6814    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6815            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6816        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6817        try {
6818            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6819        } finally {
6820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6821        }
6822    }
6823
6824    /**
6825     *  Scans a package and returns the newly parsed package.
6826     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6827     */
6828    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6829            long currentTime, UserHandle user) throws PackageManagerException {
6830        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6831        PackageParser pp = new PackageParser();
6832        pp.setSeparateProcesses(mSeparateProcesses);
6833        pp.setOnlyCoreApps(mOnlyCore);
6834        pp.setDisplayMetrics(mMetrics);
6835
6836        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6837            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6838        }
6839
6840        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6841        final PackageParser.Package pkg;
6842        try {
6843            pkg = pp.parsePackage(scanFile, parseFlags);
6844        } catch (PackageParserException e) {
6845            throw PackageManagerException.from(e);
6846        } finally {
6847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6848        }
6849
6850        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6851    }
6852
6853    /**
6854     *  Scans a package and returns the newly parsed package.
6855     *  @throws PackageManagerException on a parse error.
6856     */
6857    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6858            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6859            throws PackageManagerException {
6860        // If the package has children and this is the first dive in the function
6861        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6862        // packages (parent and children) would be successfully scanned before the
6863        // actual scan since scanning mutates internal state and we want to atomically
6864        // install the package and its children.
6865        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6866            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6867                scanFlags |= SCAN_CHECK_ONLY;
6868            }
6869        } else {
6870            scanFlags &= ~SCAN_CHECK_ONLY;
6871        }
6872
6873        // Scan the parent
6874        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6875                scanFlags, currentTime, user);
6876
6877        // Scan the children
6878        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6879        for (int i = 0; i < childCount; i++) {
6880            PackageParser.Package childPackage = pkg.childPackages.get(i);
6881            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6882                    currentTime, user);
6883        }
6884
6885
6886        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6887            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6888        }
6889
6890        return scannedPkg;
6891    }
6892
6893    /**
6894     *  Scans a package and returns the newly parsed package.
6895     *  @throws PackageManagerException on a parse error.
6896     */
6897    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6898            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6899            throws PackageManagerException {
6900        PackageSetting ps = null;
6901        PackageSetting updatedPkg;
6902        // reader
6903        synchronized (mPackages) {
6904            // Look to see if we already know about this package.
6905            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6906            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6907                // This package has been renamed to its original name.  Let's
6908                // use that.
6909                ps = mSettings.getPackageLPr(oldName);
6910            }
6911            // If there was no original package, see one for the real package name.
6912            if (ps == null) {
6913                ps = mSettings.getPackageLPr(pkg.packageName);
6914            }
6915            // Check to see if this package could be hiding/updating a system
6916            // package.  Must look for it either under the original or real
6917            // package name depending on our state.
6918            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6919            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6920
6921            // If this is a package we don't know about on the system partition, we
6922            // may need to remove disabled child packages on the system partition
6923            // or may need to not add child packages if the parent apk is updated
6924            // on the data partition and no longer defines this child package.
6925            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6926                // If this is a parent package for an updated system app and this system
6927                // app got an OTA update which no longer defines some of the child packages
6928                // we have to prune them from the disabled system packages.
6929                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6930                if (disabledPs != null) {
6931                    final int scannedChildCount = (pkg.childPackages != null)
6932                            ? pkg.childPackages.size() : 0;
6933                    final int disabledChildCount = disabledPs.childPackageNames != null
6934                            ? disabledPs.childPackageNames.size() : 0;
6935                    for (int i = 0; i < disabledChildCount; i++) {
6936                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6937                        boolean disabledPackageAvailable = false;
6938                        for (int j = 0; j < scannedChildCount; j++) {
6939                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6940                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6941                                disabledPackageAvailable = true;
6942                                break;
6943                            }
6944                         }
6945                         if (!disabledPackageAvailable) {
6946                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6947                         }
6948                    }
6949                }
6950            }
6951        }
6952
6953        boolean updatedPkgBetter = false;
6954        // First check if this is a system package that may involve an update
6955        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6956            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6957            // it needs to drop FLAG_PRIVILEGED.
6958            if (locationIsPrivileged(scanFile)) {
6959                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6960            } else {
6961                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6962            }
6963
6964            if (ps != null && !ps.codePath.equals(scanFile)) {
6965                // The path has changed from what was last scanned...  check the
6966                // version of the new path against what we have stored to determine
6967                // what to do.
6968                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6969                if (pkg.mVersionCode <= ps.versionCode) {
6970                    // The system package has been updated and the code path does not match
6971                    // Ignore entry. Skip it.
6972                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6973                            + " ignored: updated version " + ps.versionCode
6974                            + " better than this " + pkg.mVersionCode);
6975                    if (!updatedPkg.codePath.equals(scanFile)) {
6976                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6977                                + ps.name + " changing from " + updatedPkg.codePathString
6978                                + " to " + scanFile);
6979                        updatedPkg.codePath = scanFile;
6980                        updatedPkg.codePathString = scanFile.toString();
6981                        updatedPkg.resourcePath = scanFile;
6982                        updatedPkg.resourcePathString = scanFile.toString();
6983                    }
6984                    updatedPkg.pkg = pkg;
6985                    updatedPkg.versionCode = pkg.mVersionCode;
6986
6987                    // Update the disabled system child packages to point to the package too.
6988                    final int childCount = updatedPkg.childPackageNames != null
6989                            ? updatedPkg.childPackageNames.size() : 0;
6990                    for (int i = 0; i < childCount; i++) {
6991                        String childPackageName = updatedPkg.childPackageNames.get(i);
6992                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6993                                childPackageName);
6994                        if (updatedChildPkg != null) {
6995                            updatedChildPkg.pkg = pkg;
6996                            updatedChildPkg.versionCode = pkg.mVersionCode;
6997                        }
6998                    }
6999
7000                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7001                            + scanFile + " ignored: updated version " + ps.versionCode
7002                            + " better than this " + pkg.mVersionCode);
7003                } else {
7004                    // The current app on the system partition is better than
7005                    // what we have updated to on the data partition; switch
7006                    // back to the system partition version.
7007                    // At this point, its safely assumed that package installation for
7008                    // apps in system partition will go through. If not there won't be a working
7009                    // version of the app
7010                    // writer
7011                    synchronized (mPackages) {
7012                        // Just remove the loaded entries from package lists.
7013                        mPackages.remove(ps.name);
7014                    }
7015
7016                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7017                            + " reverting from " + ps.codePathString
7018                            + ": new version " + pkg.mVersionCode
7019                            + " better than installed " + ps.versionCode);
7020
7021                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7022                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7023                    synchronized (mInstallLock) {
7024                        args.cleanUpResourcesLI();
7025                    }
7026                    synchronized (mPackages) {
7027                        mSettings.enableSystemPackageLPw(ps.name);
7028                    }
7029                    updatedPkgBetter = true;
7030                }
7031            }
7032        }
7033
7034        if (updatedPkg != null) {
7035            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7036            // initially
7037            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7038
7039            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7040            // flag set initially
7041            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7042                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7043            }
7044        }
7045
7046        // Verify certificates against what was last scanned
7047        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7048
7049        /*
7050         * A new system app appeared, but we already had a non-system one of the
7051         * same name installed earlier.
7052         */
7053        boolean shouldHideSystemApp = false;
7054        if (updatedPkg == null && ps != null
7055                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7056            /*
7057             * Check to make sure the signatures match first. If they don't,
7058             * wipe the installed application and its data.
7059             */
7060            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7061                    != PackageManager.SIGNATURE_MATCH) {
7062                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7063                        + " signatures don't match existing userdata copy; removing");
7064                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7065                        "scanPackageInternalLI")) {
7066                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7067                }
7068                ps = null;
7069            } else {
7070                /*
7071                 * If the newly-added system app is an older version than the
7072                 * already installed version, hide it. It will be scanned later
7073                 * and re-added like an update.
7074                 */
7075                if (pkg.mVersionCode <= ps.versionCode) {
7076                    shouldHideSystemApp = true;
7077                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7078                            + " but new version " + pkg.mVersionCode + " better than installed "
7079                            + ps.versionCode + "; hiding system");
7080                } else {
7081                    /*
7082                     * The newly found system app is a newer version that the
7083                     * one previously installed. Simply remove the
7084                     * already-installed application and replace it with our own
7085                     * while keeping the application data.
7086                     */
7087                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7088                            + " reverting from " + ps.codePathString + ": new version "
7089                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7090                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7091                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7092                    synchronized (mInstallLock) {
7093                        args.cleanUpResourcesLI();
7094                    }
7095                }
7096            }
7097        }
7098
7099        // The apk is forward locked (not public) if its code and resources
7100        // are kept in different files. (except for app in either system or
7101        // vendor path).
7102        // TODO grab this value from PackageSettings
7103        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7104            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7105                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7106            }
7107        }
7108
7109        // TODO: extend to support forward-locked splits
7110        String resourcePath = null;
7111        String baseResourcePath = null;
7112        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7113            if (ps != null && ps.resourcePathString != null) {
7114                resourcePath = ps.resourcePathString;
7115                baseResourcePath = ps.resourcePathString;
7116            } else {
7117                // Should not happen at all. Just log an error.
7118                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7119            }
7120        } else {
7121            resourcePath = pkg.codePath;
7122            baseResourcePath = pkg.baseCodePath;
7123        }
7124
7125        // Set application objects path explicitly.
7126        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7127        pkg.setApplicationInfoCodePath(pkg.codePath);
7128        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7129        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7130        pkg.setApplicationInfoResourcePath(resourcePath);
7131        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7132        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7133
7134        // Note that we invoke the following method only if we are about to unpack an application
7135        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7136                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7137
7138        /*
7139         * If the system app should be overridden by a previously installed
7140         * data, hide the system app now and let the /data/app scan pick it up
7141         * again.
7142         */
7143        if (shouldHideSystemApp) {
7144            synchronized (mPackages) {
7145                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7146            }
7147        }
7148
7149        return scannedPkg;
7150    }
7151
7152    private static String fixProcessName(String defProcessName,
7153            String processName) {
7154        if (processName == null) {
7155            return defProcessName;
7156        }
7157        return processName;
7158    }
7159
7160    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7161            throws PackageManagerException {
7162        if (pkgSetting.signatures.mSignatures != null) {
7163            // Already existing package. Make sure signatures match
7164            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7165                    == PackageManager.SIGNATURE_MATCH;
7166            if (!match) {
7167                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7168                        == PackageManager.SIGNATURE_MATCH;
7169            }
7170            if (!match) {
7171                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7172                        == PackageManager.SIGNATURE_MATCH;
7173            }
7174            if (!match) {
7175                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7176                        + pkg.packageName + " signatures do not match the "
7177                        + "previously installed version; ignoring!");
7178            }
7179        }
7180
7181        // Check for shared user signatures
7182        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7183            // Already existing package. Make sure signatures match
7184            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7185                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7186            if (!match) {
7187                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7188                        == PackageManager.SIGNATURE_MATCH;
7189            }
7190            if (!match) {
7191                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7192                        == PackageManager.SIGNATURE_MATCH;
7193            }
7194            if (!match) {
7195                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7196                        "Package " + pkg.packageName
7197                        + " has no signatures that match those in shared user "
7198                        + pkgSetting.sharedUser.name + "; ignoring!");
7199            }
7200        }
7201    }
7202
7203    /**
7204     * Enforces that only the system UID or root's UID can call a method exposed
7205     * via Binder.
7206     *
7207     * @param message used as message if SecurityException is thrown
7208     * @throws SecurityException if the caller is not system or root
7209     */
7210    private static final void enforceSystemOrRoot(String message) {
7211        final int uid = Binder.getCallingUid();
7212        if (uid != Process.SYSTEM_UID && uid != 0) {
7213            throw new SecurityException(message);
7214        }
7215    }
7216
7217    @Override
7218    public void performFstrimIfNeeded() {
7219        enforceSystemOrRoot("Only the system can request fstrim");
7220
7221        // Before everything else, see whether we need to fstrim.
7222        try {
7223            IMountService ms = PackageHelper.getMountService();
7224            if (ms != null) {
7225                boolean doTrim = false;
7226                final long interval = android.provider.Settings.Global.getLong(
7227                        mContext.getContentResolver(),
7228                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7229                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7230                if (interval > 0) {
7231                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7232                    if (timeSinceLast > interval) {
7233                        doTrim = true;
7234                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7235                                + "; running immediately");
7236                    }
7237                }
7238                if (doTrim) {
7239                    final boolean dexOptDialogShown;
7240                    synchronized (mPackages) {
7241                        dexOptDialogShown = mDexOptDialogShown;
7242                    }
7243                    if (!isFirstBoot() && dexOptDialogShown) {
7244                        try {
7245                            ActivityManagerNative.getDefault().showBootMessage(
7246                                    mContext.getResources().getString(
7247                                            R.string.android_upgrading_fstrim), true);
7248                        } catch (RemoteException e) {
7249                        }
7250                    }
7251                    ms.runMaintenance();
7252                }
7253            } else {
7254                Slog.e(TAG, "Mount service unavailable!");
7255            }
7256        } catch (RemoteException e) {
7257            // Can't happen; MountService is local
7258        }
7259    }
7260
7261    @Override
7262    public void updatePackagesIfNeeded() {
7263        enforceSystemOrRoot("Only the system can request package update");
7264
7265        // We need to re-extract after an OTA.
7266        boolean causeUpgrade = isUpgrade();
7267
7268        // First boot or factory reset.
7269        // Note: we also handle devices that are upgrading to N right now as if it is their
7270        //       first boot, as they do not have profile data.
7271        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7272
7273        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7274        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7275
7276        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7277            return;
7278        }
7279
7280        List<PackageParser.Package> pkgs;
7281        synchronized (mPackages) {
7282            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7283        }
7284
7285        final long startTime = System.nanoTime();
7286        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7287                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7288
7289        final int elapsedTimeSeconds =
7290                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7291
7292        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7293        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7294        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7295        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7296        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7297    }
7298
7299    /**
7300     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7301     * containing statistics about the invocation. The array consists of three elements,
7302     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7303     * and {@code numberOfPackagesFailed}.
7304     */
7305    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7306            String compilerFilter) {
7307
7308        int numberOfPackagesVisited = 0;
7309        int numberOfPackagesOptimized = 0;
7310        int numberOfPackagesSkipped = 0;
7311        int numberOfPackagesFailed = 0;
7312        final int numberOfPackagesToDexopt = pkgs.size();
7313
7314        for (PackageParser.Package pkg : pkgs) {
7315            numberOfPackagesVisited++;
7316
7317            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7318                if (DEBUG_DEXOPT) {
7319                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7320                }
7321                numberOfPackagesSkipped++;
7322                continue;
7323            }
7324
7325            if (DEBUG_DEXOPT) {
7326                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7327                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7328            }
7329
7330            if (showDialog) {
7331                try {
7332                    ActivityManagerNative.getDefault().showBootMessage(
7333                            mContext.getResources().getString(R.string.android_upgrading_apk,
7334                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7335                } catch (RemoteException e) {
7336                }
7337                synchronized (mPackages) {
7338                    mDexOptDialogShown = true;
7339                }
7340            }
7341
7342            // If the OTA updates a system app which was previously preopted to a non-preopted state
7343            // the app might end up being verified at runtime. That's because by default the apps
7344            // are verify-profile but for preopted apps there's no profile.
7345            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7346            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7347            // filter (by default interpret-only).
7348            // Note that at this stage unused apps are already filtered.
7349            if (isSystemApp(pkg) &&
7350                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7351                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7352                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7353            }
7354
7355            // If the OTA updates a system app which was previously preopted to a non-preopted state
7356            // the app might end up being verified at runtime. That's because by default the apps
7357            // are verify-profile but for preopted apps there's no profile.
7358            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7359            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7360            // filter (by default interpret-only).
7361            // Note that at this stage unused apps are already filtered.
7362            if (isSystemApp(pkg) &&
7363                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7364                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7365                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7366            }
7367
7368            // checkProfiles is false to avoid merging profiles during boot which
7369            // might interfere with background compilation (b/28612421).
7370            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7371            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7372            // trade-off worth doing to save boot time work.
7373            int dexOptStatus = performDexOptTraced(pkg.packageName,
7374                    false /* checkProfiles */,
7375                    compilerFilter,
7376                    false /* force */);
7377            switch (dexOptStatus) {
7378                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7379                    numberOfPackagesOptimized++;
7380                    break;
7381                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7382                    numberOfPackagesSkipped++;
7383                    break;
7384                case PackageDexOptimizer.DEX_OPT_FAILED:
7385                    numberOfPackagesFailed++;
7386                    break;
7387                default:
7388                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7389                    break;
7390            }
7391        }
7392
7393        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7394                numberOfPackagesFailed };
7395    }
7396
7397    @Override
7398    public void notifyPackageUse(String packageName, int reason) {
7399        synchronized (mPackages) {
7400            PackageParser.Package p = mPackages.get(packageName);
7401            if (p == null) {
7402                return;
7403            }
7404            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7405        }
7406    }
7407
7408    // TODO: this is not used nor needed. Delete it.
7409    @Override
7410    public boolean performDexOptIfNeeded(String packageName) {
7411        int dexOptStatus = performDexOptTraced(packageName,
7412                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7413        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7414    }
7415
7416    @Override
7417    public boolean performDexOpt(String packageName,
7418            boolean checkProfiles, int compileReason, boolean force) {
7419        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7420                getCompilerFilterForReason(compileReason), force);
7421        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7422    }
7423
7424    @Override
7425    public boolean performDexOptMode(String packageName,
7426            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7427        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7428                targetCompilerFilter, force);
7429        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7430    }
7431
7432    private int performDexOptTraced(String packageName,
7433                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7435        try {
7436            return performDexOptInternal(packageName, checkProfiles,
7437                    targetCompilerFilter, force);
7438        } finally {
7439            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7440        }
7441    }
7442
7443    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7444    // if the package can now be considered up to date for the given filter.
7445    private int performDexOptInternal(String packageName,
7446                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7447        PackageParser.Package p;
7448        synchronized (mPackages) {
7449            p = mPackages.get(packageName);
7450            if (p == null) {
7451                // Package could not be found. Report failure.
7452                return PackageDexOptimizer.DEX_OPT_FAILED;
7453            }
7454            mPackageUsage.maybeWriteAsync(mPackages);
7455            mCompilerStats.maybeWriteAsync();
7456        }
7457        long callingId = Binder.clearCallingIdentity();
7458        try {
7459            synchronized (mInstallLock) {
7460                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7461                        targetCompilerFilter, force);
7462            }
7463        } finally {
7464            Binder.restoreCallingIdentity(callingId);
7465        }
7466    }
7467
7468    public ArraySet<String> getOptimizablePackages() {
7469        ArraySet<String> pkgs = new ArraySet<String>();
7470        synchronized (mPackages) {
7471            for (PackageParser.Package p : mPackages.values()) {
7472                if (PackageDexOptimizer.canOptimizePackage(p)) {
7473                    pkgs.add(p.packageName);
7474                }
7475            }
7476        }
7477        return pkgs;
7478    }
7479
7480    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7481            boolean checkProfiles, String targetCompilerFilter,
7482            boolean force) {
7483        // Select the dex optimizer based on the force parameter.
7484        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7485        //       allocate an object here.
7486        PackageDexOptimizer pdo = force
7487                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7488                : mPackageDexOptimizer;
7489
7490        // Optimize all dependencies first. Note: we ignore the return value and march on
7491        // on errors.
7492        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7493        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7494        if (!deps.isEmpty()) {
7495            for (PackageParser.Package depPackage : deps) {
7496                // TODO: Analyze and investigate if we (should) profile libraries.
7497                // Currently this will do a full compilation of the library by default.
7498                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7499                        false /* checkProfiles */,
7500                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7501                        getOrCreateCompilerPackageStats(depPackage));
7502            }
7503        }
7504        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7505                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7506    }
7507
7508    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7509        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7510            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7511            Set<String> collectedNames = new HashSet<>();
7512            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7513
7514            retValue.remove(p);
7515
7516            return retValue;
7517        } else {
7518            return Collections.emptyList();
7519        }
7520    }
7521
7522    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7523            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7524        if (!collectedNames.contains(p.packageName)) {
7525            collectedNames.add(p.packageName);
7526            collected.add(p);
7527
7528            if (p.usesLibraries != null) {
7529                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7530            }
7531            if (p.usesOptionalLibraries != null) {
7532                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7533                        collectedNames);
7534            }
7535        }
7536    }
7537
7538    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7539            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7540        for (String libName : libs) {
7541            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7542            if (libPkg != null) {
7543                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7544            }
7545        }
7546    }
7547
7548    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7549        synchronized (mPackages) {
7550            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7551            if (lib != null && lib.apk != null) {
7552                return mPackages.get(lib.apk);
7553            }
7554        }
7555        return null;
7556    }
7557
7558    public void shutdown() {
7559        mPackageUsage.writeNow(mPackages);
7560        mCompilerStats.writeNow();
7561    }
7562
7563    @Override
7564    public void dumpProfiles(String packageName) {
7565        PackageParser.Package pkg;
7566        synchronized (mPackages) {
7567            pkg = mPackages.get(packageName);
7568            if (pkg == null) {
7569                throw new IllegalArgumentException("Unknown package: " + packageName);
7570            }
7571        }
7572        /* Only the shell, root, or the app user should be able to dump profiles. */
7573        int callingUid = Binder.getCallingUid();
7574        if (callingUid != Process.SHELL_UID &&
7575            callingUid != Process.ROOT_UID &&
7576            callingUid != pkg.applicationInfo.uid) {
7577            throw new SecurityException("dumpProfiles");
7578        }
7579
7580        synchronized (mInstallLock) {
7581            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7582            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7583            try {
7584                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7585                String gid = Integer.toString(sharedGid);
7586                String codePaths = TextUtils.join(";", allCodePaths);
7587                mInstaller.dumpProfiles(gid, packageName, codePaths);
7588            } catch (InstallerException e) {
7589                Slog.w(TAG, "Failed to dump profiles", e);
7590            }
7591            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7592        }
7593    }
7594
7595    @Override
7596    public void forceDexOpt(String packageName) {
7597        enforceSystemOrRoot("forceDexOpt");
7598
7599        PackageParser.Package pkg;
7600        synchronized (mPackages) {
7601            pkg = mPackages.get(packageName);
7602            if (pkg == null) {
7603                throw new IllegalArgumentException("Unknown package: " + packageName);
7604            }
7605        }
7606
7607        synchronized (mInstallLock) {
7608            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7609
7610            // Whoever is calling forceDexOpt wants a fully compiled package.
7611            // Don't use profiles since that may cause compilation to be skipped.
7612            final int res = performDexOptInternalWithDependenciesLI(pkg,
7613                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7614                    true /* force */);
7615
7616            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7617            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7618                throw new IllegalStateException("Failed to dexopt: " + res);
7619            }
7620        }
7621    }
7622
7623    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7624        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7625            Slog.w(TAG, "Unable to update from " + oldPkg.name
7626                    + " to " + newPkg.packageName
7627                    + ": old package not in system partition");
7628            return false;
7629        } else if (mPackages.get(oldPkg.name) != null) {
7630            Slog.w(TAG, "Unable to update from " + oldPkg.name
7631                    + " to " + newPkg.packageName
7632                    + ": old package still exists");
7633            return false;
7634        }
7635        return true;
7636    }
7637
7638    void removeCodePathLI(File codePath) {
7639        if (codePath.isDirectory()) {
7640            try {
7641                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7642            } catch (InstallerException e) {
7643                Slog.w(TAG, "Failed to remove code path", e);
7644            }
7645        } else {
7646            codePath.delete();
7647        }
7648    }
7649
7650    private int[] resolveUserIds(int userId) {
7651        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7652    }
7653
7654    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7655        if (pkg == null) {
7656            Slog.wtf(TAG, "Package was null!", new Throwable());
7657            return;
7658        }
7659        clearAppDataLeafLIF(pkg, userId, flags);
7660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7661        for (int i = 0; i < childCount; i++) {
7662            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7663        }
7664    }
7665
7666    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7667        final PackageSetting ps;
7668        synchronized (mPackages) {
7669            ps = mSettings.mPackages.get(pkg.packageName);
7670        }
7671        for (int realUserId : resolveUserIds(userId)) {
7672            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7673            try {
7674                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7675                        ceDataInode);
7676            } catch (InstallerException e) {
7677                Slog.w(TAG, String.valueOf(e));
7678            }
7679        }
7680    }
7681
7682    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7683        if (pkg == null) {
7684            Slog.wtf(TAG, "Package was null!", new Throwable());
7685            return;
7686        }
7687        destroyAppDataLeafLIF(pkg, userId, flags);
7688        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7689        for (int i = 0; i < childCount; i++) {
7690            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7691        }
7692    }
7693
7694    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7695        final PackageSetting ps;
7696        synchronized (mPackages) {
7697            ps = mSettings.mPackages.get(pkg.packageName);
7698        }
7699        for (int realUserId : resolveUserIds(userId)) {
7700            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7701            try {
7702                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7703                        ceDataInode);
7704            } catch (InstallerException e) {
7705                Slog.w(TAG, String.valueOf(e));
7706            }
7707        }
7708    }
7709
7710    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7711        if (pkg == null) {
7712            Slog.wtf(TAG, "Package was null!", new Throwable());
7713            return;
7714        }
7715        destroyAppProfilesLeafLIF(pkg);
7716        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7718        for (int i = 0; i < childCount; i++) {
7719            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7720            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7721                    true /* removeBaseMarker */);
7722        }
7723    }
7724
7725    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7726            boolean removeBaseMarker) {
7727        if (pkg.isForwardLocked()) {
7728            return;
7729        }
7730
7731        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7732            try {
7733                path = PackageManagerServiceUtils.realpath(new File(path));
7734            } catch (IOException e) {
7735                // TODO: Should we return early here ?
7736                Slog.w(TAG, "Failed to get canonical path", e);
7737                continue;
7738            }
7739
7740            final String useMarker = path.replace('/', '@');
7741            for (int realUserId : resolveUserIds(userId)) {
7742                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7743                if (removeBaseMarker) {
7744                    File foreignUseMark = new File(profileDir, useMarker);
7745                    if (foreignUseMark.exists()) {
7746                        if (!foreignUseMark.delete()) {
7747                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7748                                    + pkg.packageName);
7749                        }
7750                    }
7751                }
7752
7753                File[] markers = profileDir.listFiles();
7754                if (markers != null) {
7755                    final String searchString = "@" + pkg.packageName + "@";
7756                    // We also delete all markers that contain the package name we're
7757                    // uninstalling. These are associated with secondary dex-files belonging
7758                    // to the package. Reconstructing the path of these dex files is messy
7759                    // in general.
7760                    for (File marker : markers) {
7761                        if (marker.getName().indexOf(searchString) > 0) {
7762                            if (!marker.delete()) {
7763                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7764                                    + pkg.packageName);
7765                            }
7766                        }
7767                    }
7768                }
7769            }
7770        }
7771    }
7772
7773    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7774        try {
7775            mInstaller.destroyAppProfiles(pkg.packageName);
7776        } catch (InstallerException e) {
7777            Slog.w(TAG, String.valueOf(e));
7778        }
7779    }
7780
7781    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7782        if (pkg == null) {
7783            Slog.wtf(TAG, "Package was null!", new Throwable());
7784            return;
7785        }
7786        clearAppProfilesLeafLIF(pkg);
7787        // We don't remove the base foreign use marker when clearing profiles because
7788        // we will rename it when the app is updated. Unlike the actual profile contents,
7789        // the foreign use marker is good across installs.
7790        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7791        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7792        for (int i = 0; i < childCount; i++) {
7793            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7794        }
7795    }
7796
7797    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7798        try {
7799            mInstaller.clearAppProfiles(pkg.packageName);
7800        } catch (InstallerException e) {
7801            Slog.w(TAG, String.valueOf(e));
7802        }
7803    }
7804
7805    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7806            long lastUpdateTime) {
7807        // Set parent install/update time
7808        PackageSetting ps = (PackageSetting) pkg.mExtras;
7809        if (ps != null) {
7810            ps.firstInstallTime = firstInstallTime;
7811            ps.lastUpdateTime = lastUpdateTime;
7812        }
7813        // Set children install/update time
7814        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7815        for (int i = 0; i < childCount; i++) {
7816            PackageParser.Package childPkg = pkg.childPackages.get(i);
7817            ps = (PackageSetting) childPkg.mExtras;
7818            if (ps != null) {
7819                ps.firstInstallTime = firstInstallTime;
7820                ps.lastUpdateTime = lastUpdateTime;
7821            }
7822        }
7823    }
7824
7825    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7826            PackageParser.Package changingLib) {
7827        if (file.path != null) {
7828            usesLibraryFiles.add(file.path);
7829            return;
7830        }
7831        PackageParser.Package p = mPackages.get(file.apk);
7832        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7833            // If we are doing this while in the middle of updating a library apk,
7834            // then we need to make sure to use that new apk for determining the
7835            // dependencies here.  (We haven't yet finished committing the new apk
7836            // to the package manager state.)
7837            if (p == null || p.packageName.equals(changingLib.packageName)) {
7838                p = changingLib;
7839            }
7840        }
7841        if (p != null) {
7842            usesLibraryFiles.addAll(p.getAllCodePaths());
7843        }
7844    }
7845
7846    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7847            PackageParser.Package changingLib) throws PackageManagerException {
7848        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7849            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7850            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7851            for (int i=0; i<N; i++) {
7852                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7853                if (file == null) {
7854                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7855                            "Package " + pkg.packageName + " requires unavailable shared library "
7856                            + pkg.usesLibraries.get(i) + "; failing!");
7857                }
7858                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7859            }
7860            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7861            for (int i=0; i<N; i++) {
7862                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7863                if (file == null) {
7864                    Slog.w(TAG, "Package " + pkg.packageName
7865                            + " desires unavailable shared library "
7866                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7867                } else {
7868                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7869                }
7870            }
7871            N = usesLibraryFiles.size();
7872            if (N > 0) {
7873                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7874            } else {
7875                pkg.usesLibraryFiles = null;
7876            }
7877        }
7878    }
7879
7880    private static boolean hasString(List<String> list, List<String> which) {
7881        if (list == null) {
7882            return false;
7883        }
7884        for (int i=list.size()-1; i>=0; i--) {
7885            for (int j=which.size()-1; j>=0; j--) {
7886                if (which.get(j).equals(list.get(i))) {
7887                    return true;
7888                }
7889            }
7890        }
7891        return false;
7892    }
7893
7894    private void updateAllSharedLibrariesLPw() {
7895        for (PackageParser.Package pkg : mPackages.values()) {
7896            try {
7897                updateSharedLibrariesLPr(pkg, null);
7898            } catch (PackageManagerException e) {
7899                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7900            }
7901        }
7902    }
7903
7904    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7905            PackageParser.Package changingPkg) {
7906        ArrayList<PackageParser.Package> res = null;
7907        for (PackageParser.Package pkg : mPackages.values()) {
7908            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7909                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7910                if (res == null) {
7911                    res = new ArrayList<PackageParser.Package>();
7912                }
7913                res.add(pkg);
7914                try {
7915                    updateSharedLibrariesLPr(pkg, changingPkg);
7916                } catch (PackageManagerException e) {
7917                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7918                }
7919            }
7920        }
7921        return res;
7922    }
7923
7924    /**
7925     * Derive the value of the {@code cpuAbiOverride} based on the provided
7926     * value and an optional stored value from the package settings.
7927     */
7928    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7929        String cpuAbiOverride = null;
7930
7931        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7932            cpuAbiOverride = null;
7933        } else if (abiOverride != null) {
7934            cpuAbiOverride = abiOverride;
7935        } else if (settings != null) {
7936            cpuAbiOverride = settings.cpuAbiOverrideString;
7937        }
7938
7939        return cpuAbiOverride;
7940    }
7941
7942    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7943            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7944                    throws PackageManagerException {
7945        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7946        // If the package has children and this is the first dive in the function
7947        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7948        // whether all packages (parent and children) would be successfully scanned
7949        // before the actual scan since scanning mutates internal state and we want
7950        // to atomically install the package and its children.
7951        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7952            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7953                scanFlags |= SCAN_CHECK_ONLY;
7954            }
7955        } else {
7956            scanFlags &= ~SCAN_CHECK_ONLY;
7957        }
7958
7959        final PackageParser.Package scannedPkg;
7960        try {
7961            // Scan the parent
7962            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7963            // Scan the children
7964            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7965            for (int i = 0; i < childCount; i++) {
7966                PackageParser.Package childPkg = pkg.childPackages.get(i);
7967                scanPackageLI(childPkg, policyFlags,
7968                        scanFlags, currentTime, user);
7969            }
7970        } finally {
7971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7972        }
7973
7974        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7975            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7976        }
7977
7978        return scannedPkg;
7979    }
7980
7981    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7982            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7983        boolean success = false;
7984        try {
7985            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7986                    currentTime, user);
7987            success = true;
7988            return res;
7989        } finally {
7990            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7991                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7992                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7993                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7994                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7995            }
7996        }
7997    }
7998
7999    /**
8000     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8001     */
8002    private static boolean apkHasCode(String fileName) {
8003        StrictJarFile jarFile = null;
8004        try {
8005            jarFile = new StrictJarFile(fileName,
8006                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8007            return jarFile.findEntry("classes.dex") != null;
8008        } catch (IOException ignore) {
8009        } finally {
8010            try {
8011                if (jarFile != null) {
8012                    jarFile.close();
8013                }
8014            } catch (IOException ignore) {}
8015        }
8016        return false;
8017    }
8018
8019    /**
8020     * Enforces code policy for the package. This ensures that if an APK has
8021     * declared hasCode="true" in its manifest that the APK actually contains
8022     * code.
8023     *
8024     * @throws PackageManagerException If bytecode could not be found when it should exist
8025     */
8026    private static void assertCodePolicy(PackageParser.Package pkg)
8027            throws PackageManagerException {
8028        final boolean shouldHaveCode =
8029                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8030        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8031            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8032                    "Package " + pkg.baseCodePath + " code is missing");
8033        }
8034
8035        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8036            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8037                final boolean splitShouldHaveCode =
8038                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8039                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8040                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8041                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8042                }
8043            }
8044        }
8045    }
8046
8047    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8048            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8049                    throws PackageManagerException {
8050        if (DEBUG_PACKAGE_SCANNING) {
8051            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8052                Log.d(TAG, "Scanning package " + pkg.packageName);
8053        }
8054
8055        applyPolicy(pkg, policyFlags);
8056
8057        assertPackageIsValid(pkg, policyFlags);
8058
8059        // Initialize package source and resource directories
8060        final File scanFile = new File(pkg.codePath);
8061        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8062        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8063
8064        SharedUserSetting suid = null;
8065        PackageSetting pkgSetting = null;
8066
8067        // Getting the package setting may have a side-effect, so if we
8068        // are only checking if scan would succeed, stash a copy of the
8069        // old setting to restore at the end.
8070        PackageSetting nonMutatedPs = null;
8071
8072        // writer
8073        synchronized (mPackages) {
8074            if (pkg.mSharedUserId != null) {
8075                // SIDE EFFECTS; may potentially allocate a new shared user
8076                suid = mSettings.getSharedUserLPw(
8077                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8078                if (DEBUG_PACKAGE_SCANNING) {
8079                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8080                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8081                                + "): packages=" + suid.packages);
8082                }
8083            }
8084
8085            // Check if we are renaming from an original package name.
8086            PackageSetting origPackage = null;
8087            String realName = null;
8088            if (pkg.mOriginalPackages != null) {
8089                // This package may need to be renamed to a previously
8090                // installed name.  Let's check on that...
8091                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8092                if (pkg.mOriginalPackages.contains(renamed)) {
8093                    // This package had originally been installed as the
8094                    // original name, and we have already taken care of
8095                    // transitioning to the new one.  Just update the new
8096                    // one to continue using the old name.
8097                    realName = pkg.mRealPackage;
8098                    if (!pkg.packageName.equals(renamed)) {
8099                        // Callers into this function may have already taken
8100                        // care of renaming the package; only do it here if
8101                        // it is not already done.
8102                        pkg.setPackageName(renamed);
8103                    }
8104                } else {
8105                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8106                        if ((origPackage = mSettings.getPackageLPr(
8107                                pkg.mOriginalPackages.get(i))) != null) {
8108                            // We do have the package already installed under its
8109                            // original name...  should we use it?
8110                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8111                                // New package is not compatible with original.
8112                                origPackage = null;
8113                                continue;
8114                            } else if (origPackage.sharedUser != null) {
8115                                // Make sure uid is compatible between packages.
8116                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8117                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8118                                            + " to " + pkg.packageName + ": old uid "
8119                                            + origPackage.sharedUser.name
8120                                            + " differs from " + pkg.mSharedUserId);
8121                                    origPackage = null;
8122                                    continue;
8123                                }
8124                                // TODO: Add case when shared user id is added [b/28144775]
8125                            } else {
8126                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8127                                        + pkg.packageName + " to old name " + origPackage.name);
8128                            }
8129                            break;
8130                        }
8131                    }
8132                }
8133            }
8134
8135            if (mTransferedPackages.contains(pkg.packageName)) {
8136                Slog.w(TAG, "Package " + pkg.packageName
8137                        + " was transferred to another, but its .apk remains");
8138            }
8139
8140            // See comments in nonMutatedPs declaration
8141            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8142                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8143                if (foundPs != null) {
8144                    nonMutatedPs = new PackageSetting(foundPs);
8145                }
8146            }
8147
8148            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8149            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8150                PackageManagerService.reportSettingsProblem(Log.WARN,
8151                        "Package " + pkg.packageName + " shared user changed from "
8152                                + (pkgSetting.sharedUser != null
8153                                        ? pkgSetting.sharedUser.name : "<nothing>")
8154                                + " to "
8155                                + (suid != null ? suid.name : "<nothing>")
8156                                + "; replacing with new");
8157                pkgSetting = null;
8158            }
8159            final PackageSetting oldPkgSetting =
8160                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8161            final PackageSetting disabledPkgSetting =
8162                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8163            if (pkgSetting == null) {
8164                final String parentPackageName = (pkg.parentPackage != null)
8165                        ? pkg.parentPackage.packageName : null;
8166                // REMOVE SharedUserSetting from method; update in a separate call
8167                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8168                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8169                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8170                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8171                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8172                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8173                        UserManagerService.getInstance());
8174                // SIDE EFFECTS; updates system state; move elsewhere
8175                if (origPackage != null) {
8176                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8177                }
8178                mSettings.addUserToSettingLPw(pkgSetting);
8179            } else {
8180                // REMOVE SharedUserSetting from method; update in a separate call
8181                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8182                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8183                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8184                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8185                        UserManagerService.getInstance());
8186            }
8187            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8188            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8189
8190            // SIDE EFFECTS; modifies system state; move elsewhere
8191            if (pkgSetting.origPackage != null) {
8192                // If we are first transitioning from an original package,
8193                // fix up the new package's name now.  We need to do this after
8194                // looking up the package under its new name, so getPackageLP
8195                // can take care of fiddling things correctly.
8196                pkg.setPackageName(origPackage.name);
8197
8198                // File a report about this.
8199                String msg = "New package " + pkgSetting.realName
8200                        + " renamed to replace old package " + pkgSetting.name;
8201                reportSettingsProblem(Log.WARN, msg);
8202
8203                // Make a note of it.
8204                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8205                    mTransferedPackages.add(origPackage.name);
8206                }
8207
8208                // No longer need to retain this.
8209                pkgSetting.origPackage = null;
8210            }
8211
8212            // SIDE EFFECTS; modifies system state; move elsewhere
8213            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8214                // Make a note of it.
8215                mTransferedPackages.add(pkg.packageName);
8216            }
8217
8218            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8219                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8220            }
8221
8222            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8223                // Check all shared libraries and map to their actual file path.
8224                // We only do this here for apps not on a system dir, because those
8225                // are the only ones that can fail an install due to this.  We
8226                // will take care of the system apps by updating all of their
8227                // library paths after the scan is done.
8228                updateSharedLibrariesLPr(pkg, null);
8229            }
8230
8231            if (mFoundPolicyFile) {
8232                SELinuxMMAC.assignSeinfoValue(pkg);
8233            }
8234
8235            pkg.applicationInfo.uid = pkgSetting.appId;
8236            pkg.mExtras = pkgSetting;
8237            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8238                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8239                    // We just determined the app is signed correctly, so bring
8240                    // over the latest parsed certs.
8241                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8242                } else {
8243                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8244                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8245                                "Package " + pkg.packageName + " upgrade keys do not match the "
8246                                + "previously installed version");
8247                    } else {
8248                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8249                        String msg = "System package " + pkg.packageName
8250                                + " signature changed; retaining data.";
8251                        reportSettingsProblem(Log.WARN, msg);
8252                    }
8253                }
8254            } else {
8255                try {
8256                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8257                    verifySignaturesLP(pkgSetting, pkg);
8258                    // We just determined the app is signed correctly, so bring
8259                    // over the latest parsed certs.
8260                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8261                } catch (PackageManagerException e) {
8262                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8263                        throw e;
8264                    }
8265                    // The signature has changed, but this package is in the system
8266                    // image...  let's recover!
8267                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8268                    // However...  if this package is part of a shared user, but it
8269                    // doesn't match the signature of the shared user, let's fail.
8270                    // What this means is that you can't change the signatures
8271                    // associated with an overall shared user, which doesn't seem all
8272                    // that unreasonable.
8273                    if (pkgSetting.sharedUser != null) {
8274                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8275                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8276                            throw new PackageManagerException(
8277                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8278                                    "Signature mismatch for shared user: "
8279                                            + pkgSetting.sharedUser);
8280                        }
8281                    }
8282                    // File a report about this.
8283                    String msg = "System package " + pkg.packageName
8284                            + " signature changed; retaining data.";
8285                    reportSettingsProblem(Log.WARN, msg);
8286                }
8287            }
8288
8289            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8290                // This package wants to adopt ownership of permissions from
8291                // another package.
8292                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8293                    final String origName = pkg.mAdoptPermissions.get(i);
8294                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8295                    if (orig != null) {
8296                        if (verifyPackageUpdateLPr(orig, pkg)) {
8297                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8298                                    + pkg.packageName);
8299                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8300                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8301                        }
8302                    }
8303                }
8304            }
8305        }
8306
8307        pkg.applicationInfo.processName = fixProcessName(
8308                pkg.applicationInfo.packageName,
8309                pkg.applicationInfo.processName);
8310
8311        if (pkg != mPlatformPackage) {
8312            // Get all of our default paths setup
8313            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8314        }
8315
8316        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8317
8318        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8319            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8320            derivePackageAbi(
8321                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8323
8324            // Some system apps still use directory structure for native libraries
8325            // in which case we might end up not detecting abi solely based on apk
8326            // structure. Try to detect abi based on directory structure.
8327            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8328                    pkg.applicationInfo.primaryCpuAbi == null) {
8329                setBundledAppAbisAndRoots(pkg, pkgSetting);
8330                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8331            }
8332        } else {
8333            if ((scanFlags & SCAN_MOVE) != 0) {
8334                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8335                // but we already have this packages package info in the PackageSetting. We just
8336                // use that and derive the native library path based on the new codepath.
8337                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8338                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8339            }
8340
8341            // Set native library paths again. For moves, the path will be updated based on the
8342            // ABIs we've determined above. For non-moves, the path will be updated based on the
8343            // ABIs we determined during compilation, but the path will depend on the final
8344            // package path (after the rename away from the stage path).
8345            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8346        }
8347
8348        // This is a special case for the "system" package, where the ABI is
8349        // dictated by the zygote configuration (and init.rc). We should keep track
8350        // of this ABI so that we can deal with "normal" applications that run under
8351        // the same UID correctly.
8352        if (mPlatformPackage == pkg) {
8353            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8354                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8355        }
8356
8357        // If there's a mismatch between the abi-override in the package setting
8358        // and the abiOverride specified for the install. Warn about this because we
8359        // would've already compiled the app without taking the package setting into
8360        // account.
8361        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8362            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8363                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8364                        " for package " + pkg.packageName);
8365            }
8366        }
8367
8368        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8369        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8370        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8371
8372        // Copy the derived override back to the parsed package, so that we can
8373        // update the package settings accordingly.
8374        pkg.cpuAbiOverride = cpuAbiOverride;
8375
8376        if (DEBUG_ABI_SELECTION) {
8377            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8378                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8379                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8380        }
8381
8382        // Push the derived path down into PackageSettings so we know what to
8383        // clean up at uninstall time.
8384        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8385
8386        if (DEBUG_ABI_SELECTION) {
8387            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8388                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8389                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8390        }
8391
8392        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8393        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8394            // We don't do this here during boot because we can do it all
8395            // at once after scanning all existing packages.
8396            //
8397            // We also do this *before* we perform dexopt on this package, so that
8398            // we can avoid redundant dexopts, and also to make sure we've got the
8399            // code and package path correct.
8400            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8401        }
8402
8403        if (mFactoryTest && pkg.requestedPermissions.contains(
8404                android.Manifest.permission.FACTORY_TEST)) {
8405            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8406        }
8407
8408        if (isSystemApp(pkg)) {
8409            pkgSetting.isOrphaned = true;
8410        }
8411
8412        // Take care of first install / last update times.
8413        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8414        if (currentTime != 0) {
8415            if (pkgSetting.firstInstallTime == 0) {
8416                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8417            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8418                pkgSetting.lastUpdateTime = currentTime;
8419            }
8420        } else if (pkgSetting.firstInstallTime == 0) {
8421            // We need *something*.  Take time time stamp of the file.
8422            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8423        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8424            if (scanFileTime != pkgSetting.timeStamp) {
8425                // A package on the system image has changed; consider this
8426                // to be an update.
8427                pkgSetting.lastUpdateTime = scanFileTime;
8428            }
8429        }
8430        pkgSetting.setTimeStamp(scanFileTime);
8431
8432        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8433            if (nonMutatedPs != null) {
8434                synchronized (mPackages) {
8435                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8436                }
8437            }
8438        } else {
8439            // Modify state for the given package setting
8440            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8441                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8442        }
8443        return pkg;
8444    }
8445
8446    /**
8447     * Applies policy to the parsed package based upon the given policy flags.
8448     * Ensures the package is in a good state.
8449     * <p>
8450     * Implementation detail: This method must NOT have any side effect. It would
8451     * ideally be static, but, it requires locks to read system state.
8452     */
8453    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8454        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8455            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8456            if (pkg.applicationInfo.isDirectBootAware()) {
8457                // we're direct boot aware; set for all components
8458                for (PackageParser.Service s : pkg.services) {
8459                    s.info.encryptionAware = s.info.directBootAware = true;
8460                }
8461                for (PackageParser.Provider p : pkg.providers) {
8462                    p.info.encryptionAware = p.info.directBootAware = true;
8463                }
8464                for (PackageParser.Activity a : pkg.activities) {
8465                    a.info.encryptionAware = a.info.directBootAware = true;
8466                }
8467                for (PackageParser.Activity r : pkg.receivers) {
8468                    r.info.encryptionAware = r.info.directBootAware = true;
8469                }
8470            }
8471        } else {
8472            // Only allow system apps to be flagged as core apps.
8473            pkg.coreApp = false;
8474            // clear flags not applicable to regular apps
8475            pkg.applicationInfo.privateFlags &=
8476                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8477            pkg.applicationInfo.privateFlags &=
8478                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8479        }
8480        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8481
8482        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8483            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8484        }
8485
8486        if (!isSystemApp(pkg)) {
8487            // Only system apps can use these features.
8488            pkg.mOriginalPackages = null;
8489            pkg.mRealPackage = null;
8490            pkg.mAdoptPermissions = null;
8491        }
8492    }
8493
8494    /**
8495     * Asserts the parsed package is valid according to teh given policy. If the
8496     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8497     * <p>
8498     * Implementation detail: This method must NOT have any side effects. It would
8499     * ideally be static, but, it requires locks to read system state.
8500     *
8501     * @throws PackageManagerException If the package fails any of the validation checks
8502     */
8503    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8504            throws PackageManagerException {
8505        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8506            assertCodePolicy(pkg);
8507        }
8508
8509        if (pkg.applicationInfo.getCodePath() == null ||
8510                pkg.applicationInfo.getResourcePath() == null) {
8511            // Bail out. The resource and code paths haven't been set.
8512            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8513                    "Code and resource paths haven't been set correctly");
8514        }
8515
8516        // Make sure we're not adding any bogus keyset info
8517        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8518        ksms.assertScannedPackageValid(pkg);
8519
8520        synchronized (mPackages) {
8521            // The special "android" package can only be defined once
8522            if (pkg.packageName.equals("android")) {
8523                if (mAndroidApplication != null) {
8524                    Slog.w(TAG, "*************************************************");
8525                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8526                    Slog.w(TAG, " codePath=" + pkg.codePath);
8527                    Slog.w(TAG, "*************************************************");
8528                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8529                            "Core android package being redefined.  Skipping.");
8530                }
8531            }
8532
8533            // A package name must be unique; don't allow duplicates
8534            if (mPackages.containsKey(pkg.packageName)
8535                    || mSharedLibraries.containsKey(pkg.packageName)) {
8536                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8537                        "Application package " + pkg.packageName
8538                        + " already installed.  Skipping duplicate.");
8539            }
8540
8541            // Only privileged apps and updated privileged apps can add child packages.
8542            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8543                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8544                    throw new PackageManagerException("Only privileged apps can add child "
8545                            + "packages. Ignoring package " + pkg.packageName);
8546                }
8547                final int childCount = pkg.childPackages.size();
8548                for (int i = 0; i < childCount; i++) {
8549                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8550                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8551                            childPkg.packageName)) {
8552                        throw new PackageManagerException("Can't override child of "
8553                                + "another disabled app. Ignoring package " + pkg.packageName);
8554                    }
8555                }
8556            }
8557
8558            // If we're only installing presumed-existing packages, require that the
8559            // scanned APK is both already known and at the path previously established
8560            // for it.  Previously unknown packages we pick up normally, but if we have an
8561            // a priori expectation about this package's install presence, enforce it.
8562            // With a singular exception for new system packages. When an OTA contains
8563            // a new system package, we allow the codepath to change from a system location
8564            // to the user-installed location. If we don't allow this change, any newer,
8565            // user-installed version of the application will be ignored.
8566            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8567                if (mExpectingBetter.containsKey(pkg.packageName)) {
8568                    logCriticalInfo(Log.WARN,
8569                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8570                } else {
8571                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8572                    if (known != null) {
8573                        if (DEBUG_PACKAGE_SCANNING) {
8574                            Log.d(TAG, "Examining " + pkg.codePath
8575                                    + " and requiring known paths " + known.codePathString
8576                                    + " & " + known.resourcePathString);
8577                        }
8578                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8579                                || !pkg.applicationInfo.getResourcePath().equals(
8580                                        known.resourcePathString)) {
8581                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8582                                    "Application package " + pkg.packageName
8583                                    + " found at " + pkg.applicationInfo.getCodePath()
8584                                    + " but expected at " + known.codePathString
8585                                    + "; ignoring.");
8586                        }
8587                    }
8588                }
8589            }
8590
8591            // Verify that this new package doesn't have any content providers
8592            // that conflict with existing packages.  Only do this if the
8593            // package isn't already installed, since we don't want to break
8594            // things that are installed.
8595            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8596                final int N = pkg.providers.size();
8597                int i;
8598                for (i=0; i<N; i++) {
8599                    PackageParser.Provider p = pkg.providers.get(i);
8600                    if (p.info.authority != null) {
8601                        String names[] = p.info.authority.split(";");
8602                        for (int j = 0; j < names.length; j++) {
8603                            if (mProvidersByAuthority.containsKey(names[j])) {
8604                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8605                                final String otherPackageName =
8606                                        ((other != null && other.getComponentName() != null) ?
8607                                                other.getComponentName().getPackageName() : "?");
8608                                throw new PackageManagerException(
8609                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8610                                        "Can't install because provider name " + names[j]
8611                                                + " (in package " + pkg.applicationInfo.packageName
8612                                                + ") is already used by " + otherPackageName);
8613                            }
8614                        }
8615                    }
8616                }
8617            }
8618        }
8619    }
8620
8621    /**
8622     * Adds a scanned package to the system. When this method is finished, the package will
8623     * be available for query, resolution, etc...
8624     */
8625    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8626            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8627        final String pkgName = pkg.packageName;
8628        if (mCustomResolverComponentName != null &&
8629                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8630            setUpCustomResolverActivity(pkg);
8631        }
8632
8633        if (pkg.packageName.equals("android")) {
8634            synchronized (mPackages) {
8635                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8636                    // Set up information for our fall-back user intent resolution activity.
8637                    mPlatformPackage = pkg;
8638                    pkg.mVersionCode = mSdkVersion;
8639                    mAndroidApplication = pkg.applicationInfo;
8640
8641                    if (!mResolverReplaced) {
8642                        mResolveActivity.applicationInfo = mAndroidApplication;
8643                        mResolveActivity.name = ResolverActivity.class.getName();
8644                        mResolveActivity.packageName = mAndroidApplication.packageName;
8645                        mResolveActivity.processName = "system:ui";
8646                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8647                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8648                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8649                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8650                        mResolveActivity.exported = true;
8651                        mResolveActivity.enabled = true;
8652                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8653                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8654                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8655                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8656                                | ActivityInfo.CONFIG_ORIENTATION
8657                                | ActivityInfo.CONFIG_KEYBOARD
8658                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8659                        mResolveInfo.activityInfo = mResolveActivity;
8660                        mResolveInfo.priority = 0;
8661                        mResolveInfo.preferredOrder = 0;
8662                        mResolveInfo.match = 0;
8663                        mResolveComponentName = new ComponentName(
8664                                mAndroidApplication.packageName, mResolveActivity.name);
8665                    }
8666                }
8667            }
8668        }
8669
8670        ArrayList<PackageParser.Package> clientLibPkgs = null;
8671        // writer
8672        synchronized (mPackages) {
8673            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8674                // Only system apps can add new shared libraries.
8675                if (pkg.libraryNames != null) {
8676                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8677                        String name = pkg.libraryNames.get(i);
8678                        boolean allowed = false;
8679                        if (pkg.isUpdatedSystemApp()) {
8680                            // New library entries can only be added through the
8681                            // system image.  This is important to get rid of a lot
8682                            // of nasty edge cases: for example if we allowed a non-
8683                            // system update of the app to add a library, then uninstalling
8684                            // the update would make the library go away, and assumptions
8685                            // we made such as through app install filtering would now
8686                            // have allowed apps on the device which aren't compatible
8687                            // with it.  Better to just have the restriction here, be
8688                            // conservative, and create many fewer cases that can negatively
8689                            // impact the user experience.
8690                            final PackageSetting sysPs = mSettings
8691                                    .getDisabledSystemPkgLPr(pkg.packageName);
8692                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8693                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8694                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8695                                        allowed = true;
8696                                        break;
8697                                    }
8698                                }
8699                            }
8700                        } else {
8701                            allowed = true;
8702                        }
8703                        if (allowed) {
8704                            if (!mSharedLibraries.containsKey(name)) {
8705                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8706                            } else if (!name.equals(pkg.packageName)) {
8707                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8708                                        + name + " already exists; skipping");
8709                            }
8710                        } else {
8711                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8712                                    + name + " that is not declared on system image; skipping");
8713                        }
8714                    }
8715                    if ((scanFlags & SCAN_BOOTING) == 0) {
8716                        // If we are not booting, we need to update any applications
8717                        // that are clients of our shared library.  If we are booting,
8718                        // this will all be done once the scan is complete.
8719                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8720                    }
8721                }
8722            }
8723        }
8724
8725        if ((scanFlags & SCAN_BOOTING) != 0) {
8726            // No apps can run during boot scan, so they don't need to be frozen
8727        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8728            // Caller asked to not kill app, so it's probably not frozen
8729        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8730            // Caller asked us to ignore frozen check for some reason; they
8731            // probably didn't know the package name
8732        } else {
8733            // We're doing major surgery on this package, so it better be frozen
8734            // right now to keep it from launching
8735            checkPackageFrozen(pkgName);
8736        }
8737
8738        // Also need to kill any apps that are dependent on the library.
8739        if (clientLibPkgs != null) {
8740            for (int i=0; i<clientLibPkgs.size(); i++) {
8741                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8742                killApplication(clientPkg.applicationInfo.packageName,
8743                        clientPkg.applicationInfo.uid, "update lib");
8744            }
8745        }
8746
8747        // writer
8748        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8749
8750        boolean createIdmapFailed = false;
8751        synchronized (mPackages) {
8752            // We don't expect installation to fail beyond this point
8753
8754            if (pkgSetting.pkg != null) {
8755                // Note that |user| might be null during the initial boot scan. If a codePath
8756                // for an app has changed during a boot scan, it's due to an app update that's
8757                // part of the system partition and marker changes must be applied to all users.
8758                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8759                final int[] userIds = resolveUserIds(userId);
8760                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8761            }
8762
8763            // Add the new setting to mSettings
8764            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8765            // Add the new setting to mPackages
8766            mPackages.put(pkg.applicationInfo.packageName, pkg);
8767            // Make sure we don't accidentally delete its data.
8768            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8769            while (iter.hasNext()) {
8770                PackageCleanItem item = iter.next();
8771                if (pkgName.equals(item.packageName)) {
8772                    iter.remove();
8773                }
8774            }
8775
8776            // Add the package's KeySets to the global KeySetManagerService
8777            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8778            ksms.addScannedPackageLPw(pkg);
8779
8780            int N = pkg.providers.size();
8781            StringBuilder r = null;
8782            int i;
8783            for (i=0; i<N; i++) {
8784                PackageParser.Provider p = pkg.providers.get(i);
8785                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8786                        p.info.processName);
8787                mProviders.addProvider(p);
8788                p.syncable = p.info.isSyncable;
8789                if (p.info.authority != null) {
8790                    String names[] = p.info.authority.split(";");
8791                    p.info.authority = null;
8792                    for (int j = 0; j < names.length; j++) {
8793                        if (j == 1 && p.syncable) {
8794                            // We only want the first authority for a provider to possibly be
8795                            // syncable, so if we already added this provider using a different
8796                            // authority clear the syncable flag. We copy the provider before
8797                            // changing it because the mProviders object contains a reference
8798                            // to a provider that we don't want to change.
8799                            // Only do this for the second authority since the resulting provider
8800                            // object can be the same for all future authorities for this provider.
8801                            p = new PackageParser.Provider(p);
8802                            p.syncable = false;
8803                        }
8804                        if (!mProvidersByAuthority.containsKey(names[j])) {
8805                            mProvidersByAuthority.put(names[j], p);
8806                            if (p.info.authority == null) {
8807                                p.info.authority = names[j];
8808                            } else {
8809                                p.info.authority = p.info.authority + ";" + names[j];
8810                            }
8811                            if (DEBUG_PACKAGE_SCANNING) {
8812                                if (chatty)
8813                                    Log.d(TAG, "Registered content provider: " + names[j]
8814                                            + ", className = " + p.info.name + ", isSyncable = "
8815                                            + p.info.isSyncable);
8816                            }
8817                        } else {
8818                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8819                            Slog.w(TAG, "Skipping provider name " + names[j] +
8820                                    " (in package " + pkg.applicationInfo.packageName +
8821                                    "): name already used by "
8822                                    + ((other != null && other.getComponentName() != null)
8823                                            ? other.getComponentName().getPackageName() : "?"));
8824                        }
8825                    }
8826                }
8827                if (chatty) {
8828                    if (r == null) {
8829                        r = new StringBuilder(256);
8830                    } else {
8831                        r.append(' ');
8832                    }
8833                    r.append(p.info.name);
8834                }
8835            }
8836            if (r != null) {
8837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8838            }
8839
8840            N = pkg.services.size();
8841            r = null;
8842            for (i=0; i<N; i++) {
8843                PackageParser.Service s = pkg.services.get(i);
8844                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8845                        s.info.processName);
8846                mServices.addService(s);
8847                if (chatty) {
8848                    if (r == null) {
8849                        r = new StringBuilder(256);
8850                    } else {
8851                        r.append(' ');
8852                    }
8853                    r.append(s.info.name);
8854                }
8855            }
8856            if (r != null) {
8857                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8858            }
8859
8860            N = pkg.receivers.size();
8861            r = null;
8862            for (i=0; i<N; i++) {
8863                PackageParser.Activity a = pkg.receivers.get(i);
8864                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8865                        a.info.processName);
8866                mReceivers.addActivity(a, "receiver");
8867                if (chatty) {
8868                    if (r == null) {
8869                        r = new StringBuilder(256);
8870                    } else {
8871                        r.append(' ');
8872                    }
8873                    r.append(a.info.name);
8874                }
8875            }
8876            if (r != null) {
8877                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8878            }
8879
8880            N = pkg.activities.size();
8881            r = null;
8882            for (i=0; i<N; i++) {
8883                PackageParser.Activity a = pkg.activities.get(i);
8884                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8885                        a.info.processName);
8886                mActivities.addActivity(a, "activity");
8887                if (chatty) {
8888                    if (r == null) {
8889                        r = new StringBuilder(256);
8890                    } else {
8891                        r.append(' ');
8892                    }
8893                    r.append(a.info.name);
8894                }
8895            }
8896            if (r != null) {
8897                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8898            }
8899
8900            N = pkg.permissionGroups.size();
8901            r = null;
8902            for (i=0; i<N; i++) {
8903                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8904                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8905                final String curPackageName = cur == null ? null : cur.info.packageName;
8906                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8907                if (cur == null || isPackageUpdate) {
8908                    mPermissionGroups.put(pg.info.name, pg);
8909                    if (chatty) {
8910                        if (r == null) {
8911                            r = new StringBuilder(256);
8912                        } else {
8913                            r.append(' ');
8914                        }
8915                        if (isPackageUpdate) {
8916                            r.append("UPD:");
8917                        }
8918                        r.append(pg.info.name);
8919                    }
8920                } else {
8921                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8922                            + pg.info.packageName + " ignored: original from "
8923                            + cur.info.packageName);
8924                    if (chatty) {
8925                        if (r == null) {
8926                            r = new StringBuilder(256);
8927                        } else {
8928                            r.append(' ');
8929                        }
8930                        r.append("DUP:");
8931                        r.append(pg.info.name);
8932                    }
8933                }
8934            }
8935            if (r != null) {
8936                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8937            }
8938
8939            N = pkg.permissions.size();
8940            r = null;
8941            for (i=0; i<N; i++) {
8942                PackageParser.Permission p = pkg.permissions.get(i);
8943
8944                // Assume by default that we did not install this permission into the system.
8945                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8946
8947                // Now that permission groups have a special meaning, we ignore permission
8948                // groups for legacy apps to prevent unexpected behavior. In particular,
8949                // permissions for one app being granted to someone just becase they happen
8950                // to be in a group defined by another app (before this had no implications).
8951                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8952                    p.group = mPermissionGroups.get(p.info.group);
8953                    // Warn for a permission in an unknown group.
8954                    if (p.info.group != null && p.group == null) {
8955                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8956                                + p.info.packageName + " in an unknown group " + p.info.group);
8957                    }
8958                }
8959
8960                ArrayMap<String, BasePermission> permissionMap =
8961                        p.tree ? mSettings.mPermissionTrees
8962                                : mSettings.mPermissions;
8963                BasePermission bp = permissionMap.get(p.info.name);
8964
8965                // Allow system apps to redefine non-system permissions
8966                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8967                    final boolean currentOwnerIsSystem = (bp.perm != null
8968                            && isSystemApp(bp.perm.owner));
8969                    if (isSystemApp(p.owner)) {
8970                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8971                            // It's a built-in permission and no owner, take ownership now
8972                            bp.packageSetting = pkgSetting;
8973                            bp.perm = p;
8974                            bp.uid = pkg.applicationInfo.uid;
8975                            bp.sourcePackage = p.info.packageName;
8976                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8977                        } else if (!currentOwnerIsSystem) {
8978                            String msg = "New decl " + p.owner + " of permission  "
8979                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8980                            reportSettingsProblem(Log.WARN, msg);
8981                            bp = null;
8982                        }
8983                    }
8984                }
8985
8986                if (bp == null) {
8987                    bp = new BasePermission(p.info.name, p.info.packageName,
8988                            BasePermission.TYPE_NORMAL);
8989                    permissionMap.put(p.info.name, bp);
8990                }
8991
8992                if (bp.perm == null) {
8993                    if (bp.sourcePackage == null
8994                            || bp.sourcePackage.equals(p.info.packageName)) {
8995                        BasePermission tree = findPermissionTreeLP(p.info.name);
8996                        if (tree == null
8997                                || tree.sourcePackage.equals(p.info.packageName)) {
8998                            bp.packageSetting = pkgSetting;
8999                            bp.perm = p;
9000                            bp.uid = pkg.applicationInfo.uid;
9001                            bp.sourcePackage = p.info.packageName;
9002                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9003                            if (chatty) {
9004                                if (r == null) {
9005                                    r = new StringBuilder(256);
9006                                } else {
9007                                    r.append(' ');
9008                                }
9009                                r.append(p.info.name);
9010                            }
9011                        } else {
9012                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9013                                    + p.info.packageName + " ignored: base tree "
9014                                    + tree.name + " is from package "
9015                                    + tree.sourcePackage);
9016                        }
9017                    } else {
9018                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9019                                + p.info.packageName + " ignored: original from "
9020                                + bp.sourcePackage);
9021                    }
9022                } else if (chatty) {
9023                    if (r == null) {
9024                        r = new StringBuilder(256);
9025                    } else {
9026                        r.append(' ');
9027                    }
9028                    r.append("DUP:");
9029                    r.append(p.info.name);
9030                }
9031                if (bp.perm == p) {
9032                    bp.protectionLevel = p.info.protectionLevel;
9033                }
9034            }
9035
9036            if (r != null) {
9037                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9038            }
9039
9040            N = pkg.instrumentation.size();
9041            r = null;
9042            for (i=0; i<N; i++) {
9043                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9044                a.info.packageName = pkg.applicationInfo.packageName;
9045                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9046                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9047                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9048                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9049                a.info.dataDir = pkg.applicationInfo.dataDir;
9050                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9051                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9052                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9053                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9054                mInstrumentation.put(a.getComponentName(), a);
9055                if (chatty) {
9056                    if (r == null) {
9057                        r = new StringBuilder(256);
9058                    } else {
9059                        r.append(' ');
9060                    }
9061                    r.append(a.info.name);
9062                }
9063            }
9064            if (r != null) {
9065                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9066            }
9067
9068            if (pkg.protectedBroadcasts != null) {
9069                N = pkg.protectedBroadcasts.size();
9070                for (i=0; i<N; i++) {
9071                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9072                }
9073            }
9074
9075            // Create idmap files for pairs of (packages, overlay packages).
9076            // Note: "android", ie framework-res.apk, is handled by native layers.
9077            if (pkg.mOverlayTarget != null) {
9078                // This is an overlay package.
9079                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9080                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9081                        mOverlays.put(pkg.mOverlayTarget,
9082                                new ArrayMap<String, PackageParser.Package>());
9083                    }
9084                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9085                    map.put(pkg.packageName, pkg);
9086                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9087                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9088                        createIdmapFailed = true;
9089                    }
9090                }
9091            } else if (mOverlays.containsKey(pkg.packageName) &&
9092                    !pkg.packageName.equals("android")) {
9093                // This is a regular package, with one or more known overlay packages.
9094                createIdmapsForPackageLI(pkg);
9095            }
9096        }
9097
9098        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9099
9100        if (createIdmapFailed) {
9101            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9102                    "scanPackageLI failed to createIdmap");
9103        }
9104    }
9105
9106    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9107            PackageParser.Package update, int[] userIds) {
9108        if (existing.applicationInfo == null || update.applicationInfo == null) {
9109            // This isn't due to an app installation.
9110            return;
9111        }
9112
9113        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9114        final File newCodePath = new File(update.applicationInfo.getCodePath());
9115
9116        // The codePath hasn't changed, so there's nothing for us to do.
9117        if (Objects.equals(oldCodePath, newCodePath)) {
9118            return;
9119        }
9120
9121        File canonicalNewCodePath;
9122        try {
9123            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9124        } catch (IOException e) {
9125            Slog.w(TAG, "Failed to get canonical path.", e);
9126            return;
9127        }
9128
9129        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9130        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9131        // that the last component of the path (i.e, the name) doesn't need canonicalization
9132        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9133        // but may change in the future. Hopefully this function won't exist at that point.
9134        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9135                oldCodePath.getName());
9136
9137        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9138        // with "@".
9139        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9140        if (!oldMarkerPrefix.endsWith("@")) {
9141            oldMarkerPrefix += "@";
9142        }
9143        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9144        if (!newMarkerPrefix.endsWith("@")) {
9145            newMarkerPrefix += "@";
9146        }
9147
9148        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9149        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9150        for (String updatedPath : updatedPaths) {
9151            String updatedPathName = new File(updatedPath).getName();
9152            markerSuffixes.add(updatedPathName.replace('/', '@'));
9153        }
9154
9155        for (int userId : userIds) {
9156            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9157
9158            for (String markerSuffix : markerSuffixes) {
9159                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9160                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9161                if (oldForeignUseMark.exists()) {
9162                    try {
9163                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9164                                newForeignUseMark.getAbsolutePath());
9165                    } catch (ErrnoException e) {
9166                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9167                        oldForeignUseMark.delete();
9168                    }
9169                }
9170            }
9171        }
9172    }
9173
9174    /**
9175     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9176     * is derived purely on the basis of the contents of {@code scanFile} and
9177     * {@code cpuAbiOverride}.
9178     *
9179     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9180     */
9181    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9182                                 String cpuAbiOverride, boolean extractLibs,
9183                                 File appLib32InstallDir)
9184            throws PackageManagerException {
9185        // TODO: We can probably be smarter about this stuff. For installed apps,
9186        // we can calculate this information at install time once and for all. For
9187        // system apps, we can probably assume that this information doesn't change
9188        // after the first boot scan. As things stand, we do lots of unnecessary work.
9189
9190        // Give ourselves some initial paths; we'll come back for another
9191        // pass once we've determined ABI below.
9192        setNativeLibraryPaths(pkg, appLib32InstallDir);
9193
9194        // We would never need to extract libs for forward-locked and external packages,
9195        // since the container service will do it for us. We shouldn't attempt to
9196        // extract libs from system app when it was not updated.
9197        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9198                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9199            extractLibs = false;
9200        }
9201
9202        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9203        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9204
9205        NativeLibraryHelper.Handle handle = null;
9206        try {
9207            handle = NativeLibraryHelper.Handle.create(pkg);
9208            // TODO(multiArch): This can be null for apps that didn't go through the
9209            // usual installation process. We can calculate it again, like we
9210            // do during install time.
9211            //
9212            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9213            // unnecessary.
9214            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9215
9216            // Null out the abis so that they can be recalculated.
9217            pkg.applicationInfo.primaryCpuAbi = null;
9218            pkg.applicationInfo.secondaryCpuAbi = null;
9219            if (isMultiArch(pkg.applicationInfo)) {
9220                // Warn if we've set an abiOverride for multi-lib packages..
9221                // By definition, we need to copy both 32 and 64 bit libraries for
9222                // such packages.
9223                if (pkg.cpuAbiOverride != null
9224                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9225                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9226                }
9227
9228                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9229                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9230                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9231                    if (extractLibs) {
9232                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9233                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9234                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9235                                useIsaSpecificSubdirs);
9236                    } else {
9237                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9238                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9239                    }
9240                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9241                }
9242
9243                maybeThrowExceptionForMultiArchCopy(
9244                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9245
9246                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9247                    if (extractLibs) {
9248                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9249                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9250                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9251                                useIsaSpecificSubdirs);
9252                    } else {
9253                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9254                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9255                    }
9256                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9257                }
9258
9259                maybeThrowExceptionForMultiArchCopy(
9260                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9261
9262                if (abi64 >= 0) {
9263                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9264                }
9265
9266                if (abi32 >= 0) {
9267                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9268                    if (abi64 >= 0) {
9269                        if (pkg.use32bitAbi) {
9270                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9271                            pkg.applicationInfo.primaryCpuAbi = abi;
9272                        } else {
9273                            pkg.applicationInfo.secondaryCpuAbi = abi;
9274                        }
9275                    } else {
9276                        pkg.applicationInfo.primaryCpuAbi = abi;
9277                    }
9278                }
9279
9280            } else {
9281                String[] abiList = (cpuAbiOverride != null) ?
9282                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9283
9284                // Enable gross and lame hacks for apps that are built with old
9285                // SDK tools. We must scan their APKs for renderscript bitcode and
9286                // not launch them if it's present. Don't bother checking on devices
9287                // that don't have 64 bit support.
9288                boolean needsRenderScriptOverride = false;
9289                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9290                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9291                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9292                    needsRenderScriptOverride = true;
9293                }
9294
9295                final int copyRet;
9296                if (extractLibs) {
9297                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9298                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9299                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9300                } else {
9301                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9302                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9303                }
9304                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9305
9306                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9307                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9308                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9309                }
9310
9311                if (copyRet >= 0) {
9312                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9313                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9314                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9315                } else if (needsRenderScriptOverride) {
9316                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9317                }
9318            }
9319        } catch (IOException ioe) {
9320            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9321        } finally {
9322            IoUtils.closeQuietly(handle);
9323        }
9324
9325        // Now that we've calculated the ABIs and determined if it's an internal app,
9326        // we will go ahead and populate the nativeLibraryPath.
9327        setNativeLibraryPaths(pkg, appLib32InstallDir);
9328    }
9329
9330    /**
9331     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9332     * i.e, so that all packages can be run inside a single process if required.
9333     *
9334     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9335     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9336     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9337     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9338     * updating a package that belongs to a shared user.
9339     *
9340     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9341     * adds unnecessary complexity.
9342     */
9343    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9344            PackageParser.Package scannedPackage) {
9345        String requiredInstructionSet = null;
9346        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9347            requiredInstructionSet = VMRuntime.getInstructionSet(
9348                     scannedPackage.applicationInfo.primaryCpuAbi);
9349        }
9350
9351        PackageSetting requirer = null;
9352        for (PackageSetting ps : packagesForUser) {
9353            // If packagesForUser contains scannedPackage, we skip it. This will happen
9354            // when scannedPackage is an update of an existing package. Without this check,
9355            // we will never be able to change the ABI of any package belonging to a shared
9356            // user, even if it's compatible with other packages.
9357            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9358                if (ps.primaryCpuAbiString == null) {
9359                    continue;
9360                }
9361
9362                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9363                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9364                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9365                    // this but there's not much we can do.
9366                    String errorMessage = "Instruction set mismatch, "
9367                            + ((requirer == null) ? "[caller]" : requirer)
9368                            + " requires " + requiredInstructionSet + " whereas " + ps
9369                            + " requires " + instructionSet;
9370                    Slog.w(TAG, errorMessage);
9371                }
9372
9373                if (requiredInstructionSet == null) {
9374                    requiredInstructionSet = instructionSet;
9375                    requirer = ps;
9376                }
9377            }
9378        }
9379
9380        if (requiredInstructionSet != null) {
9381            String adjustedAbi;
9382            if (requirer != null) {
9383                // requirer != null implies that either scannedPackage was null or that scannedPackage
9384                // did not require an ABI, in which case we have to adjust scannedPackage to match
9385                // the ABI of the set (which is the same as requirer's ABI)
9386                adjustedAbi = requirer.primaryCpuAbiString;
9387                if (scannedPackage != null) {
9388                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9389                }
9390            } else {
9391                // requirer == null implies that we're updating all ABIs in the set to
9392                // match scannedPackage.
9393                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9394            }
9395
9396            for (PackageSetting ps : packagesForUser) {
9397                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9398                    if (ps.primaryCpuAbiString != null) {
9399                        continue;
9400                    }
9401
9402                    ps.primaryCpuAbiString = adjustedAbi;
9403                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9404                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9405                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9406                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9407                                + " (requirer="
9408                                + (requirer == null ? "null" : requirer.pkg.packageName)
9409                                + ", scannedPackage="
9410                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9411                                + ")");
9412                        try {
9413                            mInstaller.rmdex(ps.codePathString,
9414                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9415                        } catch (InstallerException ignored) {
9416                        }
9417                    }
9418                }
9419            }
9420        }
9421    }
9422
9423    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9424        synchronized (mPackages) {
9425            mResolverReplaced = true;
9426            // Set up information for custom user intent resolution activity.
9427            mResolveActivity.applicationInfo = pkg.applicationInfo;
9428            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9429            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9430            mResolveActivity.processName = pkg.applicationInfo.packageName;
9431            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9432            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9433                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9434            mResolveActivity.theme = 0;
9435            mResolveActivity.exported = true;
9436            mResolveActivity.enabled = true;
9437            mResolveInfo.activityInfo = mResolveActivity;
9438            mResolveInfo.priority = 0;
9439            mResolveInfo.preferredOrder = 0;
9440            mResolveInfo.match = 0;
9441            mResolveComponentName = mCustomResolverComponentName;
9442            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9443                    mResolveComponentName);
9444        }
9445    }
9446
9447    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9448        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9449
9450        // Set up information for ephemeral installer activity
9451        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9452        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9453        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9454        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9455        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9456        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9457                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9458        mEphemeralInstallerActivity.theme = 0;
9459        mEphemeralInstallerActivity.exported = true;
9460        mEphemeralInstallerActivity.enabled = true;
9461        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9462        mEphemeralInstallerInfo.priority = 0;
9463        mEphemeralInstallerInfo.preferredOrder = 1;
9464        mEphemeralInstallerInfo.isDefault = true;
9465        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9466                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9467
9468        if (DEBUG_EPHEMERAL) {
9469            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9470        }
9471    }
9472
9473    private static String calculateBundledApkRoot(final String codePathString) {
9474        final File codePath = new File(codePathString);
9475        final File codeRoot;
9476        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9477            codeRoot = Environment.getRootDirectory();
9478        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9479            codeRoot = Environment.getOemDirectory();
9480        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9481            codeRoot = Environment.getVendorDirectory();
9482        } else {
9483            // Unrecognized code path; take its top real segment as the apk root:
9484            // e.g. /something/app/blah.apk => /something
9485            try {
9486                File f = codePath.getCanonicalFile();
9487                File parent = f.getParentFile();    // non-null because codePath is a file
9488                File tmp;
9489                while ((tmp = parent.getParentFile()) != null) {
9490                    f = parent;
9491                    parent = tmp;
9492                }
9493                codeRoot = f;
9494                Slog.w(TAG, "Unrecognized code path "
9495                        + codePath + " - using " + codeRoot);
9496            } catch (IOException e) {
9497                // Can't canonicalize the code path -- shenanigans?
9498                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9499                return Environment.getRootDirectory().getPath();
9500            }
9501        }
9502        return codeRoot.getPath();
9503    }
9504
9505    /**
9506     * Derive and set the location of native libraries for the given package,
9507     * which varies depending on where and how the package was installed.
9508     */
9509    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9510        final ApplicationInfo info = pkg.applicationInfo;
9511        final String codePath = pkg.codePath;
9512        final File codeFile = new File(codePath);
9513        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9514        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9515
9516        info.nativeLibraryRootDir = null;
9517        info.nativeLibraryRootRequiresIsa = false;
9518        info.nativeLibraryDir = null;
9519        info.secondaryNativeLibraryDir = null;
9520
9521        if (isApkFile(codeFile)) {
9522            // Monolithic install
9523            if (bundledApp) {
9524                // If "/system/lib64/apkname" exists, assume that is the per-package
9525                // native library directory to use; otherwise use "/system/lib/apkname".
9526                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9527                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9528                        getPrimaryInstructionSet(info));
9529
9530                // This is a bundled system app so choose the path based on the ABI.
9531                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9532                // is just the default path.
9533                final String apkName = deriveCodePathName(codePath);
9534                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9535                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9536                        apkName).getAbsolutePath();
9537
9538                if (info.secondaryCpuAbi != null) {
9539                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9540                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9541                            secondaryLibDir, apkName).getAbsolutePath();
9542                }
9543            } else if (asecApp) {
9544                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9545                        .getAbsolutePath();
9546            } else {
9547                final String apkName = deriveCodePathName(codePath);
9548                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9549                        .getAbsolutePath();
9550            }
9551
9552            info.nativeLibraryRootRequiresIsa = false;
9553            info.nativeLibraryDir = info.nativeLibraryRootDir;
9554        } else {
9555            // Cluster install
9556            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9557            info.nativeLibraryRootRequiresIsa = true;
9558
9559            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9560                    getPrimaryInstructionSet(info)).getAbsolutePath();
9561
9562            if (info.secondaryCpuAbi != null) {
9563                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9564                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9565            }
9566        }
9567    }
9568
9569    /**
9570     * Calculate the abis and roots for a bundled app. These can uniquely
9571     * be determined from the contents of the system partition, i.e whether
9572     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9573     * of this information, and instead assume that the system was built
9574     * sensibly.
9575     */
9576    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9577                                           PackageSetting pkgSetting) {
9578        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9579
9580        // If "/system/lib64/apkname" exists, assume that is the per-package
9581        // native library directory to use; otherwise use "/system/lib/apkname".
9582        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9583        setBundledAppAbi(pkg, apkRoot, apkName);
9584        // pkgSetting might be null during rescan following uninstall of updates
9585        // to a bundled app, so accommodate that possibility.  The settings in
9586        // that case will be established later from the parsed package.
9587        //
9588        // If the settings aren't null, sync them up with what we've just derived.
9589        // note that apkRoot isn't stored in the package settings.
9590        if (pkgSetting != null) {
9591            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9592            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9593        }
9594    }
9595
9596    /**
9597     * Deduces the ABI of a bundled app and sets the relevant fields on the
9598     * parsed pkg object.
9599     *
9600     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9601     *        under which system libraries are installed.
9602     * @param apkName the name of the installed package.
9603     */
9604    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9605        final File codeFile = new File(pkg.codePath);
9606
9607        final boolean has64BitLibs;
9608        final boolean has32BitLibs;
9609        if (isApkFile(codeFile)) {
9610            // Monolithic install
9611            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9612            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9613        } else {
9614            // Cluster install
9615            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9616            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9617                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9618                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9619                has64BitLibs = (new File(rootDir, isa)).exists();
9620            } else {
9621                has64BitLibs = false;
9622            }
9623            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9624                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9625                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9626                has32BitLibs = (new File(rootDir, isa)).exists();
9627            } else {
9628                has32BitLibs = false;
9629            }
9630        }
9631
9632        if (has64BitLibs && !has32BitLibs) {
9633            // The package has 64 bit libs, but not 32 bit libs. Its primary
9634            // ABI should be 64 bit. We can safely assume here that the bundled
9635            // native libraries correspond to the most preferred ABI in the list.
9636
9637            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9638            pkg.applicationInfo.secondaryCpuAbi = null;
9639        } else if (has32BitLibs && !has64BitLibs) {
9640            // The package has 32 bit libs but not 64 bit libs. Its primary
9641            // ABI should be 32 bit.
9642
9643            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9644            pkg.applicationInfo.secondaryCpuAbi = null;
9645        } else if (has32BitLibs && has64BitLibs) {
9646            // The application has both 64 and 32 bit bundled libraries. We check
9647            // here that the app declares multiArch support, and warn if it doesn't.
9648            //
9649            // We will be lenient here and record both ABIs. The primary will be the
9650            // ABI that's higher on the list, i.e, a device that's configured to prefer
9651            // 64 bit apps will see a 64 bit primary ABI,
9652
9653            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9654                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9655            }
9656
9657            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9658                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9659                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9660            } else {
9661                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9662                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9663            }
9664        } else {
9665            pkg.applicationInfo.primaryCpuAbi = null;
9666            pkg.applicationInfo.secondaryCpuAbi = null;
9667        }
9668    }
9669
9670    private void killApplication(String pkgName, int appId, String reason) {
9671        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9672    }
9673
9674    private void killApplication(String pkgName, int appId, int userId, String reason) {
9675        // Request the ActivityManager to kill the process(only for existing packages)
9676        // so that we do not end up in a confused state while the user is still using the older
9677        // version of the application while the new one gets installed.
9678        final long token = Binder.clearCallingIdentity();
9679        try {
9680            IActivityManager am = ActivityManagerNative.getDefault();
9681            if (am != null) {
9682                try {
9683                    am.killApplication(pkgName, appId, userId, reason);
9684                } catch (RemoteException e) {
9685                }
9686            }
9687        } finally {
9688            Binder.restoreCallingIdentity(token);
9689        }
9690    }
9691
9692    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9693        // Remove the parent package setting
9694        PackageSetting ps = (PackageSetting) pkg.mExtras;
9695        if (ps != null) {
9696            removePackageLI(ps, chatty);
9697        }
9698        // Remove the child package setting
9699        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9700        for (int i = 0; i < childCount; i++) {
9701            PackageParser.Package childPkg = pkg.childPackages.get(i);
9702            ps = (PackageSetting) childPkg.mExtras;
9703            if (ps != null) {
9704                removePackageLI(ps, chatty);
9705            }
9706        }
9707    }
9708
9709    void removePackageLI(PackageSetting ps, boolean chatty) {
9710        if (DEBUG_INSTALL) {
9711            if (chatty)
9712                Log.d(TAG, "Removing package " + ps.name);
9713        }
9714
9715        // writer
9716        synchronized (mPackages) {
9717            mPackages.remove(ps.name);
9718            final PackageParser.Package pkg = ps.pkg;
9719            if (pkg != null) {
9720                cleanPackageDataStructuresLILPw(pkg, chatty);
9721            }
9722        }
9723    }
9724
9725    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9726        if (DEBUG_INSTALL) {
9727            if (chatty)
9728                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9729        }
9730
9731        // writer
9732        synchronized (mPackages) {
9733            // Remove the parent package
9734            mPackages.remove(pkg.applicationInfo.packageName);
9735            cleanPackageDataStructuresLILPw(pkg, chatty);
9736
9737            // Remove the child packages
9738            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9739            for (int i = 0; i < childCount; i++) {
9740                PackageParser.Package childPkg = pkg.childPackages.get(i);
9741                mPackages.remove(childPkg.applicationInfo.packageName);
9742                cleanPackageDataStructuresLILPw(childPkg, chatty);
9743            }
9744        }
9745    }
9746
9747    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9748        int N = pkg.providers.size();
9749        StringBuilder r = null;
9750        int i;
9751        for (i=0; i<N; i++) {
9752            PackageParser.Provider p = pkg.providers.get(i);
9753            mProviders.removeProvider(p);
9754            if (p.info.authority == null) {
9755
9756                /* There was another ContentProvider with this authority when
9757                 * this app was installed so this authority is null,
9758                 * Ignore it as we don't have to unregister the provider.
9759                 */
9760                continue;
9761            }
9762            String names[] = p.info.authority.split(";");
9763            for (int j = 0; j < names.length; j++) {
9764                if (mProvidersByAuthority.get(names[j]) == p) {
9765                    mProvidersByAuthority.remove(names[j]);
9766                    if (DEBUG_REMOVE) {
9767                        if (chatty)
9768                            Log.d(TAG, "Unregistered content provider: " + names[j]
9769                                    + ", className = " + p.info.name + ", isSyncable = "
9770                                    + p.info.isSyncable);
9771                    }
9772                }
9773            }
9774            if (DEBUG_REMOVE && chatty) {
9775                if (r == null) {
9776                    r = new StringBuilder(256);
9777                } else {
9778                    r.append(' ');
9779                }
9780                r.append(p.info.name);
9781            }
9782        }
9783        if (r != null) {
9784            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9785        }
9786
9787        N = pkg.services.size();
9788        r = null;
9789        for (i=0; i<N; i++) {
9790            PackageParser.Service s = pkg.services.get(i);
9791            mServices.removeService(s);
9792            if (chatty) {
9793                if (r == null) {
9794                    r = new StringBuilder(256);
9795                } else {
9796                    r.append(' ');
9797                }
9798                r.append(s.info.name);
9799            }
9800        }
9801        if (r != null) {
9802            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9803        }
9804
9805        N = pkg.receivers.size();
9806        r = null;
9807        for (i=0; i<N; i++) {
9808            PackageParser.Activity a = pkg.receivers.get(i);
9809            mReceivers.removeActivity(a, "receiver");
9810            if (DEBUG_REMOVE && chatty) {
9811                if (r == null) {
9812                    r = new StringBuilder(256);
9813                } else {
9814                    r.append(' ');
9815                }
9816                r.append(a.info.name);
9817            }
9818        }
9819        if (r != null) {
9820            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9821        }
9822
9823        N = pkg.activities.size();
9824        r = null;
9825        for (i=0; i<N; i++) {
9826            PackageParser.Activity a = pkg.activities.get(i);
9827            mActivities.removeActivity(a, "activity");
9828            if (DEBUG_REMOVE && chatty) {
9829                if (r == null) {
9830                    r = new StringBuilder(256);
9831                } else {
9832                    r.append(' ');
9833                }
9834                r.append(a.info.name);
9835            }
9836        }
9837        if (r != null) {
9838            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9839        }
9840
9841        N = pkg.permissions.size();
9842        r = null;
9843        for (i=0; i<N; i++) {
9844            PackageParser.Permission p = pkg.permissions.get(i);
9845            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9846            if (bp == null) {
9847                bp = mSettings.mPermissionTrees.get(p.info.name);
9848            }
9849            if (bp != null && bp.perm == p) {
9850                bp.perm = null;
9851                if (DEBUG_REMOVE && chatty) {
9852                    if (r == null) {
9853                        r = new StringBuilder(256);
9854                    } else {
9855                        r.append(' ');
9856                    }
9857                    r.append(p.info.name);
9858                }
9859            }
9860            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9861                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9862                if (appOpPkgs != null) {
9863                    appOpPkgs.remove(pkg.packageName);
9864                }
9865            }
9866        }
9867        if (r != null) {
9868            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9869        }
9870
9871        N = pkg.requestedPermissions.size();
9872        r = null;
9873        for (i=0; i<N; i++) {
9874            String perm = pkg.requestedPermissions.get(i);
9875            BasePermission bp = mSettings.mPermissions.get(perm);
9876            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9877                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9878                if (appOpPkgs != null) {
9879                    appOpPkgs.remove(pkg.packageName);
9880                    if (appOpPkgs.isEmpty()) {
9881                        mAppOpPermissionPackages.remove(perm);
9882                    }
9883                }
9884            }
9885        }
9886        if (r != null) {
9887            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9888        }
9889
9890        N = pkg.instrumentation.size();
9891        r = null;
9892        for (i=0; i<N; i++) {
9893            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9894            mInstrumentation.remove(a.getComponentName());
9895            if (DEBUG_REMOVE && chatty) {
9896                if (r == null) {
9897                    r = new StringBuilder(256);
9898                } else {
9899                    r.append(' ');
9900                }
9901                r.append(a.info.name);
9902            }
9903        }
9904        if (r != null) {
9905            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9906        }
9907
9908        r = null;
9909        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9910            // Only system apps can hold shared libraries.
9911            if (pkg.libraryNames != null) {
9912                for (i=0; i<pkg.libraryNames.size(); i++) {
9913                    String name = pkg.libraryNames.get(i);
9914                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9915                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9916                        mSharedLibraries.remove(name);
9917                        if (DEBUG_REMOVE && chatty) {
9918                            if (r == null) {
9919                                r = new StringBuilder(256);
9920                            } else {
9921                                r.append(' ');
9922                            }
9923                            r.append(name);
9924                        }
9925                    }
9926                }
9927            }
9928        }
9929        if (r != null) {
9930            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9931        }
9932    }
9933
9934    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9935        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9936            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9937                return true;
9938            }
9939        }
9940        return false;
9941    }
9942
9943    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9944    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9945    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9946
9947    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9948        // Update the parent permissions
9949        updatePermissionsLPw(pkg.packageName, pkg, flags);
9950        // Update the child permissions
9951        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9952        for (int i = 0; i < childCount; i++) {
9953            PackageParser.Package childPkg = pkg.childPackages.get(i);
9954            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9955        }
9956    }
9957
9958    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9959            int flags) {
9960        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9961        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9962    }
9963
9964    private void updatePermissionsLPw(String changingPkg,
9965            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9966        // Make sure there are no dangling permission trees.
9967        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9968        while (it.hasNext()) {
9969            final BasePermission bp = it.next();
9970            if (bp.packageSetting == null) {
9971                // We may not yet have parsed the package, so just see if
9972                // we still know about its settings.
9973                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9974            }
9975            if (bp.packageSetting == null) {
9976                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9977                        + " from package " + bp.sourcePackage);
9978                it.remove();
9979            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9980                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9981                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9982                            + " from package " + bp.sourcePackage);
9983                    flags |= UPDATE_PERMISSIONS_ALL;
9984                    it.remove();
9985                }
9986            }
9987        }
9988
9989        // Make sure all dynamic permissions have been assigned to a package,
9990        // and make sure there are no dangling permissions.
9991        it = mSettings.mPermissions.values().iterator();
9992        while (it.hasNext()) {
9993            final BasePermission bp = it.next();
9994            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9995                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9996                        + bp.name + " pkg=" + bp.sourcePackage
9997                        + " info=" + bp.pendingInfo);
9998                if (bp.packageSetting == null && bp.pendingInfo != null) {
9999                    final BasePermission tree = findPermissionTreeLP(bp.name);
10000                    if (tree != null && tree.perm != null) {
10001                        bp.packageSetting = tree.packageSetting;
10002                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10003                                new PermissionInfo(bp.pendingInfo));
10004                        bp.perm.info.packageName = tree.perm.info.packageName;
10005                        bp.perm.info.name = bp.name;
10006                        bp.uid = tree.uid;
10007                    }
10008                }
10009            }
10010            if (bp.packageSetting == null) {
10011                // We may not yet have parsed the package, so just see if
10012                // we still know about its settings.
10013                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10014            }
10015            if (bp.packageSetting == null) {
10016                Slog.w(TAG, "Removing dangling permission: " + bp.name
10017                        + " from package " + bp.sourcePackage);
10018                it.remove();
10019            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10020                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10021                    Slog.i(TAG, "Removing old permission: " + bp.name
10022                            + " from package " + bp.sourcePackage);
10023                    flags |= UPDATE_PERMISSIONS_ALL;
10024                    it.remove();
10025                }
10026            }
10027        }
10028
10029        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10030        // Now update the permissions for all packages, in particular
10031        // replace the granted permissions of the system packages.
10032        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10033            for (PackageParser.Package pkg : mPackages.values()) {
10034                if (pkg != pkgInfo) {
10035                    // Only replace for packages on requested volume
10036                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10037                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10038                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10039                    grantPermissionsLPw(pkg, replace, changingPkg);
10040                }
10041            }
10042        }
10043
10044        if (pkgInfo != null) {
10045            // Only replace for packages on requested volume
10046            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10047            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10048                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10049            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10050        }
10051        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10052    }
10053
10054    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10055            String packageOfInterest) {
10056        // IMPORTANT: There are two types of permissions: install and runtime.
10057        // Install time permissions are granted when the app is installed to
10058        // all device users and users added in the future. Runtime permissions
10059        // are granted at runtime explicitly to specific users. Normal and signature
10060        // protected permissions are install time permissions. Dangerous permissions
10061        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10062        // otherwise they are runtime permissions. This function does not manage
10063        // runtime permissions except for the case an app targeting Lollipop MR1
10064        // being upgraded to target a newer SDK, in which case dangerous permissions
10065        // are transformed from install time to runtime ones.
10066
10067        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10068        if (ps == null) {
10069            return;
10070        }
10071
10072        PermissionsState permissionsState = ps.getPermissionsState();
10073        PermissionsState origPermissions = permissionsState;
10074
10075        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10076
10077        boolean runtimePermissionsRevoked = false;
10078        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10079
10080        boolean changedInstallPermission = false;
10081
10082        if (replace) {
10083            ps.installPermissionsFixed = false;
10084            if (!ps.isSharedUser()) {
10085                origPermissions = new PermissionsState(permissionsState);
10086                permissionsState.reset();
10087            } else {
10088                // We need to know only about runtime permission changes since the
10089                // calling code always writes the install permissions state but
10090                // the runtime ones are written only if changed. The only cases of
10091                // changed runtime permissions here are promotion of an install to
10092                // runtime and revocation of a runtime from a shared user.
10093                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10094                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10095                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10096                    runtimePermissionsRevoked = true;
10097                }
10098            }
10099        }
10100
10101        permissionsState.setGlobalGids(mGlobalGids);
10102
10103        final int N = pkg.requestedPermissions.size();
10104        for (int i=0; i<N; i++) {
10105            final String name = pkg.requestedPermissions.get(i);
10106            final BasePermission bp = mSettings.mPermissions.get(name);
10107
10108            if (DEBUG_INSTALL) {
10109                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10110            }
10111
10112            if (bp == null || bp.packageSetting == null) {
10113                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10114                    Slog.w(TAG, "Unknown permission " + name
10115                            + " in package " + pkg.packageName);
10116                }
10117                continue;
10118            }
10119
10120            final String perm = bp.name;
10121            boolean allowedSig = false;
10122            int grant = GRANT_DENIED;
10123
10124            // Keep track of app op permissions.
10125            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10126                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10127                if (pkgs == null) {
10128                    pkgs = new ArraySet<>();
10129                    mAppOpPermissionPackages.put(bp.name, pkgs);
10130                }
10131                pkgs.add(pkg.packageName);
10132            }
10133
10134            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10135            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10136                    >= Build.VERSION_CODES.M;
10137            switch (level) {
10138                case PermissionInfo.PROTECTION_NORMAL: {
10139                    // For all apps normal permissions are install time ones.
10140                    grant = GRANT_INSTALL;
10141                } break;
10142
10143                case PermissionInfo.PROTECTION_DANGEROUS: {
10144                    // If a permission review is required for legacy apps we represent
10145                    // their permissions as always granted runtime ones since we need
10146                    // to keep the review required permission flag per user while an
10147                    // install permission's state is shared across all users.
10148                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10149                        // For legacy apps dangerous permissions are install time ones.
10150                        grant = GRANT_INSTALL;
10151                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10152                        // For legacy apps that became modern, install becomes runtime.
10153                        grant = GRANT_UPGRADE;
10154                    } else if (mPromoteSystemApps
10155                            && isSystemApp(ps)
10156                            && mExistingSystemPackages.contains(ps.name)) {
10157                        // For legacy system apps, install becomes runtime.
10158                        // We cannot check hasInstallPermission() for system apps since those
10159                        // permissions were granted implicitly and not persisted pre-M.
10160                        grant = GRANT_UPGRADE;
10161                    } else {
10162                        // For modern apps keep runtime permissions unchanged.
10163                        grant = GRANT_RUNTIME;
10164                    }
10165                } break;
10166
10167                case PermissionInfo.PROTECTION_SIGNATURE: {
10168                    // For all apps signature permissions are install time ones.
10169                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10170                    if (allowedSig) {
10171                        grant = GRANT_INSTALL;
10172                    }
10173                } break;
10174            }
10175
10176            if (DEBUG_INSTALL) {
10177                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10178            }
10179
10180            if (grant != GRANT_DENIED) {
10181                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10182                    // If this is an existing, non-system package, then
10183                    // we can't add any new permissions to it.
10184                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10185                        // Except...  if this is a permission that was added
10186                        // to the platform (note: need to only do this when
10187                        // updating the platform).
10188                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10189                            grant = GRANT_DENIED;
10190                        }
10191                    }
10192                }
10193
10194                switch (grant) {
10195                    case GRANT_INSTALL: {
10196                        // Revoke this as runtime permission to handle the case of
10197                        // a runtime permission being downgraded to an install one.
10198                        // Also in permission review mode we keep dangerous permissions
10199                        // for legacy apps
10200                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10201                            if (origPermissions.getRuntimePermissionState(
10202                                    bp.name, userId) != null) {
10203                                // Revoke the runtime permission and clear the flags.
10204                                origPermissions.revokeRuntimePermission(bp, userId);
10205                                origPermissions.updatePermissionFlags(bp, userId,
10206                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10207                                // If we revoked a permission permission, we have to write.
10208                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10209                                        changedRuntimePermissionUserIds, userId);
10210                            }
10211                        }
10212                        // Grant an install permission.
10213                        if (permissionsState.grantInstallPermission(bp) !=
10214                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10215                            changedInstallPermission = true;
10216                        }
10217                    } break;
10218
10219                    case GRANT_RUNTIME: {
10220                        // Grant previously granted runtime permissions.
10221                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10222                            PermissionState permissionState = origPermissions
10223                                    .getRuntimePermissionState(bp.name, userId);
10224                            int flags = permissionState != null
10225                                    ? permissionState.getFlags() : 0;
10226                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10227                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10228                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10229                                    // If we cannot put the permission as it was, we have to write.
10230                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10231                                            changedRuntimePermissionUserIds, userId);
10232                                }
10233                                // If the app supports runtime permissions no need for a review.
10234                                if (mPermissionReviewRequired
10235                                        && appSupportsRuntimePermissions
10236                                        && (flags & PackageManager
10237                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10238                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10239                                    // Since we changed the flags, we have to write.
10240                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10241                                            changedRuntimePermissionUserIds, userId);
10242                                }
10243                            } else if (mPermissionReviewRequired
10244                                    && !appSupportsRuntimePermissions) {
10245                                // For legacy apps that need a permission review, every new
10246                                // runtime permission is granted but it is pending a review.
10247                                // We also need to review only platform defined runtime
10248                                // permissions as these are the only ones the platform knows
10249                                // how to disable the API to simulate revocation as legacy
10250                                // apps don't expect to run with revoked permissions.
10251                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10252                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10253                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10254                                        // We changed the flags, hence have to write.
10255                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10256                                                changedRuntimePermissionUserIds, userId);
10257                                    }
10258                                }
10259                                if (permissionsState.grantRuntimePermission(bp, userId)
10260                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10261                                    // We changed the permission, hence have to write.
10262                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10263                                            changedRuntimePermissionUserIds, userId);
10264                                }
10265                            }
10266                            // Propagate the permission flags.
10267                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10268                        }
10269                    } break;
10270
10271                    case GRANT_UPGRADE: {
10272                        // Grant runtime permissions for a previously held install permission.
10273                        PermissionState permissionState = origPermissions
10274                                .getInstallPermissionState(bp.name);
10275                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10276
10277                        if (origPermissions.revokeInstallPermission(bp)
10278                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10279                            // We will be transferring the permission flags, so clear them.
10280                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10281                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10282                            changedInstallPermission = true;
10283                        }
10284
10285                        // If the permission is not to be promoted to runtime we ignore it and
10286                        // also its other flags as they are not applicable to install permissions.
10287                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10288                            for (int userId : currentUserIds) {
10289                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10290                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10291                                    // Transfer the permission flags.
10292                                    permissionsState.updatePermissionFlags(bp, userId,
10293                                            flags, flags);
10294                                    // If we granted the permission, we have to write.
10295                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10296                                            changedRuntimePermissionUserIds, userId);
10297                                }
10298                            }
10299                        }
10300                    } break;
10301
10302                    default: {
10303                        if (packageOfInterest == null
10304                                || packageOfInterest.equals(pkg.packageName)) {
10305                            Slog.w(TAG, "Not granting permission " + perm
10306                                    + " to package " + pkg.packageName
10307                                    + " because it was previously installed without");
10308                        }
10309                    } break;
10310                }
10311            } else {
10312                if (permissionsState.revokeInstallPermission(bp) !=
10313                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10314                    // Also drop the permission flags.
10315                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10316                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10317                    changedInstallPermission = true;
10318                    Slog.i(TAG, "Un-granting permission " + perm
10319                            + " from package " + pkg.packageName
10320                            + " (protectionLevel=" + bp.protectionLevel
10321                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10322                            + ")");
10323                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10324                    // Don't print warning for app op permissions, since it is fine for them
10325                    // not to be granted, there is a UI for the user to decide.
10326                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10327                        Slog.w(TAG, "Not granting permission " + perm
10328                                + " to package " + pkg.packageName
10329                                + " (protectionLevel=" + bp.protectionLevel
10330                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10331                                + ")");
10332                    }
10333                }
10334            }
10335        }
10336
10337        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10338                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10339            // This is the first that we have heard about this package, so the
10340            // permissions we have now selected are fixed until explicitly
10341            // changed.
10342            ps.installPermissionsFixed = true;
10343        }
10344
10345        // Persist the runtime permissions state for users with changes. If permissions
10346        // were revoked because no app in the shared user declares them we have to
10347        // write synchronously to avoid losing runtime permissions state.
10348        for (int userId : changedRuntimePermissionUserIds) {
10349            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10350        }
10351    }
10352
10353    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10354        boolean allowed = false;
10355        final int NP = PackageParser.NEW_PERMISSIONS.length;
10356        for (int ip=0; ip<NP; ip++) {
10357            final PackageParser.NewPermissionInfo npi
10358                    = PackageParser.NEW_PERMISSIONS[ip];
10359            if (npi.name.equals(perm)
10360                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10361                allowed = true;
10362                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10363                        + pkg.packageName);
10364                break;
10365            }
10366        }
10367        return allowed;
10368    }
10369
10370    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10371            BasePermission bp, PermissionsState origPermissions) {
10372        boolean allowed;
10373        allowed = (compareSignatures(
10374                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10375                        == PackageManager.SIGNATURE_MATCH)
10376                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10377                        == PackageManager.SIGNATURE_MATCH);
10378        if (!allowed && (bp.protectionLevel
10379                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10380            if (isSystemApp(pkg)) {
10381                // For updated system applications, a system permission
10382                // is granted only if it had been defined by the original application.
10383                if (pkg.isUpdatedSystemApp()) {
10384                    final PackageSetting sysPs = mSettings
10385                            .getDisabledSystemPkgLPr(pkg.packageName);
10386                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10387                        // If the original was granted this permission, we take
10388                        // that grant decision as read and propagate it to the
10389                        // update.
10390                        if (sysPs.isPrivileged()) {
10391                            allowed = true;
10392                        }
10393                    } else {
10394                        // The system apk may have been updated with an older
10395                        // version of the one on the data partition, but which
10396                        // granted a new system permission that it didn't have
10397                        // before.  In this case we do want to allow the app to
10398                        // now get the new permission if the ancestral apk is
10399                        // privileged to get it.
10400                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10401                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10402                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10403                                    allowed = true;
10404                                    break;
10405                                }
10406                            }
10407                        }
10408                        // Also if a privileged parent package on the system image or any of
10409                        // its children requested a privileged permission, the updated child
10410                        // packages can also get the permission.
10411                        if (pkg.parentPackage != null) {
10412                            final PackageSetting disabledSysParentPs = mSettings
10413                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10414                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10415                                    && disabledSysParentPs.isPrivileged()) {
10416                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10417                                    allowed = true;
10418                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10419                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10420                                    for (int i = 0; i < count; i++) {
10421                                        PackageParser.Package disabledSysChildPkg =
10422                                                disabledSysParentPs.pkg.childPackages.get(i);
10423                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10424                                                perm)) {
10425                                            allowed = true;
10426                                            break;
10427                                        }
10428                                    }
10429                                }
10430                            }
10431                        }
10432                    }
10433                } else {
10434                    allowed = isPrivilegedApp(pkg);
10435                }
10436            }
10437        }
10438        if (!allowed) {
10439            if (!allowed && (bp.protectionLevel
10440                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10441                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10442                // If this was a previously normal/dangerous permission that got moved
10443                // to a system permission as part of the runtime permission redesign, then
10444                // we still want to blindly grant it to old apps.
10445                allowed = true;
10446            }
10447            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10448                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10449                // If this permission is to be granted to the system installer and
10450                // this app is an installer, then it gets the permission.
10451                allowed = true;
10452            }
10453            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10454                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10455                // If this permission is to be granted to the system verifier and
10456                // this app is a verifier, then it gets the permission.
10457                allowed = true;
10458            }
10459            if (!allowed && (bp.protectionLevel
10460                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10461                    && isSystemApp(pkg)) {
10462                // Any pre-installed system app is allowed to get this permission.
10463                allowed = true;
10464            }
10465            if (!allowed && (bp.protectionLevel
10466                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10467                // For development permissions, a development permission
10468                // is granted only if it was already granted.
10469                allowed = origPermissions.hasInstallPermission(perm);
10470            }
10471            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10472                    && pkg.packageName.equals(mSetupWizardPackage)) {
10473                // If this permission is to be granted to the system setup wizard and
10474                // this app is a setup wizard, then it gets the permission.
10475                allowed = true;
10476            }
10477        }
10478        return allowed;
10479    }
10480
10481    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10482        final int permCount = pkg.requestedPermissions.size();
10483        for (int j = 0; j < permCount; j++) {
10484            String requestedPermission = pkg.requestedPermissions.get(j);
10485            if (permission.equals(requestedPermission)) {
10486                return true;
10487            }
10488        }
10489        return false;
10490    }
10491
10492    final class ActivityIntentResolver
10493            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10494        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10495                boolean defaultOnly, int userId) {
10496            if (!sUserManager.exists(userId)) return null;
10497            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10498            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10499        }
10500
10501        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10502                int userId) {
10503            if (!sUserManager.exists(userId)) return null;
10504            mFlags = flags;
10505            return super.queryIntent(intent, resolvedType,
10506                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10507        }
10508
10509        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10510                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10511            if (!sUserManager.exists(userId)) return null;
10512            if (packageActivities == null) {
10513                return null;
10514            }
10515            mFlags = flags;
10516            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10517            final int N = packageActivities.size();
10518            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10519                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10520
10521            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10522            for (int i = 0; i < N; ++i) {
10523                intentFilters = packageActivities.get(i).intents;
10524                if (intentFilters != null && intentFilters.size() > 0) {
10525                    PackageParser.ActivityIntentInfo[] array =
10526                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10527                    intentFilters.toArray(array);
10528                    listCut.add(array);
10529                }
10530            }
10531            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10532        }
10533
10534        /**
10535         * Finds a privileged activity that matches the specified activity names.
10536         */
10537        private PackageParser.Activity findMatchingActivity(
10538                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10539            for (PackageParser.Activity sysActivity : activityList) {
10540                if (sysActivity.info.name.equals(activityInfo.name)) {
10541                    return sysActivity;
10542                }
10543                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10544                    return sysActivity;
10545                }
10546                if (sysActivity.info.targetActivity != null) {
10547                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10548                        return sysActivity;
10549                    }
10550                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10551                        return sysActivity;
10552                    }
10553                }
10554            }
10555            return null;
10556        }
10557
10558        public class IterGenerator<E> {
10559            public Iterator<E> generate(ActivityIntentInfo info) {
10560                return null;
10561            }
10562        }
10563
10564        public class ActionIterGenerator extends IterGenerator<String> {
10565            @Override
10566            public Iterator<String> generate(ActivityIntentInfo info) {
10567                return info.actionsIterator();
10568            }
10569        }
10570
10571        public class CategoriesIterGenerator extends IterGenerator<String> {
10572            @Override
10573            public Iterator<String> generate(ActivityIntentInfo info) {
10574                return info.categoriesIterator();
10575            }
10576        }
10577
10578        public class SchemesIterGenerator extends IterGenerator<String> {
10579            @Override
10580            public Iterator<String> generate(ActivityIntentInfo info) {
10581                return info.schemesIterator();
10582            }
10583        }
10584
10585        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10586            @Override
10587            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10588                return info.authoritiesIterator();
10589            }
10590        }
10591
10592        /**
10593         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10594         * MODIFIED. Do not pass in a list that should not be changed.
10595         */
10596        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10597                IterGenerator<T> generator, Iterator<T> searchIterator) {
10598            // loop through the set of actions; every one must be found in the intent filter
10599            while (searchIterator.hasNext()) {
10600                // we must have at least one filter in the list to consider a match
10601                if (intentList.size() == 0) {
10602                    break;
10603                }
10604
10605                final T searchAction = searchIterator.next();
10606
10607                // loop through the set of intent filters
10608                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10609                while (intentIter.hasNext()) {
10610                    final ActivityIntentInfo intentInfo = intentIter.next();
10611                    boolean selectionFound = false;
10612
10613                    // loop through the intent filter's selection criteria; at least one
10614                    // of them must match the searched criteria
10615                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10616                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10617                        final T intentSelection = intentSelectionIter.next();
10618                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10619                            selectionFound = true;
10620                            break;
10621                        }
10622                    }
10623
10624                    // the selection criteria wasn't found in this filter's set; this filter
10625                    // is not a potential match
10626                    if (!selectionFound) {
10627                        intentIter.remove();
10628                    }
10629                }
10630            }
10631        }
10632
10633        private boolean isProtectedAction(ActivityIntentInfo filter) {
10634            final Iterator<String> actionsIter = filter.actionsIterator();
10635            while (actionsIter != null && actionsIter.hasNext()) {
10636                final String filterAction = actionsIter.next();
10637                if (PROTECTED_ACTIONS.contains(filterAction)) {
10638                    return true;
10639                }
10640            }
10641            return false;
10642        }
10643
10644        /**
10645         * Adjusts the priority of the given intent filter according to policy.
10646         * <p>
10647         * <ul>
10648         * <li>The priority for non privileged applications is capped to '0'</li>
10649         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10650         * <li>The priority for unbundled updates to privileged applications is capped to the
10651         *      priority defined on the system partition</li>
10652         * </ul>
10653         * <p>
10654         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10655         * allowed to obtain any priority on any action.
10656         */
10657        private void adjustPriority(
10658                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10659            // nothing to do; priority is fine as-is
10660            if (intent.getPriority() <= 0) {
10661                return;
10662            }
10663
10664            final ActivityInfo activityInfo = intent.activity.info;
10665            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10666
10667            final boolean privilegedApp =
10668                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10669            if (!privilegedApp) {
10670                // non-privileged applications can never define a priority >0
10671                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10672                        + " package: " + applicationInfo.packageName
10673                        + " activity: " + intent.activity.className
10674                        + " origPrio: " + intent.getPriority());
10675                intent.setPriority(0);
10676                return;
10677            }
10678
10679            if (systemActivities == null) {
10680                // the system package is not disabled; we're parsing the system partition
10681                if (isProtectedAction(intent)) {
10682                    if (mDeferProtectedFilters) {
10683                        // We can't deal with these just yet. No component should ever obtain a
10684                        // >0 priority for a protected actions, with ONE exception -- the setup
10685                        // wizard. The setup wizard, however, cannot be known until we're able to
10686                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10687                        // until all intent filters have been processed. Chicken, meet egg.
10688                        // Let the filter temporarily have a high priority and rectify the
10689                        // priorities after all system packages have been scanned.
10690                        mProtectedFilters.add(intent);
10691                        if (DEBUG_FILTERS) {
10692                            Slog.i(TAG, "Protected action; save for later;"
10693                                    + " package: " + applicationInfo.packageName
10694                                    + " activity: " + intent.activity.className
10695                                    + " origPrio: " + intent.getPriority());
10696                        }
10697                        return;
10698                    } else {
10699                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10700                            Slog.i(TAG, "No setup wizard;"
10701                                + " All protected intents capped to priority 0");
10702                        }
10703                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10704                            if (DEBUG_FILTERS) {
10705                                Slog.i(TAG, "Found setup wizard;"
10706                                    + " allow priority " + intent.getPriority() + ";"
10707                                    + " package: " + intent.activity.info.packageName
10708                                    + " activity: " + intent.activity.className
10709                                    + " priority: " + intent.getPriority());
10710                            }
10711                            // setup wizard gets whatever it wants
10712                            return;
10713                        }
10714                        Slog.w(TAG, "Protected action; cap priority to 0;"
10715                                + " package: " + intent.activity.info.packageName
10716                                + " activity: " + intent.activity.className
10717                                + " origPrio: " + intent.getPriority());
10718                        intent.setPriority(0);
10719                        return;
10720                    }
10721                }
10722                // privileged apps on the system image get whatever priority they request
10723                return;
10724            }
10725
10726            // privileged app unbundled update ... try to find the same activity
10727            final PackageParser.Activity foundActivity =
10728                    findMatchingActivity(systemActivities, activityInfo);
10729            if (foundActivity == null) {
10730                // this is a new activity; it cannot obtain >0 priority
10731                if (DEBUG_FILTERS) {
10732                    Slog.i(TAG, "New activity; cap priority to 0;"
10733                            + " package: " + applicationInfo.packageName
10734                            + " activity: " + intent.activity.className
10735                            + " origPrio: " + intent.getPriority());
10736                }
10737                intent.setPriority(0);
10738                return;
10739            }
10740
10741            // found activity, now check for filter equivalence
10742
10743            // a shallow copy is enough; we modify the list, not its contents
10744            final List<ActivityIntentInfo> intentListCopy =
10745                    new ArrayList<>(foundActivity.intents);
10746            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10747
10748            // find matching action subsets
10749            final Iterator<String> actionsIterator = intent.actionsIterator();
10750            if (actionsIterator != null) {
10751                getIntentListSubset(
10752                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10753                if (intentListCopy.size() == 0) {
10754                    // no more intents to match; we're not equivalent
10755                    if (DEBUG_FILTERS) {
10756                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10757                                + " package: " + applicationInfo.packageName
10758                                + " activity: " + intent.activity.className
10759                                + " origPrio: " + intent.getPriority());
10760                    }
10761                    intent.setPriority(0);
10762                    return;
10763                }
10764            }
10765
10766            // find matching category subsets
10767            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10768            if (categoriesIterator != null) {
10769                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10770                        categoriesIterator);
10771                if (intentListCopy.size() == 0) {
10772                    // no more intents to match; we're not equivalent
10773                    if (DEBUG_FILTERS) {
10774                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10775                                + " package: " + applicationInfo.packageName
10776                                + " activity: " + intent.activity.className
10777                                + " origPrio: " + intent.getPriority());
10778                    }
10779                    intent.setPriority(0);
10780                    return;
10781                }
10782            }
10783
10784            // find matching schemes subsets
10785            final Iterator<String> schemesIterator = intent.schemesIterator();
10786            if (schemesIterator != null) {
10787                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10788                        schemesIterator);
10789                if (intentListCopy.size() == 0) {
10790                    // no more intents to match; we're not equivalent
10791                    if (DEBUG_FILTERS) {
10792                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10793                                + " package: " + applicationInfo.packageName
10794                                + " activity: " + intent.activity.className
10795                                + " origPrio: " + intent.getPriority());
10796                    }
10797                    intent.setPriority(0);
10798                    return;
10799                }
10800            }
10801
10802            // find matching authorities subsets
10803            final Iterator<IntentFilter.AuthorityEntry>
10804                    authoritiesIterator = intent.authoritiesIterator();
10805            if (authoritiesIterator != null) {
10806                getIntentListSubset(intentListCopy,
10807                        new AuthoritiesIterGenerator(),
10808                        authoritiesIterator);
10809                if (intentListCopy.size() == 0) {
10810                    // no more intents to match; we're not equivalent
10811                    if (DEBUG_FILTERS) {
10812                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10813                                + " package: " + applicationInfo.packageName
10814                                + " activity: " + intent.activity.className
10815                                + " origPrio: " + intent.getPriority());
10816                    }
10817                    intent.setPriority(0);
10818                    return;
10819                }
10820            }
10821
10822            // we found matching filter(s); app gets the max priority of all intents
10823            int cappedPriority = 0;
10824            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10825                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10826            }
10827            if (intent.getPriority() > cappedPriority) {
10828                if (DEBUG_FILTERS) {
10829                    Slog.i(TAG, "Found matching filter(s);"
10830                            + " cap priority to " + cappedPriority + ";"
10831                            + " package: " + applicationInfo.packageName
10832                            + " activity: " + intent.activity.className
10833                            + " origPrio: " + intent.getPriority());
10834                }
10835                intent.setPriority(cappedPriority);
10836                return;
10837            }
10838            // all this for nothing; the requested priority was <= what was on the system
10839        }
10840
10841        public final void addActivity(PackageParser.Activity a, String type) {
10842            mActivities.put(a.getComponentName(), a);
10843            if (DEBUG_SHOW_INFO)
10844                Log.v(
10845                TAG, "  " + type + " " +
10846                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10847            if (DEBUG_SHOW_INFO)
10848                Log.v(TAG, "    Class=" + a.info.name);
10849            final int NI = a.intents.size();
10850            for (int j=0; j<NI; j++) {
10851                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10852                if ("activity".equals(type)) {
10853                    final PackageSetting ps =
10854                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10855                    final List<PackageParser.Activity> systemActivities =
10856                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10857                    adjustPriority(systemActivities, intent);
10858                }
10859                if (DEBUG_SHOW_INFO) {
10860                    Log.v(TAG, "    IntentFilter:");
10861                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10862                }
10863                if (!intent.debugCheck()) {
10864                    Log.w(TAG, "==> For Activity " + a.info.name);
10865                }
10866                addFilter(intent);
10867            }
10868        }
10869
10870        public final void removeActivity(PackageParser.Activity a, String type) {
10871            mActivities.remove(a.getComponentName());
10872            if (DEBUG_SHOW_INFO) {
10873                Log.v(TAG, "  " + type + " "
10874                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10875                                : a.info.name) + ":");
10876                Log.v(TAG, "    Class=" + a.info.name);
10877            }
10878            final int NI = a.intents.size();
10879            for (int j=0; j<NI; j++) {
10880                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10881                if (DEBUG_SHOW_INFO) {
10882                    Log.v(TAG, "    IntentFilter:");
10883                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10884                }
10885                removeFilter(intent);
10886            }
10887        }
10888
10889        @Override
10890        protected boolean allowFilterResult(
10891                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10892            ActivityInfo filterAi = filter.activity.info;
10893            for (int i=dest.size()-1; i>=0; i--) {
10894                ActivityInfo destAi = dest.get(i).activityInfo;
10895                if (destAi.name == filterAi.name
10896                        && destAi.packageName == filterAi.packageName) {
10897                    return false;
10898                }
10899            }
10900            return true;
10901        }
10902
10903        @Override
10904        protected ActivityIntentInfo[] newArray(int size) {
10905            return new ActivityIntentInfo[size];
10906        }
10907
10908        @Override
10909        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10910            if (!sUserManager.exists(userId)) return true;
10911            PackageParser.Package p = filter.activity.owner;
10912            if (p != null) {
10913                PackageSetting ps = (PackageSetting)p.mExtras;
10914                if (ps != null) {
10915                    // System apps are never considered stopped for purposes of
10916                    // filtering, because there may be no way for the user to
10917                    // actually re-launch them.
10918                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10919                            && ps.getStopped(userId);
10920                }
10921            }
10922            return false;
10923        }
10924
10925        @Override
10926        protected boolean isPackageForFilter(String packageName,
10927                PackageParser.ActivityIntentInfo info) {
10928            return packageName.equals(info.activity.owner.packageName);
10929        }
10930
10931        @Override
10932        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10933                int match, int userId) {
10934            if (!sUserManager.exists(userId)) return null;
10935            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10936                return null;
10937            }
10938            final PackageParser.Activity activity = info.activity;
10939            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10940            if (ps == null) {
10941                return null;
10942            }
10943            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10944                    ps.readUserState(userId), userId);
10945            if (ai == null) {
10946                return null;
10947            }
10948            final ResolveInfo res = new ResolveInfo();
10949            res.activityInfo = ai;
10950            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10951                res.filter = info;
10952            }
10953            if (info != null) {
10954                res.handleAllWebDataURI = info.handleAllWebDataURI();
10955            }
10956            res.priority = info.getPriority();
10957            res.preferredOrder = activity.owner.mPreferredOrder;
10958            //System.out.println("Result: " + res.activityInfo.className +
10959            //                   " = " + res.priority);
10960            res.match = match;
10961            res.isDefault = info.hasDefault;
10962            res.labelRes = info.labelRes;
10963            res.nonLocalizedLabel = info.nonLocalizedLabel;
10964            if (userNeedsBadging(userId)) {
10965                res.noResourceId = true;
10966            } else {
10967                res.icon = info.icon;
10968            }
10969            res.iconResourceId = info.icon;
10970            res.system = res.activityInfo.applicationInfo.isSystemApp();
10971            return res;
10972        }
10973
10974        @Override
10975        protected void sortResults(List<ResolveInfo> results) {
10976            Collections.sort(results, mResolvePrioritySorter);
10977        }
10978
10979        @Override
10980        protected void dumpFilter(PrintWriter out, String prefix,
10981                PackageParser.ActivityIntentInfo filter) {
10982            out.print(prefix); out.print(
10983                    Integer.toHexString(System.identityHashCode(filter.activity)));
10984                    out.print(' ');
10985                    filter.activity.printComponentShortName(out);
10986                    out.print(" filter ");
10987                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10988        }
10989
10990        @Override
10991        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10992            return filter.activity;
10993        }
10994
10995        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10996            PackageParser.Activity activity = (PackageParser.Activity)label;
10997            out.print(prefix); out.print(
10998                    Integer.toHexString(System.identityHashCode(activity)));
10999                    out.print(' ');
11000                    activity.printComponentShortName(out);
11001            if (count > 1) {
11002                out.print(" ("); out.print(count); out.print(" filters)");
11003            }
11004            out.println();
11005        }
11006
11007        // Keys are String (activity class name), values are Activity.
11008        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11009                = new ArrayMap<ComponentName, PackageParser.Activity>();
11010        private int mFlags;
11011    }
11012
11013    private final class ServiceIntentResolver
11014            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11015        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11016                boolean defaultOnly, int userId) {
11017            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11018            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11019        }
11020
11021        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11022                int userId) {
11023            if (!sUserManager.exists(userId)) return null;
11024            mFlags = flags;
11025            return super.queryIntent(intent, resolvedType,
11026                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11027        }
11028
11029        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11030                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11031            if (!sUserManager.exists(userId)) return null;
11032            if (packageServices == null) {
11033                return null;
11034            }
11035            mFlags = flags;
11036            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11037            final int N = packageServices.size();
11038            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11039                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11040
11041            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11042            for (int i = 0; i < N; ++i) {
11043                intentFilters = packageServices.get(i).intents;
11044                if (intentFilters != null && intentFilters.size() > 0) {
11045                    PackageParser.ServiceIntentInfo[] array =
11046                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11047                    intentFilters.toArray(array);
11048                    listCut.add(array);
11049                }
11050            }
11051            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11052        }
11053
11054        public final void addService(PackageParser.Service s) {
11055            mServices.put(s.getComponentName(), s);
11056            if (DEBUG_SHOW_INFO) {
11057                Log.v(TAG, "  "
11058                        + (s.info.nonLocalizedLabel != null
11059                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11060                Log.v(TAG, "    Class=" + s.info.name);
11061            }
11062            final int NI = s.intents.size();
11063            int j;
11064            for (j=0; j<NI; j++) {
11065                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11066                if (DEBUG_SHOW_INFO) {
11067                    Log.v(TAG, "    IntentFilter:");
11068                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11069                }
11070                if (!intent.debugCheck()) {
11071                    Log.w(TAG, "==> For Service " + s.info.name);
11072                }
11073                addFilter(intent);
11074            }
11075        }
11076
11077        public final void removeService(PackageParser.Service s) {
11078            mServices.remove(s.getComponentName());
11079            if (DEBUG_SHOW_INFO) {
11080                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11081                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11082                Log.v(TAG, "    Class=" + s.info.name);
11083            }
11084            final int NI = s.intents.size();
11085            int j;
11086            for (j=0; j<NI; j++) {
11087                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11088                if (DEBUG_SHOW_INFO) {
11089                    Log.v(TAG, "    IntentFilter:");
11090                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11091                }
11092                removeFilter(intent);
11093            }
11094        }
11095
11096        @Override
11097        protected boolean allowFilterResult(
11098                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11099            ServiceInfo filterSi = filter.service.info;
11100            for (int i=dest.size()-1; i>=0; i--) {
11101                ServiceInfo destAi = dest.get(i).serviceInfo;
11102                if (destAi.name == filterSi.name
11103                        && destAi.packageName == filterSi.packageName) {
11104                    return false;
11105                }
11106            }
11107            return true;
11108        }
11109
11110        @Override
11111        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11112            return new PackageParser.ServiceIntentInfo[size];
11113        }
11114
11115        @Override
11116        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11117            if (!sUserManager.exists(userId)) return true;
11118            PackageParser.Package p = filter.service.owner;
11119            if (p != null) {
11120                PackageSetting ps = (PackageSetting)p.mExtras;
11121                if (ps != null) {
11122                    // System apps are never considered stopped for purposes of
11123                    // filtering, because there may be no way for the user to
11124                    // actually re-launch them.
11125                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11126                            && ps.getStopped(userId);
11127                }
11128            }
11129            return false;
11130        }
11131
11132        @Override
11133        protected boolean isPackageForFilter(String packageName,
11134                PackageParser.ServiceIntentInfo info) {
11135            return packageName.equals(info.service.owner.packageName);
11136        }
11137
11138        @Override
11139        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11140                int match, int userId) {
11141            if (!sUserManager.exists(userId)) return null;
11142            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11143            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11144                return null;
11145            }
11146            final PackageParser.Service service = info.service;
11147            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11148            if (ps == null) {
11149                return null;
11150            }
11151            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11152                    ps.readUserState(userId), userId);
11153            if (si == null) {
11154                return null;
11155            }
11156            final ResolveInfo res = new ResolveInfo();
11157            res.serviceInfo = si;
11158            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11159                res.filter = filter;
11160            }
11161            res.priority = info.getPriority();
11162            res.preferredOrder = service.owner.mPreferredOrder;
11163            res.match = match;
11164            res.isDefault = info.hasDefault;
11165            res.labelRes = info.labelRes;
11166            res.nonLocalizedLabel = info.nonLocalizedLabel;
11167            res.icon = info.icon;
11168            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11169            return res;
11170        }
11171
11172        @Override
11173        protected void sortResults(List<ResolveInfo> results) {
11174            Collections.sort(results, mResolvePrioritySorter);
11175        }
11176
11177        @Override
11178        protected void dumpFilter(PrintWriter out, String prefix,
11179                PackageParser.ServiceIntentInfo filter) {
11180            out.print(prefix); out.print(
11181                    Integer.toHexString(System.identityHashCode(filter.service)));
11182                    out.print(' ');
11183                    filter.service.printComponentShortName(out);
11184                    out.print(" filter ");
11185                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11186        }
11187
11188        @Override
11189        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11190            return filter.service;
11191        }
11192
11193        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11194            PackageParser.Service service = (PackageParser.Service)label;
11195            out.print(prefix); out.print(
11196                    Integer.toHexString(System.identityHashCode(service)));
11197                    out.print(' ');
11198                    service.printComponentShortName(out);
11199            if (count > 1) {
11200                out.print(" ("); out.print(count); out.print(" filters)");
11201            }
11202            out.println();
11203        }
11204
11205//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11206//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11207//            final List<ResolveInfo> retList = Lists.newArrayList();
11208//            while (i.hasNext()) {
11209//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11210//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11211//                    retList.add(resolveInfo);
11212//                }
11213//            }
11214//            return retList;
11215//        }
11216
11217        // Keys are String (activity class name), values are Activity.
11218        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11219                = new ArrayMap<ComponentName, PackageParser.Service>();
11220        private int mFlags;
11221    };
11222
11223    private final class ProviderIntentResolver
11224            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11225        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11226                boolean defaultOnly, int userId) {
11227            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11228            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11229        }
11230
11231        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11232                int userId) {
11233            if (!sUserManager.exists(userId))
11234                return null;
11235            mFlags = flags;
11236            return super.queryIntent(intent, resolvedType,
11237                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11238        }
11239
11240        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11241                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11242            if (!sUserManager.exists(userId))
11243                return null;
11244            if (packageProviders == null) {
11245                return null;
11246            }
11247            mFlags = flags;
11248            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11249            final int N = packageProviders.size();
11250            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11251                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11252
11253            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11254            for (int i = 0; i < N; ++i) {
11255                intentFilters = packageProviders.get(i).intents;
11256                if (intentFilters != null && intentFilters.size() > 0) {
11257                    PackageParser.ProviderIntentInfo[] array =
11258                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11259                    intentFilters.toArray(array);
11260                    listCut.add(array);
11261                }
11262            }
11263            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11264        }
11265
11266        public final void addProvider(PackageParser.Provider p) {
11267            if (mProviders.containsKey(p.getComponentName())) {
11268                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11269                return;
11270            }
11271
11272            mProviders.put(p.getComponentName(), p);
11273            if (DEBUG_SHOW_INFO) {
11274                Log.v(TAG, "  "
11275                        + (p.info.nonLocalizedLabel != null
11276                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11277                Log.v(TAG, "    Class=" + p.info.name);
11278            }
11279            final int NI = p.intents.size();
11280            int j;
11281            for (j = 0; j < NI; j++) {
11282                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11283                if (DEBUG_SHOW_INFO) {
11284                    Log.v(TAG, "    IntentFilter:");
11285                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11286                }
11287                if (!intent.debugCheck()) {
11288                    Log.w(TAG, "==> For Provider " + p.info.name);
11289                }
11290                addFilter(intent);
11291            }
11292        }
11293
11294        public final void removeProvider(PackageParser.Provider p) {
11295            mProviders.remove(p.getComponentName());
11296            if (DEBUG_SHOW_INFO) {
11297                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11298                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11299                Log.v(TAG, "    Class=" + p.info.name);
11300            }
11301            final int NI = p.intents.size();
11302            int j;
11303            for (j = 0; j < NI; j++) {
11304                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11305                if (DEBUG_SHOW_INFO) {
11306                    Log.v(TAG, "    IntentFilter:");
11307                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11308                }
11309                removeFilter(intent);
11310            }
11311        }
11312
11313        @Override
11314        protected boolean allowFilterResult(
11315                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11316            ProviderInfo filterPi = filter.provider.info;
11317            for (int i = dest.size() - 1; i >= 0; i--) {
11318                ProviderInfo destPi = dest.get(i).providerInfo;
11319                if (destPi.name == filterPi.name
11320                        && destPi.packageName == filterPi.packageName) {
11321                    return false;
11322                }
11323            }
11324            return true;
11325        }
11326
11327        @Override
11328        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11329            return new PackageParser.ProviderIntentInfo[size];
11330        }
11331
11332        @Override
11333        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11334            if (!sUserManager.exists(userId))
11335                return true;
11336            PackageParser.Package p = filter.provider.owner;
11337            if (p != null) {
11338                PackageSetting ps = (PackageSetting) p.mExtras;
11339                if (ps != null) {
11340                    // System apps are never considered stopped for purposes of
11341                    // filtering, because there may be no way for the user to
11342                    // actually re-launch them.
11343                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11344                            && ps.getStopped(userId);
11345                }
11346            }
11347            return false;
11348        }
11349
11350        @Override
11351        protected boolean isPackageForFilter(String packageName,
11352                PackageParser.ProviderIntentInfo info) {
11353            return packageName.equals(info.provider.owner.packageName);
11354        }
11355
11356        @Override
11357        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11358                int match, int userId) {
11359            if (!sUserManager.exists(userId))
11360                return null;
11361            final PackageParser.ProviderIntentInfo info = filter;
11362            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11363                return null;
11364            }
11365            final PackageParser.Provider provider = info.provider;
11366            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11367            if (ps == null) {
11368                return null;
11369            }
11370            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11371                    ps.readUserState(userId), userId);
11372            if (pi == null) {
11373                return null;
11374            }
11375            final ResolveInfo res = new ResolveInfo();
11376            res.providerInfo = pi;
11377            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11378                res.filter = filter;
11379            }
11380            res.priority = info.getPriority();
11381            res.preferredOrder = provider.owner.mPreferredOrder;
11382            res.match = match;
11383            res.isDefault = info.hasDefault;
11384            res.labelRes = info.labelRes;
11385            res.nonLocalizedLabel = info.nonLocalizedLabel;
11386            res.icon = info.icon;
11387            res.system = res.providerInfo.applicationInfo.isSystemApp();
11388            return res;
11389        }
11390
11391        @Override
11392        protected void sortResults(List<ResolveInfo> results) {
11393            Collections.sort(results, mResolvePrioritySorter);
11394        }
11395
11396        @Override
11397        protected void dumpFilter(PrintWriter out, String prefix,
11398                PackageParser.ProviderIntentInfo filter) {
11399            out.print(prefix);
11400            out.print(
11401                    Integer.toHexString(System.identityHashCode(filter.provider)));
11402            out.print(' ');
11403            filter.provider.printComponentShortName(out);
11404            out.print(" filter ");
11405            out.println(Integer.toHexString(System.identityHashCode(filter)));
11406        }
11407
11408        @Override
11409        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11410            return filter.provider;
11411        }
11412
11413        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11414            PackageParser.Provider provider = (PackageParser.Provider)label;
11415            out.print(prefix); out.print(
11416                    Integer.toHexString(System.identityHashCode(provider)));
11417                    out.print(' ');
11418                    provider.printComponentShortName(out);
11419            if (count > 1) {
11420                out.print(" ("); out.print(count); out.print(" filters)");
11421            }
11422            out.println();
11423        }
11424
11425        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11426                = new ArrayMap<ComponentName, PackageParser.Provider>();
11427        private int mFlags;
11428    }
11429
11430    private static final class EphemeralIntentResolver
11431            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11432        /**
11433         * The result that has the highest defined order. Ordering applies on a
11434         * per-package basis. Mapping is from package name to Pair of order and
11435         * EphemeralResolveInfo.
11436         * <p>
11437         * NOTE: This is implemented as a field variable for convenience and efficiency.
11438         * By having a field variable, we're able to track filter ordering as soon as
11439         * a non-zero order is defined. Otherwise, multiple loops across the result set
11440         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11441         * this needs to be contained entirely within {@link #filterResults()}.
11442         */
11443        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11444
11445        @Override
11446        protected EphemeralResolveIntentInfo[] newArray(int size) {
11447            return new EphemeralResolveIntentInfo[size];
11448        }
11449
11450        @Override
11451        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11452            return true;
11453        }
11454
11455        @Override
11456        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11457                int userId) {
11458            if (!sUserManager.exists(userId)) {
11459                return null;
11460            }
11461            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11462            final Integer order = info.getOrder();
11463            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11464                    mOrderResult.get(packageName);
11465            // ordering is enabled and this item's order isn't high enough
11466            if (lastOrderResult != null && lastOrderResult.first >= order) {
11467                return null;
11468            }
11469            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11470            if (order > 0) {
11471                // non-zero order, enable ordering
11472                mOrderResult.put(packageName, new Pair<>(order, res));
11473            }
11474            return res;
11475        }
11476
11477        @Override
11478        protected void filterResults(List<EphemeralResolveInfo> results) {
11479            // only do work if ordering is enabled [most of the time it won't be]
11480            if (mOrderResult.size() == 0) {
11481                return;
11482            }
11483            int resultSize = results.size();
11484            for (int i = 0; i < resultSize; i++) {
11485                final EphemeralResolveInfo info = results.get(i);
11486                final String packageName = info.getPackageName();
11487                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11488                if (savedInfo == null) {
11489                    // package doesn't having ordering
11490                    continue;
11491                }
11492                if (savedInfo.second == info) {
11493                    // circled back to the highest ordered item; remove from order list
11494                    mOrderResult.remove(savedInfo);
11495                    if (mOrderResult.size() == 0) {
11496                        // no more ordered items
11497                        break;
11498                    }
11499                    continue;
11500                }
11501                // item has a worse order, remove it from the result list
11502                results.remove(i);
11503                resultSize--;
11504                i--;
11505            }
11506        }
11507    }
11508
11509    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11510            new Comparator<ResolveInfo>() {
11511        public int compare(ResolveInfo r1, ResolveInfo r2) {
11512            int v1 = r1.priority;
11513            int v2 = r2.priority;
11514            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11515            if (v1 != v2) {
11516                return (v1 > v2) ? -1 : 1;
11517            }
11518            v1 = r1.preferredOrder;
11519            v2 = r2.preferredOrder;
11520            if (v1 != v2) {
11521                return (v1 > v2) ? -1 : 1;
11522            }
11523            if (r1.isDefault != r2.isDefault) {
11524                return r1.isDefault ? -1 : 1;
11525            }
11526            v1 = r1.match;
11527            v2 = r2.match;
11528            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11529            if (v1 != v2) {
11530                return (v1 > v2) ? -1 : 1;
11531            }
11532            if (r1.system != r2.system) {
11533                return r1.system ? -1 : 1;
11534            }
11535            if (r1.activityInfo != null) {
11536                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11537            }
11538            if (r1.serviceInfo != null) {
11539                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11540            }
11541            if (r1.providerInfo != null) {
11542                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11543            }
11544            return 0;
11545        }
11546    };
11547
11548    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11549            new Comparator<ProviderInfo>() {
11550        public int compare(ProviderInfo p1, ProviderInfo p2) {
11551            final int v1 = p1.initOrder;
11552            final int v2 = p2.initOrder;
11553            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11554        }
11555    };
11556
11557    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11558            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11559            final int[] userIds) {
11560        mHandler.post(new Runnable() {
11561            @Override
11562            public void run() {
11563                try {
11564                    final IActivityManager am = ActivityManagerNative.getDefault();
11565                    if (am == null) return;
11566                    final int[] resolvedUserIds;
11567                    if (userIds == null) {
11568                        resolvedUserIds = am.getRunningUserIds();
11569                    } else {
11570                        resolvedUserIds = userIds;
11571                    }
11572                    for (int id : resolvedUserIds) {
11573                        final Intent intent = new Intent(action,
11574                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11575                        if (extras != null) {
11576                            intent.putExtras(extras);
11577                        }
11578                        if (targetPkg != null) {
11579                            intent.setPackage(targetPkg);
11580                        }
11581                        // Modify the UID when posting to other users
11582                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11583                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11584                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11585                            intent.putExtra(Intent.EXTRA_UID, uid);
11586                        }
11587                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11588                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11589                        if (DEBUG_BROADCASTS) {
11590                            RuntimeException here = new RuntimeException("here");
11591                            here.fillInStackTrace();
11592                            Slog.d(TAG, "Sending to user " + id + ": "
11593                                    + intent.toShortString(false, true, false, false)
11594                                    + " " + intent.getExtras(), here);
11595                        }
11596                        am.broadcastIntent(null, intent, null, finishedReceiver,
11597                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11598                                null, finishedReceiver != null, false, id);
11599                    }
11600                } catch (RemoteException ex) {
11601                }
11602            }
11603        });
11604    }
11605
11606    /**
11607     * Check if the external storage media is available. This is true if there
11608     * is a mounted external storage medium or if the external storage is
11609     * emulated.
11610     */
11611    private boolean isExternalMediaAvailable() {
11612        return mMediaMounted || Environment.isExternalStorageEmulated();
11613    }
11614
11615    @Override
11616    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11617        // writer
11618        synchronized (mPackages) {
11619            if (!isExternalMediaAvailable()) {
11620                // If the external storage is no longer mounted at this point,
11621                // the caller may not have been able to delete all of this
11622                // packages files and can not delete any more.  Bail.
11623                return null;
11624            }
11625            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11626            if (lastPackage != null) {
11627                pkgs.remove(lastPackage);
11628            }
11629            if (pkgs.size() > 0) {
11630                return pkgs.get(0);
11631            }
11632        }
11633        return null;
11634    }
11635
11636    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11637        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11638                userId, andCode ? 1 : 0, packageName);
11639        if (mSystemReady) {
11640            msg.sendToTarget();
11641        } else {
11642            if (mPostSystemReadyMessages == null) {
11643                mPostSystemReadyMessages = new ArrayList<>();
11644            }
11645            mPostSystemReadyMessages.add(msg);
11646        }
11647    }
11648
11649    void startCleaningPackages() {
11650        // reader
11651        if (!isExternalMediaAvailable()) {
11652            return;
11653        }
11654        synchronized (mPackages) {
11655            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11656                return;
11657            }
11658        }
11659        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11660        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11661        IActivityManager am = ActivityManagerNative.getDefault();
11662        if (am != null) {
11663            try {
11664                am.startService(null, intent, null, mContext.getOpPackageName(),
11665                        UserHandle.USER_SYSTEM);
11666            } catch (RemoteException e) {
11667            }
11668        }
11669    }
11670
11671    @Override
11672    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11673            int installFlags, String installerPackageName, int userId) {
11674        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11675
11676        final int callingUid = Binder.getCallingUid();
11677        enforceCrossUserPermission(callingUid, userId,
11678                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11679
11680        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11681            try {
11682                if (observer != null) {
11683                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11684                }
11685            } catch (RemoteException re) {
11686            }
11687            return;
11688        }
11689
11690        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11691            installFlags |= PackageManager.INSTALL_FROM_ADB;
11692
11693        } else {
11694            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11695            // about installerPackageName.
11696
11697            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11698            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11699        }
11700
11701        UserHandle user;
11702        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11703            user = UserHandle.ALL;
11704        } else {
11705            user = new UserHandle(userId);
11706        }
11707
11708        // Only system components can circumvent runtime permissions when installing.
11709        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11710                && mContext.checkCallingOrSelfPermission(Manifest.permission
11711                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11712            throw new SecurityException("You need the "
11713                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11714                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11715        }
11716
11717        final File originFile = new File(originPath);
11718        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11719
11720        final Message msg = mHandler.obtainMessage(INIT_COPY);
11721        final VerificationInfo verificationInfo = new VerificationInfo(
11722                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11723        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11724                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11725                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11726                null /*certificates*/);
11727        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11728        msg.obj = params;
11729
11730        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11731                System.identityHashCode(msg.obj));
11732        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11733                System.identityHashCode(msg.obj));
11734
11735        mHandler.sendMessage(msg);
11736    }
11737
11738    void installStage(String packageName, File stagedDir, String stagedCid,
11739            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11740            String installerPackageName, int installerUid, UserHandle user,
11741            Certificate[][] certificates) {
11742        if (DEBUG_EPHEMERAL) {
11743            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11744                Slog.d(TAG, "Ephemeral install of " + packageName);
11745            }
11746        }
11747        final VerificationInfo verificationInfo = new VerificationInfo(
11748                sessionParams.originatingUri, sessionParams.referrerUri,
11749                sessionParams.originatingUid, installerUid);
11750
11751        final OriginInfo origin;
11752        if (stagedDir != null) {
11753            origin = OriginInfo.fromStagedFile(stagedDir);
11754        } else {
11755            origin = OriginInfo.fromStagedContainer(stagedCid);
11756        }
11757
11758        final Message msg = mHandler.obtainMessage(INIT_COPY);
11759        final InstallParams params = new InstallParams(origin, null, observer,
11760                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11761                verificationInfo, user, sessionParams.abiOverride,
11762                sessionParams.grantedRuntimePermissions, certificates);
11763        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11764        msg.obj = params;
11765
11766        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11767                System.identityHashCode(msg.obj));
11768        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11769                System.identityHashCode(msg.obj));
11770
11771        mHandler.sendMessage(msg);
11772    }
11773
11774    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11775            int userId) {
11776        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11777        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11778    }
11779
11780    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11781            int appId, int userId) {
11782        Bundle extras = new Bundle(1);
11783        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11784
11785        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11786                packageName, extras, 0, null, null, new int[] {userId});
11787        try {
11788            IActivityManager am = ActivityManagerNative.getDefault();
11789            if (isSystem && am.isUserRunning(userId, 0)) {
11790                // The just-installed/enabled app is bundled on the system, so presumed
11791                // to be able to run automatically without needing an explicit launch.
11792                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11793                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11794                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11795                        .setPackage(packageName);
11796                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11797                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11798            }
11799        } catch (RemoteException e) {
11800            // shouldn't happen
11801            Slog.w(TAG, "Unable to bootstrap installed package", e);
11802        }
11803    }
11804
11805    @Override
11806    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11807            int userId) {
11808        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11809        PackageSetting pkgSetting;
11810        final int uid = Binder.getCallingUid();
11811        enforceCrossUserPermission(uid, userId,
11812                true /* requireFullPermission */, true /* checkShell */,
11813                "setApplicationHiddenSetting for user " + userId);
11814
11815        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11816            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11817            return false;
11818        }
11819
11820        long callingId = Binder.clearCallingIdentity();
11821        try {
11822            boolean sendAdded = false;
11823            boolean sendRemoved = false;
11824            // writer
11825            synchronized (mPackages) {
11826                pkgSetting = mSettings.mPackages.get(packageName);
11827                if (pkgSetting == null) {
11828                    return false;
11829                }
11830                // Do not allow "android" is being disabled
11831                if ("android".equals(packageName)) {
11832                    Slog.w(TAG, "Cannot hide package: android");
11833                    return false;
11834                }
11835                // Only allow protected packages to hide themselves.
11836                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11837                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11838                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11839                    return false;
11840                }
11841
11842                if (pkgSetting.getHidden(userId) != hidden) {
11843                    pkgSetting.setHidden(hidden, userId);
11844                    mSettings.writePackageRestrictionsLPr(userId);
11845                    if (hidden) {
11846                        sendRemoved = true;
11847                    } else {
11848                        sendAdded = true;
11849                    }
11850                }
11851            }
11852            if (sendAdded) {
11853                sendPackageAddedForUser(packageName, pkgSetting, userId);
11854                return true;
11855            }
11856            if (sendRemoved) {
11857                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11858                        "hiding pkg");
11859                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11860                return true;
11861            }
11862        } finally {
11863            Binder.restoreCallingIdentity(callingId);
11864        }
11865        return false;
11866    }
11867
11868    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11869            int userId) {
11870        final PackageRemovedInfo info = new PackageRemovedInfo();
11871        info.removedPackage = packageName;
11872        info.removedUsers = new int[] {userId};
11873        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11874        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11875    }
11876
11877    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11878        if (pkgList.length > 0) {
11879            Bundle extras = new Bundle(1);
11880            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11881
11882            sendPackageBroadcast(
11883                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11884                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11885                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11886                    new int[] {userId});
11887        }
11888    }
11889
11890    /**
11891     * Returns true if application is not found or there was an error. Otherwise it returns
11892     * the hidden state of the package for the given user.
11893     */
11894    @Override
11895    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11896        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11897        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11898                true /* requireFullPermission */, false /* checkShell */,
11899                "getApplicationHidden for user " + userId);
11900        PackageSetting pkgSetting;
11901        long callingId = Binder.clearCallingIdentity();
11902        try {
11903            // writer
11904            synchronized (mPackages) {
11905                pkgSetting = mSettings.mPackages.get(packageName);
11906                if (pkgSetting == null) {
11907                    return true;
11908                }
11909                return pkgSetting.getHidden(userId);
11910            }
11911        } finally {
11912            Binder.restoreCallingIdentity(callingId);
11913        }
11914    }
11915
11916    /**
11917     * @hide
11918     */
11919    @Override
11920    public int installExistingPackageAsUser(String packageName, int userId) {
11921        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11922                null);
11923        PackageSetting pkgSetting;
11924        final int uid = Binder.getCallingUid();
11925        enforceCrossUserPermission(uid, userId,
11926                true /* requireFullPermission */, true /* checkShell */,
11927                "installExistingPackage for user " + userId);
11928        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11929            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11930        }
11931
11932        long callingId = Binder.clearCallingIdentity();
11933        try {
11934            boolean installed = false;
11935
11936            // writer
11937            synchronized (mPackages) {
11938                pkgSetting = mSettings.mPackages.get(packageName);
11939                if (pkgSetting == null) {
11940                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11941                }
11942                if (!pkgSetting.getInstalled(userId)) {
11943                    pkgSetting.setInstalled(true, userId);
11944                    pkgSetting.setHidden(false, userId);
11945                    mSettings.writePackageRestrictionsLPr(userId);
11946                    installed = true;
11947                }
11948            }
11949
11950            if (installed) {
11951                if (pkgSetting.pkg != null) {
11952                    synchronized (mInstallLock) {
11953                        // We don't need to freeze for a brand new install
11954                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11955                    }
11956                }
11957                sendPackageAddedForUser(packageName, pkgSetting, userId);
11958            }
11959        } finally {
11960            Binder.restoreCallingIdentity(callingId);
11961        }
11962
11963        return PackageManager.INSTALL_SUCCEEDED;
11964    }
11965
11966    boolean isUserRestricted(int userId, String restrictionKey) {
11967        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11968        if (restrictions.getBoolean(restrictionKey, false)) {
11969            Log.w(TAG, "User is restricted: " + restrictionKey);
11970            return true;
11971        }
11972        return false;
11973    }
11974
11975    @Override
11976    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11977            int userId) {
11978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11979        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11980                true /* requireFullPermission */, true /* checkShell */,
11981                "setPackagesSuspended for user " + userId);
11982
11983        if (ArrayUtils.isEmpty(packageNames)) {
11984            return packageNames;
11985        }
11986
11987        // List of package names for whom the suspended state has changed.
11988        List<String> changedPackages = new ArrayList<>(packageNames.length);
11989        // List of package names for whom the suspended state is not set as requested in this
11990        // method.
11991        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11992        long callingId = Binder.clearCallingIdentity();
11993        try {
11994            for (int i = 0; i < packageNames.length; i++) {
11995                String packageName = packageNames[i];
11996                boolean changed = false;
11997                final int appId;
11998                synchronized (mPackages) {
11999                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12000                    if (pkgSetting == null) {
12001                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12002                                + "\". Skipping suspending/un-suspending.");
12003                        unactionedPackages.add(packageName);
12004                        continue;
12005                    }
12006                    appId = pkgSetting.appId;
12007                    if (pkgSetting.getSuspended(userId) != suspended) {
12008                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12009                            unactionedPackages.add(packageName);
12010                            continue;
12011                        }
12012                        pkgSetting.setSuspended(suspended, userId);
12013                        mSettings.writePackageRestrictionsLPr(userId);
12014                        changed = true;
12015                        changedPackages.add(packageName);
12016                    }
12017                }
12018
12019                if (changed && suspended) {
12020                    killApplication(packageName, UserHandle.getUid(userId, appId),
12021                            "suspending package");
12022                }
12023            }
12024        } finally {
12025            Binder.restoreCallingIdentity(callingId);
12026        }
12027
12028        if (!changedPackages.isEmpty()) {
12029            sendPackagesSuspendedForUser(changedPackages.toArray(
12030                    new String[changedPackages.size()]), userId, suspended);
12031        }
12032
12033        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12034    }
12035
12036    @Override
12037    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12038        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12039                true /* requireFullPermission */, false /* checkShell */,
12040                "isPackageSuspendedForUser for user " + userId);
12041        synchronized (mPackages) {
12042            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12043            if (pkgSetting == null) {
12044                throw new IllegalArgumentException("Unknown target package: " + packageName);
12045            }
12046            return pkgSetting.getSuspended(userId);
12047        }
12048    }
12049
12050    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12051        if (isPackageDeviceAdmin(packageName, userId)) {
12052            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12053                    + "\": has an active device admin");
12054            return false;
12055        }
12056
12057        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12058        if (packageName.equals(activeLauncherPackageName)) {
12059            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12060                    + "\": contains the active launcher");
12061            return false;
12062        }
12063
12064        if (packageName.equals(mRequiredInstallerPackage)) {
12065            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12066                    + "\": required for package installation");
12067            return false;
12068        }
12069
12070        if (packageName.equals(mRequiredUninstallerPackage)) {
12071            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12072                    + "\": required for package uninstallation");
12073            return false;
12074        }
12075
12076        if (packageName.equals(mRequiredVerifierPackage)) {
12077            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12078                    + "\": required for package verification");
12079            return false;
12080        }
12081
12082        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12083            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12084                    + "\": is the default dialer");
12085            return false;
12086        }
12087
12088        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12089            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12090                    + "\": protected package");
12091            return false;
12092        }
12093
12094        return true;
12095    }
12096
12097    private String getActiveLauncherPackageName(int userId) {
12098        Intent intent = new Intent(Intent.ACTION_MAIN);
12099        intent.addCategory(Intent.CATEGORY_HOME);
12100        ResolveInfo resolveInfo = resolveIntent(
12101                intent,
12102                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12103                PackageManager.MATCH_DEFAULT_ONLY,
12104                userId);
12105
12106        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12107    }
12108
12109    private String getDefaultDialerPackageName(int userId) {
12110        synchronized (mPackages) {
12111            return mSettings.getDefaultDialerPackageNameLPw(userId);
12112        }
12113    }
12114
12115    @Override
12116    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12117        mContext.enforceCallingOrSelfPermission(
12118                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12119                "Only package verification agents can verify applications");
12120
12121        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12122        final PackageVerificationResponse response = new PackageVerificationResponse(
12123                verificationCode, Binder.getCallingUid());
12124        msg.arg1 = id;
12125        msg.obj = response;
12126        mHandler.sendMessage(msg);
12127    }
12128
12129    @Override
12130    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12131            long millisecondsToDelay) {
12132        mContext.enforceCallingOrSelfPermission(
12133                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12134                "Only package verification agents can extend verification timeouts");
12135
12136        final PackageVerificationState state = mPendingVerification.get(id);
12137        final PackageVerificationResponse response = new PackageVerificationResponse(
12138                verificationCodeAtTimeout, Binder.getCallingUid());
12139
12140        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12141            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12142        }
12143        if (millisecondsToDelay < 0) {
12144            millisecondsToDelay = 0;
12145        }
12146        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12147                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12148            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12149        }
12150
12151        if ((state != null) && !state.timeoutExtended()) {
12152            state.extendTimeout();
12153
12154            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12155            msg.arg1 = id;
12156            msg.obj = response;
12157            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12158        }
12159    }
12160
12161    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12162            int verificationCode, UserHandle user) {
12163        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12164        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12165        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12166        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12167        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12168
12169        mContext.sendBroadcastAsUser(intent, user,
12170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12171    }
12172
12173    private ComponentName matchComponentForVerifier(String packageName,
12174            List<ResolveInfo> receivers) {
12175        ActivityInfo targetReceiver = null;
12176
12177        final int NR = receivers.size();
12178        for (int i = 0; i < NR; i++) {
12179            final ResolveInfo info = receivers.get(i);
12180            if (info.activityInfo == null) {
12181                continue;
12182            }
12183
12184            if (packageName.equals(info.activityInfo.packageName)) {
12185                targetReceiver = info.activityInfo;
12186                break;
12187            }
12188        }
12189
12190        if (targetReceiver == null) {
12191            return null;
12192        }
12193
12194        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12195    }
12196
12197    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12198            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12199        if (pkgInfo.verifiers.length == 0) {
12200            return null;
12201        }
12202
12203        final int N = pkgInfo.verifiers.length;
12204        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12205        for (int i = 0; i < N; i++) {
12206            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12207
12208            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12209                    receivers);
12210            if (comp == null) {
12211                continue;
12212            }
12213
12214            final int verifierUid = getUidForVerifier(verifierInfo);
12215            if (verifierUid == -1) {
12216                continue;
12217            }
12218
12219            if (DEBUG_VERIFY) {
12220                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12221                        + " with the correct signature");
12222            }
12223            sufficientVerifiers.add(comp);
12224            verificationState.addSufficientVerifier(verifierUid);
12225        }
12226
12227        return sufficientVerifiers;
12228    }
12229
12230    private int getUidForVerifier(VerifierInfo verifierInfo) {
12231        synchronized (mPackages) {
12232            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12233            if (pkg == null) {
12234                return -1;
12235            } else if (pkg.mSignatures.length != 1) {
12236                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12237                        + " has more than one signature; ignoring");
12238                return -1;
12239            }
12240
12241            /*
12242             * If the public key of the package's signature does not match
12243             * our expected public key, then this is a different package and
12244             * we should skip.
12245             */
12246
12247            final byte[] expectedPublicKey;
12248            try {
12249                final Signature verifierSig = pkg.mSignatures[0];
12250                final PublicKey publicKey = verifierSig.getPublicKey();
12251                expectedPublicKey = publicKey.getEncoded();
12252            } catch (CertificateException e) {
12253                return -1;
12254            }
12255
12256            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12257
12258            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12259                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12260                        + " does not have the expected public key; ignoring");
12261                return -1;
12262            }
12263
12264            return pkg.applicationInfo.uid;
12265        }
12266    }
12267
12268    @Override
12269    public void finishPackageInstall(int token, boolean didLaunch) {
12270        enforceSystemOrRoot("Only the system is allowed to finish installs");
12271
12272        if (DEBUG_INSTALL) {
12273            Slog.v(TAG, "BM finishing package install for " + token);
12274        }
12275        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12276
12277        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12278        mHandler.sendMessage(msg);
12279    }
12280
12281    /**
12282     * Get the verification agent timeout.
12283     *
12284     * @return verification timeout in milliseconds
12285     */
12286    private long getVerificationTimeout() {
12287        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12288                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12289                DEFAULT_VERIFICATION_TIMEOUT);
12290    }
12291
12292    /**
12293     * Get the default verification agent response code.
12294     *
12295     * @return default verification response code
12296     */
12297    private int getDefaultVerificationResponse() {
12298        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12299                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12300                DEFAULT_VERIFICATION_RESPONSE);
12301    }
12302
12303    /**
12304     * Check whether or not package verification has been enabled.
12305     *
12306     * @return true if verification should be performed
12307     */
12308    private boolean isVerificationEnabled(int userId, int installFlags) {
12309        if (!DEFAULT_VERIFY_ENABLE) {
12310            return false;
12311        }
12312        // Ephemeral apps don't get the full verification treatment
12313        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12314            if (DEBUG_EPHEMERAL) {
12315                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12316            }
12317            return false;
12318        }
12319
12320        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12321
12322        // Check if installing from ADB
12323        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12324            // Do not run verification in a test harness environment
12325            if (ActivityManager.isRunningInTestHarness()) {
12326                return false;
12327            }
12328            if (ensureVerifyAppsEnabled) {
12329                return true;
12330            }
12331            // Check if the developer does not want package verification for ADB installs
12332            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12333                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12334                return false;
12335            }
12336        }
12337
12338        if (ensureVerifyAppsEnabled) {
12339            return true;
12340        }
12341
12342        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12343                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12344    }
12345
12346    @Override
12347    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12348            throws RemoteException {
12349        mContext.enforceCallingOrSelfPermission(
12350                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12351                "Only intentfilter verification agents can verify applications");
12352
12353        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12354        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12355                Binder.getCallingUid(), verificationCode, failedDomains);
12356        msg.arg1 = id;
12357        msg.obj = response;
12358        mHandler.sendMessage(msg);
12359    }
12360
12361    @Override
12362    public int getIntentVerificationStatus(String packageName, int userId) {
12363        synchronized (mPackages) {
12364            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12365        }
12366    }
12367
12368    @Override
12369    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12370        mContext.enforceCallingOrSelfPermission(
12371                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12372
12373        boolean result = false;
12374        synchronized (mPackages) {
12375            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12376        }
12377        if (result) {
12378            scheduleWritePackageRestrictionsLocked(userId);
12379        }
12380        return result;
12381    }
12382
12383    @Override
12384    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12385            String packageName) {
12386        synchronized (mPackages) {
12387            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12388        }
12389    }
12390
12391    @Override
12392    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12393        if (TextUtils.isEmpty(packageName)) {
12394            return ParceledListSlice.emptyList();
12395        }
12396        synchronized (mPackages) {
12397            PackageParser.Package pkg = mPackages.get(packageName);
12398            if (pkg == null || pkg.activities == null) {
12399                return ParceledListSlice.emptyList();
12400            }
12401            final int count = pkg.activities.size();
12402            ArrayList<IntentFilter> result = new ArrayList<>();
12403            for (int n=0; n<count; n++) {
12404                PackageParser.Activity activity = pkg.activities.get(n);
12405                if (activity.intents != null && activity.intents.size() > 0) {
12406                    result.addAll(activity.intents);
12407                }
12408            }
12409            return new ParceledListSlice<>(result);
12410        }
12411    }
12412
12413    @Override
12414    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12415        mContext.enforceCallingOrSelfPermission(
12416                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12417
12418        synchronized (mPackages) {
12419            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12420            if (packageName != null) {
12421                result |= updateIntentVerificationStatus(packageName,
12422                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12423                        userId);
12424                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12425                        packageName, userId);
12426            }
12427            return result;
12428        }
12429    }
12430
12431    @Override
12432    public String getDefaultBrowserPackageName(int userId) {
12433        synchronized (mPackages) {
12434            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12435        }
12436    }
12437
12438    /**
12439     * Get the "allow unknown sources" setting.
12440     *
12441     * @return the current "allow unknown sources" setting
12442     */
12443    private int getUnknownSourcesSettings() {
12444        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12445                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12446                -1);
12447    }
12448
12449    @Override
12450    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12451        final int uid = Binder.getCallingUid();
12452        // writer
12453        synchronized (mPackages) {
12454            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12455            if (targetPackageSetting == null) {
12456                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12457            }
12458
12459            PackageSetting installerPackageSetting;
12460            if (installerPackageName != null) {
12461                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12462                if (installerPackageSetting == null) {
12463                    throw new IllegalArgumentException("Unknown installer package: "
12464                            + installerPackageName);
12465                }
12466            } else {
12467                installerPackageSetting = null;
12468            }
12469
12470            Signature[] callerSignature;
12471            Object obj = mSettings.getUserIdLPr(uid);
12472            if (obj != null) {
12473                if (obj instanceof SharedUserSetting) {
12474                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12475                } else if (obj instanceof PackageSetting) {
12476                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12477                } else {
12478                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12479                }
12480            } else {
12481                throw new SecurityException("Unknown calling UID: " + uid);
12482            }
12483
12484            // Verify: can't set installerPackageName to a package that is
12485            // not signed with the same cert as the caller.
12486            if (installerPackageSetting != null) {
12487                if (compareSignatures(callerSignature,
12488                        installerPackageSetting.signatures.mSignatures)
12489                        != PackageManager.SIGNATURE_MATCH) {
12490                    throw new SecurityException(
12491                            "Caller does not have same cert as new installer package "
12492                            + installerPackageName);
12493                }
12494            }
12495
12496            // Verify: if target already has an installer package, it must
12497            // be signed with the same cert as the caller.
12498            if (targetPackageSetting.installerPackageName != null) {
12499                PackageSetting setting = mSettings.mPackages.get(
12500                        targetPackageSetting.installerPackageName);
12501                // If the currently set package isn't valid, then it's always
12502                // okay to change it.
12503                if (setting != null) {
12504                    if (compareSignatures(callerSignature,
12505                            setting.signatures.mSignatures)
12506                            != PackageManager.SIGNATURE_MATCH) {
12507                        throw new SecurityException(
12508                                "Caller does not have same cert as old installer package "
12509                                + targetPackageSetting.installerPackageName);
12510                    }
12511                }
12512            }
12513
12514            // Okay!
12515            targetPackageSetting.installerPackageName = installerPackageName;
12516            if (installerPackageName != null) {
12517                mSettings.mInstallerPackages.add(installerPackageName);
12518            }
12519            scheduleWriteSettingsLocked();
12520        }
12521    }
12522
12523    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12524        // Queue up an async operation since the package installation may take a little while.
12525        mHandler.post(new Runnable() {
12526            public void run() {
12527                mHandler.removeCallbacks(this);
12528                 // Result object to be returned
12529                PackageInstalledInfo res = new PackageInstalledInfo();
12530                res.setReturnCode(currentStatus);
12531                res.uid = -1;
12532                res.pkg = null;
12533                res.removedInfo = null;
12534                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12535                    args.doPreInstall(res.returnCode);
12536                    synchronized (mInstallLock) {
12537                        installPackageTracedLI(args, res);
12538                    }
12539                    args.doPostInstall(res.returnCode, res.uid);
12540                }
12541
12542                // A restore should be performed at this point if (a) the install
12543                // succeeded, (b) the operation is not an update, and (c) the new
12544                // package has not opted out of backup participation.
12545                final boolean update = res.removedInfo != null
12546                        && res.removedInfo.removedPackage != null;
12547                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12548                boolean doRestore = !update
12549                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12550
12551                // Set up the post-install work request bookkeeping.  This will be used
12552                // and cleaned up by the post-install event handling regardless of whether
12553                // there's a restore pass performed.  Token values are >= 1.
12554                int token;
12555                if (mNextInstallToken < 0) mNextInstallToken = 1;
12556                token = mNextInstallToken++;
12557
12558                PostInstallData data = new PostInstallData(args, res);
12559                mRunningInstalls.put(token, data);
12560                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12561
12562                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12563                    // Pass responsibility to the Backup Manager.  It will perform a
12564                    // restore if appropriate, then pass responsibility back to the
12565                    // Package Manager to run the post-install observer callbacks
12566                    // and broadcasts.
12567                    IBackupManager bm = IBackupManager.Stub.asInterface(
12568                            ServiceManager.getService(Context.BACKUP_SERVICE));
12569                    if (bm != null) {
12570                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12571                                + " to BM for possible restore");
12572                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12573                        try {
12574                            // TODO: http://b/22388012
12575                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12576                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12577                            } else {
12578                                doRestore = false;
12579                            }
12580                        } catch (RemoteException e) {
12581                            // can't happen; the backup manager is local
12582                        } catch (Exception e) {
12583                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12584                            doRestore = false;
12585                        }
12586                    } else {
12587                        Slog.e(TAG, "Backup Manager not found!");
12588                        doRestore = false;
12589                    }
12590                }
12591
12592                if (!doRestore) {
12593                    // No restore possible, or the Backup Manager was mysteriously not
12594                    // available -- just fire the post-install work request directly.
12595                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12596
12597                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12598
12599                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12600                    mHandler.sendMessage(msg);
12601                }
12602            }
12603        });
12604    }
12605
12606    /**
12607     * Callback from PackageSettings whenever an app is first transitioned out of the
12608     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12609     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12610     * here whether the app is the target of an ongoing install, and only send the
12611     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12612     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12613     * handling.
12614     */
12615    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12616        // Serialize this with the rest of the install-process message chain.  In the
12617        // restore-at-install case, this Runnable will necessarily run before the
12618        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12619        // are coherent.  In the non-restore case, the app has already completed install
12620        // and been launched through some other means, so it is not in a problematic
12621        // state for observers to see the FIRST_LAUNCH signal.
12622        mHandler.post(new Runnable() {
12623            @Override
12624            public void run() {
12625                for (int i = 0; i < mRunningInstalls.size(); i++) {
12626                    final PostInstallData data = mRunningInstalls.valueAt(i);
12627                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12628                        continue;
12629                    }
12630                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12631                        // right package; but is it for the right user?
12632                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12633                            if (userId == data.res.newUsers[uIndex]) {
12634                                if (DEBUG_BACKUP) {
12635                                    Slog.i(TAG, "Package " + pkgName
12636                                            + " being restored so deferring FIRST_LAUNCH");
12637                                }
12638                                return;
12639                            }
12640                        }
12641                    }
12642                }
12643                // didn't find it, so not being restored
12644                if (DEBUG_BACKUP) {
12645                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12646                }
12647                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12648            }
12649        });
12650    }
12651
12652    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12653        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12654                installerPkg, null, userIds);
12655    }
12656
12657    private abstract class HandlerParams {
12658        private static final int MAX_RETRIES = 4;
12659
12660        /**
12661         * Number of times startCopy() has been attempted and had a non-fatal
12662         * error.
12663         */
12664        private int mRetries = 0;
12665
12666        /** User handle for the user requesting the information or installation. */
12667        private final UserHandle mUser;
12668        String traceMethod;
12669        int traceCookie;
12670
12671        HandlerParams(UserHandle user) {
12672            mUser = user;
12673        }
12674
12675        UserHandle getUser() {
12676            return mUser;
12677        }
12678
12679        HandlerParams setTraceMethod(String traceMethod) {
12680            this.traceMethod = traceMethod;
12681            return this;
12682        }
12683
12684        HandlerParams setTraceCookie(int traceCookie) {
12685            this.traceCookie = traceCookie;
12686            return this;
12687        }
12688
12689        final boolean startCopy() {
12690            boolean res;
12691            try {
12692                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12693
12694                if (++mRetries > MAX_RETRIES) {
12695                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12696                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12697                    handleServiceError();
12698                    return false;
12699                } else {
12700                    handleStartCopy();
12701                    res = true;
12702                }
12703            } catch (RemoteException e) {
12704                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12705                mHandler.sendEmptyMessage(MCS_RECONNECT);
12706                res = false;
12707            }
12708            handleReturnCode();
12709            return res;
12710        }
12711
12712        final void serviceError() {
12713            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12714            handleServiceError();
12715            handleReturnCode();
12716        }
12717
12718        abstract void handleStartCopy() throws RemoteException;
12719        abstract void handleServiceError();
12720        abstract void handleReturnCode();
12721    }
12722
12723    class MeasureParams extends HandlerParams {
12724        private final PackageStats mStats;
12725        private boolean mSuccess;
12726
12727        private final IPackageStatsObserver mObserver;
12728
12729        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12730            super(new UserHandle(stats.userHandle));
12731            mObserver = observer;
12732            mStats = stats;
12733        }
12734
12735        @Override
12736        public String toString() {
12737            return "MeasureParams{"
12738                + Integer.toHexString(System.identityHashCode(this))
12739                + " " + mStats.packageName + "}";
12740        }
12741
12742        @Override
12743        void handleStartCopy() throws RemoteException {
12744            synchronized (mInstallLock) {
12745                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12746            }
12747
12748            if (mSuccess) {
12749                boolean mounted = false;
12750                try {
12751                    final String status = Environment.getExternalStorageState();
12752                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12753                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12754                } catch (Exception e) {
12755                }
12756
12757                if (mounted) {
12758                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12759
12760                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12761                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12762
12763                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12764                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12765
12766                    // Always subtract cache size, since it's a subdirectory
12767                    mStats.externalDataSize -= mStats.externalCacheSize;
12768
12769                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12770                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12771
12772                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12773                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12774                }
12775            }
12776        }
12777
12778        @Override
12779        void handleReturnCode() {
12780            if (mObserver != null) {
12781                try {
12782                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12783                } catch (RemoteException e) {
12784                    Slog.i(TAG, "Observer no longer exists.");
12785                }
12786            }
12787        }
12788
12789        @Override
12790        void handleServiceError() {
12791            Slog.e(TAG, "Could not measure application " + mStats.packageName
12792                            + " external storage");
12793        }
12794    }
12795
12796    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12797            throws RemoteException {
12798        long result = 0;
12799        for (File path : paths) {
12800            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12801        }
12802        return result;
12803    }
12804
12805    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12806        for (File path : paths) {
12807            try {
12808                mcs.clearDirectory(path.getAbsolutePath());
12809            } catch (RemoteException e) {
12810            }
12811        }
12812    }
12813
12814    static class OriginInfo {
12815        /**
12816         * Location where install is coming from, before it has been
12817         * copied/renamed into place. This could be a single monolithic APK
12818         * file, or a cluster directory. This location may be untrusted.
12819         */
12820        final File file;
12821        final String cid;
12822
12823        /**
12824         * Flag indicating that {@link #file} or {@link #cid} has already been
12825         * staged, meaning downstream users don't need to defensively copy the
12826         * contents.
12827         */
12828        final boolean staged;
12829
12830        /**
12831         * Flag indicating that {@link #file} or {@link #cid} is an already
12832         * installed app that is being moved.
12833         */
12834        final boolean existing;
12835
12836        final String resolvedPath;
12837        final File resolvedFile;
12838
12839        static OriginInfo fromNothing() {
12840            return new OriginInfo(null, null, false, false);
12841        }
12842
12843        static OriginInfo fromUntrustedFile(File file) {
12844            return new OriginInfo(file, null, false, false);
12845        }
12846
12847        static OriginInfo fromExistingFile(File file) {
12848            return new OriginInfo(file, null, false, true);
12849        }
12850
12851        static OriginInfo fromStagedFile(File file) {
12852            return new OriginInfo(file, null, true, false);
12853        }
12854
12855        static OriginInfo fromStagedContainer(String cid) {
12856            return new OriginInfo(null, cid, true, false);
12857        }
12858
12859        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12860            this.file = file;
12861            this.cid = cid;
12862            this.staged = staged;
12863            this.existing = existing;
12864
12865            if (cid != null) {
12866                resolvedPath = PackageHelper.getSdDir(cid);
12867                resolvedFile = new File(resolvedPath);
12868            } else if (file != null) {
12869                resolvedPath = file.getAbsolutePath();
12870                resolvedFile = file;
12871            } else {
12872                resolvedPath = null;
12873                resolvedFile = null;
12874            }
12875        }
12876    }
12877
12878    static class MoveInfo {
12879        final int moveId;
12880        final String fromUuid;
12881        final String toUuid;
12882        final String packageName;
12883        final String dataAppName;
12884        final int appId;
12885        final String seinfo;
12886        final int targetSdkVersion;
12887
12888        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12889                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12890            this.moveId = moveId;
12891            this.fromUuid = fromUuid;
12892            this.toUuid = toUuid;
12893            this.packageName = packageName;
12894            this.dataAppName = dataAppName;
12895            this.appId = appId;
12896            this.seinfo = seinfo;
12897            this.targetSdkVersion = targetSdkVersion;
12898        }
12899    }
12900
12901    static class VerificationInfo {
12902        /** A constant used to indicate that a uid value is not present. */
12903        public static final int NO_UID = -1;
12904
12905        /** URI referencing where the package was downloaded from. */
12906        final Uri originatingUri;
12907
12908        /** HTTP referrer URI associated with the originatingURI. */
12909        final Uri referrer;
12910
12911        /** UID of the application that the install request originated from. */
12912        final int originatingUid;
12913
12914        /** UID of application requesting the install */
12915        final int installerUid;
12916
12917        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12918            this.originatingUri = originatingUri;
12919            this.referrer = referrer;
12920            this.originatingUid = originatingUid;
12921            this.installerUid = installerUid;
12922        }
12923    }
12924
12925    class InstallParams extends HandlerParams {
12926        final OriginInfo origin;
12927        final MoveInfo move;
12928        final IPackageInstallObserver2 observer;
12929        int installFlags;
12930        final String installerPackageName;
12931        final String volumeUuid;
12932        private InstallArgs mArgs;
12933        private int mRet;
12934        final String packageAbiOverride;
12935        final String[] grantedRuntimePermissions;
12936        final VerificationInfo verificationInfo;
12937        final Certificate[][] certificates;
12938
12939        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12940                int installFlags, String installerPackageName, String volumeUuid,
12941                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12942                String[] grantedPermissions, Certificate[][] certificates) {
12943            super(user);
12944            this.origin = origin;
12945            this.move = move;
12946            this.observer = observer;
12947            this.installFlags = installFlags;
12948            this.installerPackageName = installerPackageName;
12949            this.volumeUuid = volumeUuid;
12950            this.verificationInfo = verificationInfo;
12951            this.packageAbiOverride = packageAbiOverride;
12952            this.grantedRuntimePermissions = grantedPermissions;
12953            this.certificates = certificates;
12954        }
12955
12956        @Override
12957        public String toString() {
12958            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12959                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12960        }
12961
12962        private int installLocationPolicy(PackageInfoLite pkgLite) {
12963            String packageName = pkgLite.packageName;
12964            int installLocation = pkgLite.installLocation;
12965            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12966            // reader
12967            synchronized (mPackages) {
12968                // Currently installed package which the new package is attempting to replace or
12969                // null if no such package is installed.
12970                PackageParser.Package installedPkg = mPackages.get(packageName);
12971                // Package which currently owns the data which the new package will own if installed.
12972                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12973                // will be null whereas dataOwnerPkg will contain information about the package
12974                // which was uninstalled while keeping its data.
12975                PackageParser.Package dataOwnerPkg = installedPkg;
12976                if (dataOwnerPkg  == null) {
12977                    PackageSetting ps = mSettings.mPackages.get(packageName);
12978                    if (ps != null) {
12979                        dataOwnerPkg = ps.pkg;
12980                    }
12981                }
12982
12983                if (dataOwnerPkg != null) {
12984                    // If installed, the package will get access to data left on the device by its
12985                    // predecessor. As a security measure, this is permited only if this is not a
12986                    // version downgrade or if the predecessor package is marked as debuggable and
12987                    // a downgrade is explicitly requested.
12988                    //
12989                    // On debuggable platform builds, downgrades are permitted even for
12990                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12991                    // not offer security guarantees and thus it's OK to disable some security
12992                    // mechanisms to make debugging/testing easier on those builds. However, even on
12993                    // debuggable builds downgrades of packages are permitted only if requested via
12994                    // installFlags. This is because we aim to keep the behavior of debuggable
12995                    // platform builds as close as possible to the behavior of non-debuggable
12996                    // platform builds.
12997                    final boolean downgradeRequested =
12998                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12999                    final boolean packageDebuggable =
13000                                (dataOwnerPkg.applicationInfo.flags
13001                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13002                    final boolean downgradePermitted =
13003                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13004                    if (!downgradePermitted) {
13005                        try {
13006                            checkDowngrade(dataOwnerPkg, pkgLite);
13007                        } catch (PackageManagerException e) {
13008                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13009                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13010                        }
13011                    }
13012                }
13013
13014                if (installedPkg != null) {
13015                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13016                        // Check for updated system application.
13017                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13018                            if (onSd) {
13019                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13020                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13021                            }
13022                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13023                        } else {
13024                            if (onSd) {
13025                                // Install flag overrides everything.
13026                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13027                            }
13028                            // If current upgrade specifies particular preference
13029                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13030                                // Application explicitly specified internal.
13031                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13032                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13033                                // App explictly prefers external. Let policy decide
13034                            } else {
13035                                // Prefer previous location
13036                                if (isExternal(installedPkg)) {
13037                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13038                                }
13039                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13040                            }
13041                        }
13042                    } else {
13043                        // Invalid install. Return error code
13044                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13045                    }
13046                }
13047            }
13048            // All the special cases have been taken care of.
13049            // Return result based on recommended install location.
13050            if (onSd) {
13051                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13052            }
13053            return pkgLite.recommendedInstallLocation;
13054        }
13055
13056        /*
13057         * Invoke remote method to get package information and install
13058         * location values. Override install location based on default
13059         * policy if needed and then create install arguments based
13060         * on the install location.
13061         */
13062        public void handleStartCopy() throws RemoteException {
13063            int ret = PackageManager.INSTALL_SUCCEEDED;
13064
13065            // If we're already staged, we've firmly committed to an install location
13066            if (origin.staged) {
13067                if (origin.file != null) {
13068                    installFlags |= PackageManager.INSTALL_INTERNAL;
13069                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13070                } else if (origin.cid != null) {
13071                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13072                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13073                } else {
13074                    throw new IllegalStateException("Invalid stage location");
13075                }
13076            }
13077
13078            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13079            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13080            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13081            PackageInfoLite pkgLite = null;
13082
13083            if (onInt && onSd) {
13084                // Check if both bits are set.
13085                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13086                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13087            } else if (onSd && ephemeral) {
13088                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13089                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13090            } else {
13091                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13092                        packageAbiOverride);
13093
13094                if (DEBUG_EPHEMERAL && ephemeral) {
13095                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13096                }
13097
13098                /*
13099                 * If we have too little free space, try to free cache
13100                 * before giving up.
13101                 */
13102                if (!origin.staged && pkgLite.recommendedInstallLocation
13103                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13104                    // TODO: focus freeing disk space on the target device
13105                    final StorageManager storage = StorageManager.from(mContext);
13106                    final long lowThreshold = storage.getStorageLowBytes(
13107                            Environment.getDataDirectory());
13108
13109                    final long sizeBytes = mContainerService.calculateInstalledSize(
13110                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13111
13112                    try {
13113                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13114                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13115                                installFlags, packageAbiOverride);
13116                    } catch (InstallerException e) {
13117                        Slog.w(TAG, "Failed to free cache", e);
13118                    }
13119
13120                    /*
13121                     * The cache free must have deleted the file we
13122                     * downloaded to install.
13123                     *
13124                     * TODO: fix the "freeCache" call to not delete
13125                     *       the file we care about.
13126                     */
13127                    if (pkgLite.recommendedInstallLocation
13128                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13129                        pkgLite.recommendedInstallLocation
13130                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13131                    }
13132                }
13133            }
13134
13135            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13136                int loc = pkgLite.recommendedInstallLocation;
13137                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13138                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13139                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13140                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13141                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13142                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13144                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13145                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13146                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13147                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13148                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13149                } else {
13150                    // Override with defaults if needed.
13151                    loc = installLocationPolicy(pkgLite);
13152                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13153                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13154                    } else if (!onSd && !onInt) {
13155                        // Override install location with flags
13156                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13157                            // Set the flag to install on external media.
13158                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13159                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13160                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13161                            if (DEBUG_EPHEMERAL) {
13162                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13163                            }
13164                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13165                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13166                                    |PackageManager.INSTALL_INTERNAL);
13167                        } else {
13168                            // Make sure the flag for installing on external
13169                            // media is unset
13170                            installFlags |= PackageManager.INSTALL_INTERNAL;
13171                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13172                        }
13173                    }
13174                }
13175            }
13176
13177            final InstallArgs args = createInstallArgs(this);
13178            mArgs = args;
13179
13180            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13181                // TODO: http://b/22976637
13182                // Apps installed for "all" users use the device owner to verify the app
13183                UserHandle verifierUser = getUser();
13184                if (verifierUser == UserHandle.ALL) {
13185                    verifierUser = UserHandle.SYSTEM;
13186                }
13187
13188                /*
13189                 * Determine if we have any installed package verifiers. If we
13190                 * do, then we'll defer to them to verify the packages.
13191                 */
13192                final int requiredUid = mRequiredVerifierPackage == null ? -1
13193                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13194                                verifierUser.getIdentifier());
13195                if (!origin.existing && requiredUid != -1
13196                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13197                    final Intent verification = new Intent(
13198                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13199                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13200                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13201                            PACKAGE_MIME_TYPE);
13202                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13203
13204                    // Query all live verifiers based on current user state
13205                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13206                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13207
13208                    if (DEBUG_VERIFY) {
13209                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13210                                + verification.toString() + " with " + pkgLite.verifiers.length
13211                                + " optional verifiers");
13212                    }
13213
13214                    final int verificationId = mPendingVerificationToken++;
13215
13216                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13217
13218                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13219                            installerPackageName);
13220
13221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13222                            installFlags);
13223
13224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13225                            pkgLite.packageName);
13226
13227                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13228                            pkgLite.versionCode);
13229
13230                    if (verificationInfo != null) {
13231                        if (verificationInfo.originatingUri != null) {
13232                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13233                                    verificationInfo.originatingUri);
13234                        }
13235                        if (verificationInfo.referrer != null) {
13236                            verification.putExtra(Intent.EXTRA_REFERRER,
13237                                    verificationInfo.referrer);
13238                        }
13239                        if (verificationInfo.originatingUid >= 0) {
13240                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13241                                    verificationInfo.originatingUid);
13242                        }
13243                        if (verificationInfo.installerUid >= 0) {
13244                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13245                                    verificationInfo.installerUid);
13246                        }
13247                    }
13248
13249                    final PackageVerificationState verificationState = new PackageVerificationState(
13250                            requiredUid, args);
13251
13252                    mPendingVerification.append(verificationId, verificationState);
13253
13254                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13255                            receivers, verificationState);
13256
13257                    /*
13258                     * If any sufficient verifiers were listed in the package
13259                     * manifest, attempt to ask them.
13260                     */
13261                    if (sufficientVerifiers != null) {
13262                        final int N = sufficientVerifiers.size();
13263                        if (N == 0) {
13264                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13265                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13266                        } else {
13267                            for (int i = 0; i < N; i++) {
13268                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13269
13270                                final Intent sufficientIntent = new Intent(verification);
13271                                sufficientIntent.setComponent(verifierComponent);
13272                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13273                            }
13274                        }
13275                    }
13276
13277                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13278                            mRequiredVerifierPackage, receivers);
13279                    if (ret == PackageManager.INSTALL_SUCCEEDED
13280                            && mRequiredVerifierPackage != null) {
13281                        Trace.asyncTraceBegin(
13282                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13283                        /*
13284                         * Send the intent to the required verification agent,
13285                         * but only start the verification timeout after the
13286                         * target BroadcastReceivers have run.
13287                         */
13288                        verification.setComponent(requiredVerifierComponent);
13289                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13290                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13291                                new BroadcastReceiver() {
13292                                    @Override
13293                                    public void onReceive(Context context, Intent intent) {
13294                                        final Message msg = mHandler
13295                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13296                                        msg.arg1 = verificationId;
13297                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13298                                    }
13299                                }, null, 0, null, null);
13300
13301                        /*
13302                         * We don't want the copy to proceed until verification
13303                         * succeeds, so null out this field.
13304                         */
13305                        mArgs = null;
13306                    }
13307                } else {
13308                    /*
13309                     * No package verification is enabled, so immediately start
13310                     * the remote call to initiate copy using temporary file.
13311                     */
13312                    ret = args.copyApk(mContainerService, true);
13313                }
13314            }
13315
13316            mRet = ret;
13317        }
13318
13319        @Override
13320        void handleReturnCode() {
13321            // If mArgs is null, then MCS couldn't be reached. When it
13322            // reconnects, it will try again to install. At that point, this
13323            // will succeed.
13324            if (mArgs != null) {
13325                processPendingInstall(mArgs, mRet);
13326            }
13327        }
13328
13329        @Override
13330        void handleServiceError() {
13331            mArgs = createInstallArgs(this);
13332            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13333        }
13334
13335        public boolean isForwardLocked() {
13336            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13337        }
13338    }
13339
13340    /**
13341     * Used during creation of InstallArgs
13342     *
13343     * @param installFlags package installation flags
13344     * @return true if should be installed on external storage
13345     */
13346    private static boolean installOnExternalAsec(int installFlags) {
13347        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13348            return false;
13349        }
13350        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13351            return true;
13352        }
13353        return false;
13354    }
13355
13356    /**
13357     * Used during creation of InstallArgs
13358     *
13359     * @param installFlags package installation flags
13360     * @return true if should be installed as forward locked
13361     */
13362    private static boolean installForwardLocked(int installFlags) {
13363        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13364    }
13365
13366    private InstallArgs createInstallArgs(InstallParams params) {
13367        if (params.move != null) {
13368            return new MoveInstallArgs(params);
13369        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13370            return new AsecInstallArgs(params);
13371        } else {
13372            return new FileInstallArgs(params);
13373        }
13374    }
13375
13376    /**
13377     * Create args that describe an existing installed package. Typically used
13378     * when cleaning up old installs, or used as a move source.
13379     */
13380    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13381            String resourcePath, String[] instructionSets) {
13382        final boolean isInAsec;
13383        if (installOnExternalAsec(installFlags)) {
13384            /* Apps on SD card are always in ASEC containers. */
13385            isInAsec = true;
13386        } else if (installForwardLocked(installFlags)
13387                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13388            /*
13389             * Forward-locked apps are only in ASEC containers if they're the
13390             * new style
13391             */
13392            isInAsec = true;
13393        } else {
13394            isInAsec = false;
13395        }
13396
13397        if (isInAsec) {
13398            return new AsecInstallArgs(codePath, instructionSets,
13399                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13400        } else {
13401            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13402        }
13403    }
13404
13405    static abstract class InstallArgs {
13406        /** @see InstallParams#origin */
13407        final OriginInfo origin;
13408        /** @see InstallParams#move */
13409        final MoveInfo move;
13410
13411        final IPackageInstallObserver2 observer;
13412        // Always refers to PackageManager flags only
13413        final int installFlags;
13414        final String installerPackageName;
13415        final String volumeUuid;
13416        final UserHandle user;
13417        final String abiOverride;
13418        final String[] installGrantPermissions;
13419        /** If non-null, drop an async trace when the install completes */
13420        final String traceMethod;
13421        final int traceCookie;
13422        final Certificate[][] certificates;
13423
13424        // The list of instruction sets supported by this app. This is currently
13425        // only used during the rmdex() phase to clean up resources. We can get rid of this
13426        // if we move dex files under the common app path.
13427        /* nullable */ String[] instructionSets;
13428
13429        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13430                int installFlags, String installerPackageName, String volumeUuid,
13431                UserHandle user, String[] instructionSets,
13432                String abiOverride, String[] installGrantPermissions,
13433                String traceMethod, int traceCookie, Certificate[][] certificates) {
13434            this.origin = origin;
13435            this.move = move;
13436            this.installFlags = installFlags;
13437            this.observer = observer;
13438            this.installerPackageName = installerPackageName;
13439            this.volumeUuid = volumeUuid;
13440            this.user = user;
13441            this.instructionSets = instructionSets;
13442            this.abiOverride = abiOverride;
13443            this.installGrantPermissions = installGrantPermissions;
13444            this.traceMethod = traceMethod;
13445            this.traceCookie = traceCookie;
13446            this.certificates = certificates;
13447        }
13448
13449        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13450        abstract int doPreInstall(int status);
13451
13452        /**
13453         * Rename package into final resting place. All paths on the given
13454         * scanned package should be updated to reflect the rename.
13455         */
13456        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13457        abstract int doPostInstall(int status, int uid);
13458
13459        /** @see PackageSettingBase#codePathString */
13460        abstract String getCodePath();
13461        /** @see PackageSettingBase#resourcePathString */
13462        abstract String getResourcePath();
13463
13464        // Need installer lock especially for dex file removal.
13465        abstract void cleanUpResourcesLI();
13466        abstract boolean doPostDeleteLI(boolean delete);
13467
13468        /**
13469         * Called before the source arguments are copied. This is used mostly
13470         * for MoveParams when it needs to read the source file to put it in the
13471         * destination.
13472         */
13473        int doPreCopy() {
13474            return PackageManager.INSTALL_SUCCEEDED;
13475        }
13476
13477        /**
13478         * Called after the source arguments are copied. This is used mostly for
13479         * MoveParams when it needs to read the source file to put it in the
13480         * destination.
13481         */
13482        int doPostCopy(int uid) {
13483            return PackageManager.INSTALL_SUCCEEDED;
13484        }
13485
13486        protected boolean isFwdLocked() {
13487            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13488        }
13489
13490        protected boolean isExternalAsec() {
13491            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13492        }
13493
13494        protected boolean isEphemeral() {
13495            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13496        }
13497
13498        UserHandle getUser() {
13499            return user;
13500        }
13501    }
13502
13503    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13504        if (!allCodePaths.isEmpty()) {
13505            if (instructionSets == null) {
13506                throw new IllegalStateException("instructionSet == null");
13507            }
13508            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13509            for (String codePath : allCodePaths) {
13510                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13511                    try {
13512                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13513                    } catch (InstallerException ignored) {
13514                    }
13515                }
13516            }
13517        }
13518    }
13519
13520    /**
13521     * Logic to handle installation of non-ASEC applications, including copying
13522     * and renaming logic.
13523     */
13524    class FileInstallArgs extends InstallArgs {
13525        private File codeFile;
13526        private File resourceFile;
13527
13528        // Example topology:
13529        // /data/app/com.example/base.apk
13530        // /data/app/com.example/split_foo.apk
13531        // /data/app/com.example/lib/arm/libfoo.so
13532        // /data/app/com.example/lib/arm64/libfoo.so
13533        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13534
13535        /** New install */
13536        FileInstallArgs(InstallParams params) {
13537            super(params.origin, params.move, params.observer, params.installFlags,
13538                    params.installerPackageName, params.volumeUuid,
13539                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13540                    params.grantedRuntimePermissions,
13541                    params.traceMethod, params.traceCookie, params.certificates);
13542            if (isFwdLocked()) {
13543                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13544            }
13545        }
13546
13547        /** Existing install */
13548        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13549            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13550                    null, null, null, 0, null /*certificates*/);
13551            this.codeFile = (codePath != null) ? new File(codePath) : null;
13552            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13553        }
13554
13555        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13556            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13557            try {
13558                return doCopyApk(imcs, temp);
13559            } finally {
13560                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13561            }
13562        }
13563
13564        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13565            if (origin.staged) {
13566                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13567                codeFile = origin.file;
13568                resourceFile = origin.file;
13569                return PackageManager.INSTALL_SUCCEEDED;
13570            }
13571
13572            try {
13573                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13574                final File tempDir =
13575                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13576                codeFile = tempDir;
13577                resourceFile = tempDir;
13578            } catch (IOException e) {
13579                Slog.w(TAG, "Failed to create copy file: " + e);
13580                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13581            }
13582
13583            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13584                @Override
13585                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13586                    if (!FileUtils.isValidExtFilename(name)) {
13587                        throw new IllegalArgumentException("Invalid filename: " + name);
13588                    }
13589                    try {
13590                        final File file = new File(codeFile, name);
13591                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13592                                O_RDWR | O_CREAT, 0644);
13593                        Os.chmod(file.getAbsolutePath(), 0644);
13594                        return new ParcelFileDescriptor(fd);
13595                    } catch (ErrnoException e) {
13596                        throw new RemoteException("Failed to open: " + e.getMessage());
13597                    }
13598                }
13599            };
13600
13601            int ret = PackageManager.INSTALL_SUCCEEDED;
13602            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13603            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13604                Slog.e(TAG, "Failed to copy package");
13605                return ret;
13606            }
13607
13608            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13609            NativeLibraryHelper.Handle handle = null;
13610            try {
13611                handle = NativeLibraryHelper.Handle.create(codeFile);
13612                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13613                        abiOverride);
13614            } catch (IOException e) {
13615                Slog.e(TAG, "Copying native libraries failed", e);
13616                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13617            } finally {
13618                IoUtils.closeQuietly(handle);
13619            }
13620
13621            return ret;
13622        }
13623
13624        int doPreInstall(int status) {
13625            if (status != PackageManager.INSTALL_SUCCEEDED) {
13626                cleanUp();
13627            }
13628            return status;
13629        }
13630
13631        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13632            if (status != PackageManager.INSTALL_SUCCEEDED) {
13633                cleanUp();
13634                return false;
13635            }
13636
13637            final File targetDir = codeFile.getParentFile();
13638            final File beforeCodeFile = codeFile;
13639            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13640
13641            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13642            try {
13643                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13644            } catch (ErrnoException e) {
13645                Slog.w(TAG, "Failed to rename", e);
13646                return false;
13647            }
13648
13649            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13650                Slog.w(TAG, "Failed to restorecon");
13651                return false;
13652            }
13653
13654            // Reflect the rename internally
13655            codeFile = afterCodeFile;
13656            resourceFile = afterCodeFile;
13657
13658            // Reflect the rename in scanned details
13659            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13660            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13661                    afterCodeFile, pkg.baseCodePath));
13662            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13663                    afterCodeFile, pkg.splitCodePaths));
13664
13665            // Reflect the rename in app info
13666            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13667            pkg.setApplicationInfoCodePath(pkg.codePath);
13668            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13669            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13670            pkg.setApplicationInfoResourcePath(pkg.codePath);
13671            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13672            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13673
13674            return true;
13675        }
13676
13677        int doPostInstall(int status, int uid) {
13678            if (status != PackageManager.INSTALL_SUCCEEDED) {
13679                cleanUp();
13680            }
13681            return status;
13682        }
13683
13684        @Override
13685        String getCodePath() {
13686            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13687        }
13688
13689        @Override
13690        String getResourcePath() {
13691            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13692        }
13693
13694        private boolean cleanUp() {
13695            if (codeFile == null || !codeFile.exists()) {
13696                return false;
13697            }
13698
13699            removeCodePathLI(codeFile);
13700
13701            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13702                resourceFile.delete();
13703            }
13704
13705            return true;
13706        }
13707
13708        void cleanUpResourcesLI() {
13709            // Try enumerating all code paths before deleting
13710            List<String> allCodePaths = Collections.EMPTY_LIST;
13711            if (codeFile != null && codeFile.exists()) {
13712                try {
13713                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13714                    allCodePaths = pkg.getAllCodePaths();
13715                } catch (PackageParserException e) {
13716                    // Ignored; we tried our best
13717                }
13718            }
13719
13720            cleanUp();
13721            removeDexFiles(allCodePaths, instructionSets);
13722        }
13723
13724        boolean doPostDeleteLI(boolean delete) {
13725            // XXX err, shouldn't we respect the delete flag?
13726            cleanUpResourcesLI();
13727            return true;
13728        }
13729    }
13730
13731    private boolean isAsecExternal(String cid) {
13732        final String asecPath = PackageHelper.getSdFilesystem(cid);
13733        return !asecPath.startsWith(mAsecInternalPath);
13734    }
13735
13736    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13737            PackageManagerException {
13738        if (copyRet < 0) {
13739            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13740                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13741                throw new PackageManagerException(copyRet, message);
13742            }
13743        }
13744    }
13745
13746    /**
13747     * Extract the MountService "container ID" from the full code path of an
13748     * .apk.
13749     */
13750    static String cidFromCodePath(String fullCodePath) {
13751        int eidx = fullCodePath.lastIndexOf("/");
13752        String subStr1 = fullCodePath.substring(0, eidx);
13753        int sidx = subStr1.lastIndexOf("/");
13754        return subStr1.substring(sidx+1, eidx);
13755    }
13756
13757    /**
13758     * Logic to handle installation of ASEC applications, including copying and
13759     * renaming logic.
13760     */
13761    class AsecInstallArgs extends InstallArgs {
13762        static final String RES_FILE_NAME = "pkg.apk";
13763        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13764
13765        String cid;
13766        String packagePath;
13767        String resourcePath;
13768
13769        /** New install */
13770        AsecInstallArgs(InstallParams params) {
13771            super(params.origin, params.move, params.observer, params.installFlags,
13772                    params.installerPackageName, params.volumeUuid,
13773                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13774                    params.grantedRuntimePermissions,
13775                    params.traceMethod, params.traceCookie, params.certificates);
13776        }
13777
13778        /** Existing install */
13779        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13780                        boolean isExternal, boolean isForwardLocked) {
13781            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13782              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13783                    instructionSets, null, null, null, 0, null /*certificates*/);
13784            // Hackily pretend we're still looking at a full code path
13785            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13786                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13787            }
13788
13789            // Extract cid from fullCodePath
13790            int eidx = fullCodePath.lastIndexOf("/");
13791            String subStr1 = fullCodePath.substring(0, eidx);
13792            int sidx = subStr1.lastIndexOf("/");
13793            cid = subStr1.substring(sidx+1, eidx);
13794            setMountPath(subStr1);
13795        }
13796
13797        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13798            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13799              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13800                    instructionSets, null, null, null, 0, null /*certificates*/);
13801            this.cid = cid;
13802            setMountPath(PackageHelper.getSdDir(cid));
13803        }
13804
13805        void createCopyFile() {
13806            cid = mInstallerService.allocateExternalStageCidLegacy();
13807        }
13808
13809        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13810            if (origin.staged && origin.cid != null) {
13811                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13812                cid = origin.cid;
13813                setMountPath(PackageHelper.getSdDir(cid));
13814                return PackageManager.INSTALL_SUCCEEDED;
13815            }
13816
13817            if (temp) {
13818                createCopyFile();
13819            } else {
13820                /*
13821                 * Pre-emptively destroy the container since it's destroyed if
13822                 * copying fails due to it existing anyway.
13823                 */
13824                PackageHelper.destroySdDir(cid);
13825            }
13826
13827            final String newMountPath = imcs.copyPackageToContainer(
13828                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13829                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13830
13831            if (newMountPath != null) {
13832                setMountPath(newMountPath);
13833                return PackageManager.INSTALL_SUCCEEDED;
13834            } else {
13835                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13836            }
13837        }
13838
13839        @Override
13840        String getCodePath() {
13841            return packagePath;
13842        }
13843
13844        @Override
13845        String getResourcePath() {
13846            return resourcePath;
13847        }
13848
13849        int doPreInstall(int status) {
13850            if (status != PackageManager.INSTALL_SUCCEEDED) {
13851                // Destroy container
13852                PackageHelper.destroySdDir(cid);
13853            } else {
13854                boolean mounted = PackageHelper.isContainerMounted(cid);
13855                if (!mounted) {
13856                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13857                            Process.SYSTEM_UID);
13858                    if (newMountPath != null) {
13859                        setMountPath(newMountPath);
13860                    } else {
13861                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13862                    }
13863                }
13864            }
13865            return status;
13866        }
13867
13868        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13869            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13870            String newMountPath = null;
13871            if (PackageHelper.isContainerMounted(cid)) {
13872                // Unmount the container
13873                if (!PackageHelper.unMountSdDir(cid)) {
13874                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13875                    return false;
13876                }
13877            }
13878            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13879                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13880                        " which might be stale. Will try to clean up.");
13881                // Clean up the stale container and proceed to recreate.
13882                if (!PackageHelper.destroySdDir(newCacheId)) {
13883                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13884                    return false;
13885                }
13886                // Successfully cleaned up stale container. Try to rename again.
13887                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13888                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13889                            + " inspite of cleaning it up.");
13890                    return false;
13891                }
13892            }
13893            if (!PackageHelper.isContainerMounted(newCacheId)) {
13894                Slog.w(TAG, "Mounting container " + newCacheId);
13895                newMountPath = PackageHelper.mountSdDir(newCacheId,
13896                        getEncryptKey(), Process.SYSTEM_UID);
13897            } else {
13898                newMountPath = PackageHelper.getSdDir(newCacheId);
13899            }
13900            if (newMountPath == null) {
13901                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13902                return false;
13903            }
13904            Log.i(TAG, "Succesfully renamed " + cid +
13905                    " to " + newCacheId +
13906                    " at new path: " + newMountPath);
13907            cid = newCacheId;
13908
13909            final File beforeCodeFile = new File(packagePath);
13910            setMountPath(newMountPath);
13911            final File afterCodeFile = new File(packagePath);
13912
13913            // Reflect the rename in scanned details
13914            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13915            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13916                    afterCodeFile, pkg.baseCodePath));
13917            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13918                    afterCodeFile, pkg.splitCodePaths));
13919
13920            // Reflect the rename in app info
13921            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13922            pkg.setApplicationInfoCodePath(pkg.codePath);
13923            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13924            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13925            pkg.setApplicationInfoResourcePath(pkg.codePath);
13926            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13927            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13928
13929            return true;
13930        }
13931
13932        private void setMountPath(String mountPath) {
13933            final File mountFile = new File(mountPath);
13934
13935            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13936            if (monolithicFile.exists()) {
13937                packagePath = monolithicFile.getAbsolutePath();
13938                if (isFwdLocked()) {
13939                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13940                } else {
13941                    resourcePath = packagePath;
13942                }
13943            } else {
13944                packagePath = mountFile.getAbsolutePath();
13945                resourcePath = packagePath;
13946            }
13947        }
13948
13949        int doPostInstall(int status, int uid) {
13950            if (status != PackageManager.INSTALL_SUCCEEDED) {
13951                cleanUp();
13952            } else {
13953                final int groupOwner;
13954                final String protectedFile;
13955                if (isFwdLocked()) {
13956                    groupOwner = UserHandle.getSharedAppGid(uid);
13957                    protectedFile = RES_FILE_NAME;
13958                } else {
13959                    groupOwner = -1;
13960                    protectedFile = null;
13961                }
13962
13963                if (uid < Process.FIRST_APPLICATION_UID
13964                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13965                    Slog.e(TAG, "Failed to finalize " + cid);
13966                    PackageHelper.destroySdDir(cid);
13967                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13968                }
13969
13970                boolean mounted = PackageHelper.isContainerMounted(cid);
13971                if (!mounted) {
13972                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13973                }
13974            }
13975            return status;
13976        }
13977
13978        private void cleanUp() {
13979            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13980
13981            // Destroy secure container
13982            PackageHelper.destroySdDir(cid);
13983        }
13984
13985        private List<String> getAllCodePaths() {
13986            final File codeFile = new File(getCodePath());
13987            if (codeFile != null && codeFile.exists()) {
13988                try {
13989                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13990                    return pkg.getAllCodePaths();
13991                } catch (PackageParserException e) {
13992                    // Ignored; we tried our best
13993                }
13994            }
13995            return Collections.EMPTY_LIST;
13996        }
13997
13998        void cleanUpResourcesLI() {
13999            // Enumerate all code paths before deleting
14000            cleanUpResourcesLI(getAllCodePaths());
14001        }
14002
14003        private void cleanUpResourcesLI(List<String> allCodePaths) {
14004            cleanUp();
14005            removeDexFiles(allCodePaths, instructionSets);
14006        }
14007
14008        String getPackageName() {
14009            return getAsecPackageName(cid);
14010        }
14011
14012        boolean doPostDeleteLI(boolean delete) {
14013            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14014            final List<String> allCodePaths = getAllCodePaths();
14015            boolean mounted = PackageHelper.isContainerMounted(cid);
14016            if (mounted) {
14017                // Unmount first
14018                if (PackageHelper.unMountSdDir(cid)) {
14019                    mounted = false;
14020                }
14021            }
14022            if (!mounted && delete) {
14023                cleanUpResourcesLI(allCodePaths);
14024            }
14025            return !mounted;
14026        }
14027
14028        @Override
14029        int doPreCopy() {
14030            if (isFwdLocked()) {
14031                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14032                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14033                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14034                }
14035            }
14036
14037            return PackageManager.INSTALL_SUCCEEDED;
14038        }
14039
14040        @Override
14041        int doPostCopy(int uid) {
14042            if (isFwdLocked()) {
14043                if (uid < Process.FIRST_APPLICATION_UID
14044                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14045                                RES_FILE_NAME)) {
14046                    Slog.e(TAG, "Failed to finalize " + cid);
14047                    PackageHelper.destroySdDir(cid);
14048                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14049                }
14050            }
14051
14052            return PackageManager.INSTALL_SUCCEEDED;
14053        }
14054    }
14055
14056    /**
14057     * Logic to handle movement of existing installed applications.
14058     */
14059    class MoveInstallArgs extends InstallArgs {
14060        private File codeFile;
14061        private File resourceFile;
14062
14063        /** New install */
14064        MoveInstallArgs(InstallParams params) {
14065            super(params.origin, params.move, params.observer, params.installFlags,
14066                    params.installerPackageName, params.volumeUuid,
14067                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14068                    params.grantedRuntimePermissions,
14069                    params.traceMethod, params.traceCookie, params.certificates);
14070        }
14071
14072        int copyApk(IMediaContainerService imcs, boolean temp) {
14073            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14074                    + move.fromUuid + " to " + move.toUuid);
14075            synchronized (mInstaller) {
14076                try {
14077                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14078                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14079                } catch (InstallerException e) {
14080                    Slog.w(TAG, "Failed to move app", e);
14081                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14082                }
14083            }
14084
14085            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14086            resourceFile = codeFile;
14087            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14088
14089            return PackageManager.INSTALL_SUCCEEDED;
14090        }
14091
14092        int doPreInstall(int status) {
14093            if (status != PackageManager.INSTALL_SUCCEEDED) {
14094                cleanUp(move.toUuid);
14095            }
14096            return status;
14097        }
14098
14099        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14100            if (status != PackageManager.INSTALL_SUCCEEDED) {
14101                cleanUp(move.toUuid);
14102                return false;
14103            }
14104
14105            // Reflect the move in app info
14106            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14107            pkg.setApplicationInfoCodePath(pkg.codePath);
14108            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14109            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14110            pkg.setApplicationInfoResourcePath(pkg.codePath);
14111            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14112            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14113
14114            return true;
14115        }
14116
14117        int doPostInstall(int status, int uid) {
14118            if (status == PackageManager.INSTALL_SUCCEEDED) {
14119                cleanUp(move.fromUuid);
14120            } else {
14121                cleanUp(move.toUuid);
14122            }
14123            return status;
14124        }
14125
14126        @Override
14127        String getCodePath() {
14128            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14129        }
14130
14131        @Override
14132        String getResourcePath() {
14133            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14134        }
14135
14136        private boolean cleanUp(String volumeUuid) {
14137            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14138                    move.dataAppName);
14139            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14140            final int[] userIds = sUserManager.getUserIds();
14141            synchronized (mInstallLock) {
14142                // Clean up both app data and code
14143                // All package moves are frozen until finished
14144                for (int userId : userIds) {
14145                    try {
14146                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14147                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14148                    } catch (InstallerException e) {
14149                        Slog.w(TAG, String.valueOf(e));
14150                    }
14151                }
14152                removeCodePathLI(codeFile);
14153            }
14154            return true;
14155        }
14156
14157        void cleanUpResourcesLI() {
14158            throw new UnsupportedOperationException();
14159        }
14160
14161        boolean doPostDeleteLI(boolean delete) {
14162            throw new UnsupportedOperationException();
14163        }
14164    }
14165
14166    static String getAsecPackageName(String packageCid) {
14167        int idx = packageCid.lastIndexOf("-");
14168        if (idx == -1) {
14169            return packageCid;
14170        }
14171        return packageCid.substring(0, idx);
14172    }
14173
14174    // Utility method used to create code paths based on package name and available index.
14175    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14176        String idxStr = "";
14177        int idx = 1;
14178        // Fall back to default value of idx=1 if prefix is not
14179        // part of oldCodePath
14180        if (oldCodePath != null) {
14181            String subStr = oldCodePath;
14182            // Drop the suffix right away
14183            if (suffix != null && subStr.endsWith(suffix)) {
14184                subStr = subStr.substring(0, subStr.length() - suffix.length());
14185            }
14186            // If oldCodePath already contains prefix find out the
14187            // ending index to either increment or decrement.
14188            int sidx = subStr.lastIndexOf(prefix);
14189            if (sidx != -1) {
14190                subStr = subStr.substring(sidx + prefix.length());
14191                if (subStr != null) {
14192                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14193                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14194                    }
14195                    try {
14196                        idx = Integer.parseInt(subStr);
14197                        if (idx <= 1) {
14198                            idx++;
14199                        } else {
14200                            idx--;
14201                        }
14202                    } catch(NumberFormatException e) {
14203                    }
14204                }
14205            }
14206        }
14207        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14208        return prefix + idxStr;
14209    }
14210
14211    private File getNextCodePath(File targetDir, String packageName) {
14212        int suffix = 1;
14213        File result;
14214        do {
14215            result = new File(targetDir, packageName + "-" + suffix);
14216            suffix++;
14217        } while (result.exists());
14218        return result;
14219    }
14220
14221    // Utility method that returns the relative package path with respect
14222    // to the installation directory. Like say for /data/data/com.test-1.apk
14223    // string com.test-1 is returned.
14224    static String deriveCodePathName(String codePath) {
14225        if (codePath == null) {
14226            return null;
14227        }
14228        final File codeFile = new File(codePath);
14229        final String name = codeFile.getName();
14230        if (codeFile.isDirectory()) {
14231            return name;
14232        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14233            final int lastDot = name.lastIndexOf('.');
14234            return name.substring(0, lastDot);
14235        } else {
14236            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14237            return null;
14238        }
14239    }
14240
14241    static class PackageInstalledInfo {
14242        String name;
14243        int uid;
14244        // The set of users that originally had this package installed.
14245        int[] origUsers;
14246        // The set of users that now have this package installed.
14247        int[] newUsers;
14248        PackageParser.Package pkg;
14249        int returnCode;
14250        String returnMsg;
14251        PackageRemovedInfo removedInfo;
14252        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14253
14254        public void setError(int code, String msg) {
14255            setReturnCode(code);
14256            setReturnMessage(msg);
14257            Slog.w(TAG, msg);
14258        }
14259
14260        public void setError(String msg, PackageParserException e) {
14261            setReturnCode(e.error);
14262            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14263            Slog.w(TAG, msg, e);
14264        }
14265
14266        public void setError(String msg, PackageManagerException e) {
14267            returnCode = e.error;
14268            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14269            Slog.w(TAG, msg, e);
14270        }
14271
14272        public void setReturnCode(int returnCode) {
14273            this.returnCode = returnCode;
14274            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14275            for (int i = 0; i < childCount; i++) {
14276                addedChildPackages.valueAt(i).returnCode = returnCode;
14277            }
14278        }
14279
14280        private void setReturnMessage(String returnMsg) {
14281            this.returnMsg = returnMsg;
14282            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14283            for (int i = 0; i < childCount; i++) {
14284                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14285            }
14286        }
14287
14288        // In some error cases we want to convey more info back to the observer
14289        String origPackage;
14290        String origPermission;
14291    }
14292
14293    /*
14294     * Install a non-existing package.
14295     */
14296    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14297            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14298            PackageInstalledInfo res) {
14299        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14300
14301        // Remember this for later, in case we need to rollback this install
14302        String pkgName = pkg.packageName;
14303
14304        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14305
14306        synchronized(mPackages) {
14307            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14308            if (renamedPackage != null) {
14309                // A package with the same name is already installed, though
14310                // it has been renamed to an older name.  The package we
14311                // are trying to install should be installed as an update to
14312                // the existing one, but that has not been requested, so bail.
14313                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14314                        + " without first uninstalling package running as "
14315                        + renamedPackage);
14316                return;
14317            }
14318            if (mPackages.containsKey(pkgName)) {
14319                // Don't allow installation over an existing package with the same name.
14320                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14321                        + " without first uninstalling.");
14322                return;
14323            }
14324        }
14325
14326        try {
14327            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14328                    System.currentTimeMillis(), user);
14329
14330            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14331
14332            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14333                prepareAppDataAfterInstallLIF(newPackage);
14334
14335            } else {
14336                // Remove package from internal structures, but keep around any
14337                // data that might have already existed
14338                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14339                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14340            }
14341        } catch (PackageManagerException e) {
14342            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14343        }
14344
14345        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14346    }
14347
14348    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14349        // Can't rotate keys during boot or if sharedUser.
14350        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14351                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14352            return false;
14353        }
14354        // app is using upgradeKeySets; make sure all are valid
14355        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14356        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14357        for (int i = 0; i < upgradeKeySets.length; i++) {
14358            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14359                Slog.wtf(TAG, "Package "
14360                         + (oldPs.name != null ? oldPs.name : "<null>")
14361                         + " contains upgrade-key-set reference to unknown key-set: "
14362                         + upgradeKeySets[i]
14363                         + " reverting to signatures check.");
14364                return false;
14365            }
14366        }
14367        return true;
14368    }
14369
14370    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14371        // Upgrade keysets are being used.  Determine if new package has a superset of the
14372        // required keys.
14373        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14374        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14375        for (int i = 0; i < upgradeKeySets.length; i++) {
14376            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14377            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14378                return true;
14379            }
14380        }
14381        return false;
14382    }
14383
14384    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14385        try (DigestInputStream digestStream =
14386                new DigestInputStream(new FileInputStream(file), digest)) {
14387            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14388        }
14389    }
14390
14391    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14392            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14393        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14394
14395        final PackageParser.Package oldPackage;
14396        final String pkgName = pkg.packageName;
14397        final int[] allUsers;
14398        final int[] installedUsers;
14399
14400        synchronized(mPackages) {
14401            oldPackage = mPackages.get(pkgName);
14402            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14403
14404            // don't allow upgrade to target a release SDK from a pre-release SDK
14405            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14406                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14407            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14408                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14409            if (oldTargetsPreRelease
14410                    && !newTargetsPreRelease
14411                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14412                Slog.w(TAG, "Can't install package targeting released sdk");
14413                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14414                return;
14415            }
14416
14417            // don't allow an upgrade from full to ephemeral
14418            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14419            if (isEphemeral && !oldIsEphemeral) {
14420                // can't downgrade from full to ephemeral
14421                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14422                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14423                return;
14424            }
14425
14426            // verify signatures are valid
14427            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14428            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14429                if (!checkUpgradeKeySetLP(ps, pkg)) {
14430                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14431                            "New package not signed by keys specified by upgrade-keysets: "
14432                                    + pkgName);
14433                    return;
14434                }
14435            } else {
14436                // default to original signature matching
14437                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14438                        != PackageManager.SIGNATURE_MATCH) {
14439                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14440                            "New package has a different signature: " + pkgName);
14441                    return;
14442                }
14443            }
14444
14445            // don't allow a system upgrade unless the upgrade hash matches
14446            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14447                byte[] digestBytes = null;
14448                try {
14449                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14450                    updateDigest(digest, new File(pkg.baseCodePath));
14451                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14452                        for (String path : pkg.splitCodePaths) {
14453                            updateDigest(digest, new File(path));
14454                        }
14455                    }
14456                    digestBytes = digest.digest();
14457                } catch (NoSuchAlgorithmException | IOException e) {
14458                    res.setError(INSTALL_FAILED_INVALID_APK,
14459                            "Could not compute hash: " + pkgName);
14460                    return;
14461                }
14462                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14463                    res.setError(INSTALL_FAILED_INVALID_APK,
14464                            "New package fails restrict-update check: " + pkgName);
14465                    return;
14466                }
14467                // retain upgrade restriction
14468                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14469            }
14470
14471            // Check for shared user id changes
14472            String invalidPackageName =
14473                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14474            if (invalidPackageName != null) {
14475                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14476                        "Package " + invalidPackageName + " tried to change user "
14477                                + oldPackage.mSharedUserId);
14478                return;
14479            }
14480
14481            // In case of rollback, remember per-user/profile install state
14482            allUsers = sUserManager.getUserIds();
14483            installedUsers = ps.queryInstalledUsers(allUsers, true);
14484        }
14485
14486        // Update what is removed
14487        res.removedInfo = new PackageRemovedInfo();
14488        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14489        res.removedInfo.removedPackage = oldPackage.packageName;
14490        res.removedInfo.isUpdate = true;
14491        res.removedInfo.origUsers = installedUsers;
14492        final int childCount = (oldPackage.childPackages != null)
14493                ? oldPackage.childPackages.size() : 0;
14494        for (int i = 0; i < childCount; i++) {
14495            boolean childPackageUpdated = false;
14496            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14497            if (res.addedChildPackages != null) {
14498                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14499                if (childRes != null) {
14500                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14501                    childRes.removedInfo.removedPackage = childPkg.packageName;
14502                    childRes.removedInfo.isUpdate = true;
14503                    childPackageUpdated = true;
14504                }
14505            }
14506            if (!childPackageUpdated) {
14507                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14508                childRemovedRes.removedPackage = childPkg.packageName;
14509                childRemovedRes.isUpdate = false;
14510                childRemovedRes.dataRemoved = true;
14511                synchronized (mPackages) {
14512                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14513                    if (childPs != null) {
14514                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14515                    }
14516                }
14517                if (res.removedInfo.removedChildPackages == null) {
14518                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14519                }
14520                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14521            }
14522        }
14523
14524        boolean sysPkg = (isSystemApp(oldPackage));
14525        if (sysPkg) {
14526            // Set the system/privileged flags as needed
14527            final boolean privileged =
14528                    (oldPackage.applicationInfo.privateFlags
14529                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14530            final int systemPolicyFlags = policyFlags
14531                    | PackageParser.PARSE_IS_SYSTEM
14532                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14533
14534            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14535                    user, allUsers, installerPackageName, res);
14536        } else {
14537            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14538                    user, allUsers, installerPackageName, res);
14539        }
14540    }
14541
14542    public List<String> getPreviousCodePaths(String packageName) {
14543        final PackageSetting ps = mSettings.mPackages.get(packageName);
14544        final List<String> result = new ArrayList<String>();
14545        if (ps != null && ps.oldCodePaths != null) {
14546            result.addAll(ps.oldCodePaths);
14547        }
14548        return result;
14549    }
14550
14551    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14552            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14553            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14554        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14555                + deletedPackage);
14556
14557        String pkgName = deletedPackage.packageName;
14558        boolean deletedPkg = true;
14559        boolean addedPkg = false;
14560        boolean updatedSettings = false;
14561        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14562        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14563                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14564
14565        final long origUpdateTime = (pkg.mExtras != null)
14566                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14567
14568        // First delete the existing package while retaining the data directory
14569        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14570                res.removedInfo, true, pkg)) {
14571            // If the existing package wasn't successfully deleted
14572            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14573            deletedPkg = false;
14574        } else {
14575            // Successfully deleted the old package; proceed with replace.
14576
14577            // If deleted package lived in a container, give users a chance to
14578            // relinquish resources before killing.
14579            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14580                if (DEBUG_INSTALL) {
14581                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14582                }
14583                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14584                final ArrayList<String> pkgList = new ArrayList<String>(1);
14585                pkgList.add(deletedPackage.applicationInfo.packageName);
14586                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14587            }
14588
14589            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14590                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14591            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14592
14593            try {
14594                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14595                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14596                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14597
14598                // Update the in-memory copy of the previous code paths.
14599                PackageSetting ps = mSettings.mPackages.get(pkgName);
14600                if (!killApp) {
14601                    if (ps.oldCodePaths == null) {
14602                        ps.oldCodePaths = new ArraySet<>();
14603                    }
14604                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14605                    if (deletedPackage.splitCodePaths != null) {
14606                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14607                    }
14608                } else {
14609                    ps.oldCodePaths = null;
14610                }
14611                if (ps.childPackageNames != null) {
14612                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14613                        final String childPkgName = ps.childPackageNames.get(i);
14614                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14615                        childPs.oldCodePaths = ps.oldCodePaths;
14616                    }
14617                }
14618                prepareAppDataAfterInstallLIF(newPackage);
14619                addedPkg = true;
14620            } catch (PackageManagerException e) {
14621                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14622            }
14623        }
14624
14625        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14626            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14627
14628            // Revert all internal state mutations and added folders for the failed install
14629            if (addedPkg) {
14630                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14631                        res.removedInfo, true, null);
14632            }
14633
14634            // Restore the old package
14635            if (deletedPkg) {
14636                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14637                File restoreFile = new File(deletedPackage.codePath);
14638                // Parse old package
14639                boolean oldExternal = isExternal(deletedPackage);
14640                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14641                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14642                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14643                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14644                try {
14645                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14646                            null);
14647                } catch (PackageManagerException e) {
14648                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14649                            + e.getMessage());
14650                    return;
14651                }
14652
14653                synchronized (mPackages) {
14654                    // Ensure the installer package name up to date
14655                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14656
14657                    // Update permissions for restored package
14658                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14659
14660                    mSettings.writeLPr();
14661                }
14662
14663                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14664            }
14665        } else {
14666            synchronized (mPackages) {
14667                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14668                if (ps != null) {
14669                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14670                    if (res.removedInfo.removedChildPackages != null) {
14671                        final int childCount = res.removedInfo.removedChildPackages.size();
14672                        // Iterate in reverse as we may modify the collection
14673                        for (int i = childCount - 1; i >= 0; i--) {
14674                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14675                            if (res.addedChildPackages.containsKey(childPackageName)) {
14676                                res.removedInfo.removedChildPackages.removeAt(i);
14677                            } else {
14678                                PackageRemovedInfo childInfo = res.removedInfo
14679                                        .removedChildPackages.valueAt(i);
14680                                childInfo.removedForAllUsers = mPackages.get(
14681                                        childInfo.removedPackage) == null;
14682                            }
14683                        }
14684                    }
14685                }
14686            }
14687        }
14688    }
14689
14690    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14691            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14692            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14693        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14694                + ", old=" + deletedPackage);
14695
14696        final boolean disabledSystem;
14697
14698        // Remove existing system package
14699        removePackageLI(deletedPackage, true);
14700
14701        synchronized (mPackages) {
14702            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14703        }
14704        if (!disabledSystem) {
14705            // We didn't need to disable the .apk as a current system package,
14706            // which means we are replacing another update that is already
14707            // installed.  We need to make sure to delete the older one's .apk.
14708            res.removedInfo.args = createInstallArgsForExisting(0,
14709                    deletedPackage.applicationInfo.getCodePath(),
14710                    deletedPackage.applicationInfo.getResourcePath(),
14711                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14712        } else {
14713            res.removedInfo.args = null;
14714        }
14715
14716        // Successfully disabled the old package. Now proceed with re-installation
14717        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14718                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14719        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14720
14721        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14722        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14723                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14724
14725        PackageParser.Package newPackage = null;
14726        try {
14727            // Add the package to the internal data structures
14728            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14729
14730            // Set the update and install times
14731            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14732            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14733                    System.currentTimeMillis());
14734
14735            // Update the package dynamic state if succeeded
14736            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14737                // Now that the install succeeded make sure we remove data
14738                // directories for any child package the update removed.
14739                final int deletedChildCount = (deletedPackage.childPackages != null)
14740                        ? deletedPackage.childPackages.size() : 0;
14741                final int newChildCount = (newPackage.childPackages != null)
14742                        ? newPackage.childPackages.size() : 0;
14743                for (int i = 0; i < deletedChildCount; i++) {
14744                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14745                    boolean childPackageDeleted = true;
14746                    for (int j = 0; j < newChildCount; j++) {
14747                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14748                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14749                            childPackageDeleted = false;
14750                            break;
14751                        }
14752                    }
14753                    if (childPackageDeleted) {
14754                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14755                                deletedChildPkg.packageName);
14756                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14757                            PackageRemovedInfo removedChildRes = res.removedInfo
14758                                    .removedChildPackages.get(deletedChildPkg.packageName);
14759                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14760                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14761                        }
14762                    }
14763                }
14764
14765                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14766                prepareAppDataAfterInstallLIF(newPackage);
14767            }
14768        } catch (PackageManagerException e) {
14769            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14770            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14771        }
14772
14773        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14774            // Re installation failed. Restore old information
14775            // Remove new pkg information
14776            if (newPackage != null) {
14777                removeInstalledPackageLI(newPackage, true);
14778            }
14779            // Add back the old system package
14780            try {
14781                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14782            } catch (PackageManagerException e) {
14783                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14784            }
14785
14786            synchronized (mPackages) {
14787                if (disabledSystem) {
14788                    enableSystemPackageLPw(deletedPackage);
14789                }
14790
14791                // Ensure the installer package name up to date
14792                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14793
14794                // Update permissions for restored package
14795                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14796
14797                mSettings.writeLPr();
14798            }
14799
14800            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14801                    + " after failed upgrade");
14802        }
14803    }
14804
14805    /**
14806     * Checks whether the parent or any of the child packages have a change shared
14807     * user. For a package to be a valid update the shred users of the parent and
14808     * the children should match. We may later support changing child shared users.
14809     * @param oldPkg The updated package.
14810     * @param newPkg The update package.
14811     * @return The shared user that change between the versions.
14812     */
14813    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14814            PackageParser.Package newPkg) {
14815        // Check parent shared user
14816        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14817            return newPkg.packageName;
14818        }
14819        // Check child shared users
14820        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14821        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14822        for (int i = 0; i < newChildCount; i++) {
14823            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14824            // If this child was present, did it have the same shared user?
14825            for (int j = 0; j < oldChildCount; j++) {
14826                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14827                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14828                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14829                    return newChildPkg.packageName;
14830                }
14831            }
14832        }
14833        return null;
14834    }
14835
14836    private void removeNativeBinariesLI(PackageSetting ps) {
14837        // Remove the lib path for the parent package
14838        if (ps != null) {
14839            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14840            // Remove the lib path for the child packages
14841            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14842            for (int i = 0; i < childCount; i++) {
14843                PackageSetting childPs = null;
14844                synchronized (mPackages) {
14845                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14846                }
14847                if (childPs != null) {
14848                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14849                            .legacyNativeLibraryPathString);
14850                }
14851            }
14852        }
14853    }
14854
14855    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14856        // Enable the parent package
14857        mSettings.enableSystemPackageLPw(pkg.packageName);
14858        // Enable the child packages
14859        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14860        for (int i = 0; i < childCount; i++) {
14861            PackageParser.Package childPkg = pkg.childPackages.get(i);
14862            mSettings.enableSystemPackageLPw(childPkg.packageName);
14863        }
14864    }
14865
14866    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14867            PackageParser.Package newPkg) {
14868        // Disable the parent package (parent always replaced)
14869        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14870        // Disable the child packages
14871        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14872        for (int i = 0; i < childCount; i++) {
14873            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14874            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14875            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14876        }
14877        return disabled;
14878    }
14879
14880    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14881            String installerPackageName) {
14882        // Enable the parent package
14883        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14884        // Enable the child packages
14885        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14886        for (int i = 0; i < childCount; i++) {
14887            PackageParser.Package childPkg = pkg.childPackages.get(i);
14888            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14889        }
14890    }
14891
14892    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14893        // Collect all used permissions in the UID
14894        ArraySet<String> usedPermissions = new ArraySet<>();
14895        final int packageCount = su.packages.size();
14896        for (int i = 0; i < packageCount; i++) {
14897            PackageSetting ps = su.packages.valueAt(i);
14898            if (ps.pkg == null) {
14899                continue;
14900            }
14901            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14902            for (int j = 0; j < requestedPermCount; j++) {
14903                String permission = ps.pkg.requestedPermissions.get(j);
14904                BasePermission bp = mSettings.mPermissions.get(permission);
14905                if (bp != null) {
14906                    usedPermissions.add(permission);
14907                }
14908            }
14909        }
14910
14911        PermissionsState permissionsState = su.getPermissionsState();
14912        // Prune install permissions
14913        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14914        final int installPermCount = installPermStates.size();
14915        for (int i = installPermCount - 1; i >= 0;  i--) {
14916            PermissionState permissionState = installPermStates.get(i);
14917            if (!usedPermissions.contains(permissionState.getName())) {
14918                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14919                if (bp != null) {
14920                    permissionsState.revokeInstallPermission(bp);
14921                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14922                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14923                }
14924            }
14925        }
14926
14927        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14928
14929        // Prune runtime permissions
14930        for (int userId : allUserIds) {
14931            List<PermissionState> runtimePermStates = permissionsState
14932                    .getRuntimePermissionStates(userId);
14933            final int runtimePermCount = runtimePermStates.size();
14934            for (int i = runtimePermCount - 1; i >= 0; i--) {
14935                PermissionState permissionState = runtimePermStates.get(i);
14936                if (!usedPermissions.contains(permissionState.getName())) {
14937                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14938                    if (bp != null) {
14939                        permissionsState.revokeRuntimePermission(bp, userId);
14940                        permissionsState.updatePermissionFlags(bp, userId,
14941                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14942                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14943                                runtimePermissionChangedUserIds, userId);
14944                    }
14945                }
14946            }
14947        }
14948
14949        return runtimePermissionChangedUserIds;
14950    }
14951
14952    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14953            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14954        // Update the parent package setting
14955        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14956                res, user);
14957        // Update the child packages setting
14958        final int childCount = (newPackage.childPackages != null)
14959                ? newPackage.childPackages.size() : 0;
14960        for (int i = 0; i < childCount; i++) {
14961            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14962            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14963            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14964                    childRes.origUsers, childRes, user);
14965        }
14966    }
14967
14968    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14969            String installerPackageName, int[] allUsers, int[] installedForUsers,
14970            PackageInstalledInfo res, UserHandle user) {
14971        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14972
14973        String pkgName = newPackage.packageName;
14974        synchronized (mPackages) {
14975            //write settings. the installStatus will be incomplete at this stage.
14976            //note that the new package setting would have already been
14977            //added to mPackages. It hasn't been persisted yet.
14978            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14979            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14980            mSettings.writeLPr();
14981            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14982        }
14983
14984        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14985        synchronized (mPackages) {
14986            updatePermissionsLPw(newPackage.packageName, newPackage,
14987                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14988                            ? UPDATE_PERMISSIONS_ALL : 0));
14989            // For system-bundled packages, we assume that installing an upgraded version
14990            // of the package implies that the user actually wants to run that new code,
14991            // so we enable the package.
14992            PackageSetting ps = mSettings.mPackages.get(pkgName);
14993            final int userId = user.getIdentifier();
14994            if (ps != null) {
14995                if (isSystemApp(newPackage)) {
14996                    if (DEBUG_INSTALL) {
14997                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14998                    }
14999                    // Enable system package for requested users
15000                    if (res.origUsers != null) {
15001                        for (int origUserId : res.origUsers) {
15002                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15003                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15004                                        origUserId, installerPackageName);
15005                            }
15006                        }
15007                    }
15008                    // Also convey the prior install/uninstall state
15009                    if (allUsers != null && installedForUsers != null) {
15010                        for (int currentUserId : allUsers) {
15011                            final boolean installed = ArrayUtils.contains(
15012                                    installedForUsers, currentUserId);
15013                            if (DEBUG_INSTALL) {
15014                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15015                            }
15016                            ps.setInstalled(installed, currentUserId);
15017                        }
15018                        // these install state changes will be persisted in the
15019                        // upcoming call to mSettings.writeLPr().
15020                    }
15021                }
15022                // It's implied that when a user requests installation, they want the app to be
15023                // installed and enabled.
15024                if (userId != UserHandle.USER_ALL) {
15025                    ps.setInstalled(true, userId);
15026                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15027                }
15028            }
15029            res.name = pkgName;
15030            res.uid = newPackage.applicationInfo.uid;
15031            res.pkg = newPackage;
15032            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15033            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15034            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15035            //to update install status
15036            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15037            mSettings.writeLPr();
15038            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15039        }
15040
15041        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15042    }
15043
15044    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15045        try {
15046            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15047            installPackageLI(args, res);
15048        } finally {
15049            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15050        }
15051    }
15052
15053    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15054        final int installFlags = args.installFlags;
15055        final String installerPackageName = args.installerPackageName;
15056        final String volumeUuid = args.volumeUuid;
15057        final File tmpPackageFile = new File(args.getCodePath());
15058        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15059        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15060                || (args.volumeUuid != null));
15061        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15062        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15063        boolean replace = false;
15064        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15065        if (args.move != null) {
15066            // moving a complete application; perform an initial scan on the new install location
15067            scanFlags |= SCAN_INITIAL;
15068        }
15069        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15070            scanFlags |= SCAN_DONT_KILL_APP;
15071        }
15072
15073        // Result object to be returned
15074        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15075
15076        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15077
15078        // Sanity check
15079        if (ephemeral && (forwardLocked || onExternal)) {
15080            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15081                    + " external=" + onExternal);
15082            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15083            return;
15084        }
15085
15086        // Retrieve PackageSettings and parse package
15087        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15088                | PackageParser.PARSE_ENFORCE_CODE
15089                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15090                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15091                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15092                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15093        PackageParser pp = new PackageParser();
15094        pp.setSeparateProcesses(mSeparateProcesses);
15095        pp.setDisplayMetrics(mMetrics);
15096
15097        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15098        final PackageParser.Package pkg;
15099        try {
15100            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15101        } catch (PackageParserException e) {
15102            res.setError("Failed parse during installPackageLI", e);
15103            return;
15104        } finally {
15105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15106        }
15107
15108        // If we are installing a clustered package add results for the children
15109        if (pkg.childPackages != null) {
15110            synchronized (mPackages) {
15111                final int childCount = pkg.childPackages.size();
15112                for (int i = 0; i < childCount; i++) {
15113                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15114                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15115                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15116                    childRes.pkg = childPkg;
15117                    childRes.name = childPkg.packageName;
15118                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15119                    if (childPs != null) {
15120                        childRes.origUsers = childPs.queryInstalledUsers(
15121                                sUserManager.getUserIds(), true);
15122                    }
15123                    if ((mPackages.containsKey(childPkg.packageName))) {
15124                        childRes.removedInfo = new PackageRemovedInfo();
15125                        childRes.removedInfo.removedPackage = childPkg.packageName;
15126                    }
15127                    if (res.addedChildPackages == null) {
15128                        res.addedChildPackages = new ArrayMap<>();
15129                    }
15130                    res.addedChildPackages.put(childPkg.packageName, childRes);
15131                }
15132            }
15133        }
15134
15135        // If package doesn't declare API override, mark that we have an install
15136        // time CPU ABI override.
15137        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15138            pkg.cpuAbiOverride = args.abiOverride;
15139        }
15140
15141        String pkgName = res.name = pkg.packageName;
15142        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15143            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15144                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15145                return;
15146            }
15147        }
15148
15149        try {
15150            // either use what we've been given or parse directly from the APK
15151            if (args.certificates != null) {
15152                try {
15153                    PackageParser.populateCertificates(pkg, args.certificates);
15154                } catch (PackageParserException e) {
15155                    // there was something wrong with the certificates we were given;
15156                    // try to pull them from the APK
15157                    PackageParser.collectCertificates(pkg, parseFlags);
15158                }
15159            } else {
15160                PackageParser.collectCertificates(pkg, parseFlags);
15161            }
15162        } catch (PackageParserException e) {
15163            res.setError("Failed collect during installPackageLI", e);
15164            return;
15165        }
15166
15167        // Get rid of all references to package scan path via parser.
15168        pp = null;
15169        String oldCodePath = null;
15170        boolean systemApp = false;
15171        synchronized (mPackages) {
15172            // Check if installing already existing package
15173            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15174                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15175                if (pkg.mOriginalPackages != null
15176                        && pkg.mOriginalPackages.contains(oldName)
15177                        && mPackages.containsKey(oldName)) {
15178                    // This package is derived from an original package,
15179                    // and this device has been updating from that original
15180                    // name.  We must continue using the original name, so
15181                    // rename the new package here.
15182                    pkg.setPackageName(oldName);
15183                    pkgName = pkg.packageName;
15184                    replace = true;
15185                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15186                            + oldName + " pkgName=" + pkgName);
15187                } else if (mPackages.containsKey(pkgName)) {
15188                    // This package, under its official name, already exists
15189                    // on the device; we should replace it.
15190                    replace = true;
15191                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15192                }
15193
15194                // Child packages are installed through the parent package
15195                if (pkg.parentPackage != null) {
15196                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15197                            "Package " + pkg.packageName + " is child of package "
15198                                    + pkg.parentPackage.parentPackage + ". Child packages "
15199                                    + "can be updated only through the parent package.");
15200                    return;
15201                }
15202
15203                if (replace) {
15204                    // Prevent apps opting out from runtime permissions
15205                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15206                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15207                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15208                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15209                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15210                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15211                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15212                                        + " doesn't support runtime permissions but the old"
15213                                        + " target SDK " + oldTargetSdk + " does.");
15214                        return;
15215                    }
15216
15217                    // Prevent installing of child packages
15218                    if (oldPackage.parentPackage != null) {
15219                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15220                                "Package " + pkg.packageName + " is child of package "
15221                                        + oldPackage.parentPackage + ". Child packages "
15222                                        + "can be updated only through the parent package.");
15223                        return;
15224                    }
15225                }
15226            }
15227
15228            PackageSetting ps = mSettings.mPackages.get(pkgName);
15229            if (ps != null) {
15230                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15231
15232                // Quick sanity check that we're signed correctly if updating;
15233                // we'll check this again later when scanning, but we want to
15234                // bail early here before tripping over redefined permissions.
15235                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15236                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15237                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15238                                + pkg.packageName + " upgrade keys do not match the "
15239                                + "previously installed version");
15240                        return;
15241                    }
15242                } else {
15243                    try {
15244                        verifySignaturesLP(ps, pkg);
15245                    } catch (PackageManagerException e) {
15246                        res.setError(e.error, e.getMessage());
15247                        return;
15248                    }
15249                }
15250
15251                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15252                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15253                    systemApp = (ps.pkg.applicationInfo.flags &
15254                            ApplicationInfo.FLAG_SYSTEM) != 0;
15255                }
15256                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15257            }
15258
15259            // Check whether the newly-scanned package wants to define an already-defined perm
15260            int N = pkg.permissions.size();
15261            for (int i = N-1; i >= 0; i--) {
15262                PackageParser.Permission perm = pkg.permissions.get(i);
15263                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15264                if (bp != null) {
15265                    // If the defining package is signed with our cert, it's okay.  This
15266                    // also includes the "updating the same package" case, of course.
15267                    // "updating same package" could also involve key-rotation.
15268                    final boolean sigsOk;
15269                    if (bp.sourcePackage.equals(pkg.packageName)
15270                            && (bp.packageSetting instanceof PackageSetting)
15271                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15272                                    scanFlags))) {
15273                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15274                    } else {
15275                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15276                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15277                    }
15278                    if (!sigsOk) {
15279                        // If the owning package is the system itself, we log but allow
15280                        // install to proceed; we fail the install on all other permission
15281                        // redefinitions.
15282                        if (!bp.sourcePackage.equals("android")) {
15283                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15284                                    + pkg.packageName + " attempting to redeclare permission "
15285                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15286                            res.origPermission = perm.info.name;
15287                            res.origPackage = bp.sourcePackage;
15288                            return;
15289                        } else {
15290                            Slog.w(TAG, "Package " + pkg.packageName
15291                                    + " attempting to redeclare system permission "
15292                                    + perm.info.name + "; ignoring new declaration");
15293                            pkg.permissions.remove(i);
15294                        }
15295                    }
15296                }
15297            }
15298        }
15299
15300        if (systemApp) {
15301            if (onExternal) {
15302                // Abort update; system app can't be replaced with app on sdcard
15303                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15304                        "Cannot install updates to system apps on sdcard");
15305                return;
15306            } else if (ephemeral) {
15307                // Abort update; system app can't be replaced with an ephemeral app
15308                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15309                        "Cannot update a system app with an ephemeral app");
15310                return;
15311            }
15312        }
15313
15314        if (args.move != null) {
15315            // We did an in-place move, so dex is ready to roll
15316            scanFlags |= SCAN_NO_DEX;
15317            scanFlags |= SCAN_MOVE;
15318
15319            synchronized (mPackages) {
15320                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15321                if (ps == null) {
15322                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15323                            "Missing settings for moved package " + pkgName);
15324                }
15325
15326                // We moved the entire application as-is, so bring over the
15327                // previously derived ABI information.
15328                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15329                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15330            }
15331
15332        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15333            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15334            scanFlags |= SCAN_NO_DEX;
15335
15336            try {
15337                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15338                    args.abiOverride : pkg.cpuAbiOverride);
15339                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15340                        true /*extractLibs*/, mAppLib32InstallDir);
15341            } catch (PackageManagerException pme) {
15342                Slog.e(TAG, "Error deriving application ABI", pme);
15343                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15344                return;
15345            }
15346
15347            // Shared libraries for the package need to be updated.
15348            synchronized (mPackages) {
15349                try {
15350                    updateSharedLibrariesLPr(pkg, null);
15351                } catch (PackageManagerException e) {
15352                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15353                }
15354            }
15355            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15356            // Do not run PackageDexOptimizer through the local performDexOpt
15357            // method because `pkg` may not be in `mPackages` yet.
15358            //
15359            // Also, don't fail application installs if the dexopt step fails.
15360            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15361                    null /* instructionSets */, false /* checkProfiles */,
15362                    getCompilerFilterForReason(REASON_INSTALL),
15363                    getOrCreateCompilerPackageStats(pkg));
15364            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15365
15366            // Notify BackgroundDexOptService that the package has been changed.
15367            // If this is an update of a package which used to fail to compile,
15368            // BDOS will remove it from its blacklist.
15369            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15370        }
15371
15372        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15373            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15374            return;
15375        }
15376
15377        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15378
15379        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15380                "installPackageLI")) {
15381            if (replace) {
15382                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15383                        installerPackageName, res);
15384            } else {
15385                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15386                        args.user, installerPackageName, volumeUuid, res);
15387            }
15388        }
15389        synchronized (mPackages) {
15390            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15391            if (ps != null) {
15392                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15393            }
15394
15395            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15396            for (int i = 0; i < childCount; i++) {
15397                PackageParser.Package childPkg = pkg.childPackages.get(i);
15398                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15399                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15400                if (childPs != null) {
15401                    childRes.newUsers = childPs.queryInstalledUsers(
15402                            sUserManager.getUserIds(), true);
15403                }
15404            }
15405        }
15406    }
15407
15408    private void startIntentFilterVerifications(int userId, boolean replacing,
15409            PackageParser.Package pkg) {
15410        if (mIntentFilterVerifierComponent == null) {
15411            Slog.w(TAG, "No IntentFilter verification will not be done as "
15412                    + "there is no IntentFilterVerifier available!");
15413            return;
15414        }
15415
15416        final int verifierUid = getPackageUid(
15417                mIntentFilterVerifierComponent.getPackageName(),
15418                MATCH_DEBUG_TRIAGED_MISSING,
15419                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15420
15421        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15422        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15423        mHandler.sendMessage(msg);
15424
15425        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15426        for (int i = 0; i < childCount; i++) {
15427            PackageParser.Package childPkg = pkg.childPackages.get(i);
15428            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15429            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15430            mHandler.sendMessage(msg);
15431        }
15432    }
15433
15434    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15435            PackageParser.Package pkg) {
15436        int size = pkg.activities.size();
15437        if (size == 0) {
15438            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15439                    "No activity, so no need to verify any IntentFilter!");
15440            return;
15441        }
15442
15443        final boolean hasDomainURLs = hasDomainURLs(pkg);
15444        if (!hasDomainURLs) {
15445            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15446                    "No domain URLs, so no need to verify any IntentFilter!");
15447            return;
15448        }
15449
15450        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15451                + " if any IntentFilter from the " + size
15452                + " Activities needs verification ...");
15453
15454        int count = 0;
15455        final String packageName = pkg.packageName;
15456
15457        synchronized (mPackages) {
15458            // If this is a new install and we see that we've already run verification for this
15459            // package, we have nothing to do: it means the state was restored from backup.
15460            if (!replacing) {
15461                IntentFilterVerificationInfo ivi =
15462                        mSettings.getIntentFilterVerificationLPr(packageName);
15463                if (ivi != null) {
15464                    if (DEBUG_DOMAIN_VERIFICATION) {
15465                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15466                                + ivi.getStatusString());
15467                    }
15468                    return;
15469                }
15470            }
15471
15472            // If any filters need to be verified, then all need to be.
15473            boolean needToVerify = false;
15474            for (PackageParser.Activity a : pkg.activities) {
15475                for (ActivityIntentInfo filter : a.intents) {
15476                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15477                        if (DEBUG_DOMAIN_VERIFICATION) {
15478                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15479                        }
15480                        needToVerify = true;
15481                        break;
15482                    }
15483                }
15484            }
15485
15486            if (needToVerify) {
15487                final int verificationId = mIntentFilterVerificationToken++;
15488                for (PackageParser.Activity a : pkg.activities) {
15489                    for (ActivityIntentInfo filter : a.intents) {
15490                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15491                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15492                                    "Verification needed for IntentFilter:" + filter.toString());
15493                            mIntentFilterVerifier.addOneIntentFilterVerification(
15494                                    verifierUid, userId, verificationId, filter, packageName);
15495                            count++;
15496                        }
15497                    }
15498                }
15499            }
15500        }
15501
15502        if (count > 0) {
15503            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15504                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15505                    +  " for userId:" + userId);
15506            mIntentFilterVerifier.startVerifications(userId);
15507        } else {
15508            if (DEBUG_DOMAIN_VERIFICATION) {
15509                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15510            }
15511        }
15512    }
15513
15514    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15515        final ComponentName cn  = filter.activity.getComponentName();
15516        final String packageName = cn.getPackageName();
15517
15518        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15519                packageName);
15520        if (ivi == null) {
15521            return true;
15522        }
15523        int status = ivi.getStatus();
15524        switch (status) {
15525            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15526            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15527                return true;
15528
15529            default:
15530                // Nothing to do
15531                return false;
15532        }
15533    }
15534
15535    private static boolean isMultiArch(ApplicationInfo info) {
15536        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15537    }
15538
15539    private static boolean isExternal(PackageParser.Package pkg) {
15540        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15541    }
15542
15543    private static boolean isExternal(PackageSetting ps) {
15544        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15545    }
15546
15547    private static boolean isEphemeral(PackageParser.Package pkg) {
15548        return pkg.applicationInfo.isEphemeralApp();
15549    }
15550
15551    private static boolean isEphemeral(PackageSetting ps) {
15552        return ps.pkg != null && isEphemeral(ps.pkg);
15553    }
15554
15555    private static boolean isSystemApp(PackageParser.Package pkg) {
15556        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15557    }
15558
15559    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15560        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15561    }
15562
15563    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15564        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15565    }
15566
15567    private static boolean isSystemApp(PackageSetting ps) {
15568        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15569    }
15570
15571    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15572        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15573    }
15574
15575    private int packageFlagsToInstallFlags(PackageSetting ps) {
15576        int installFlags = 0;
15577        if (isEphemeral(ps)) {
15578            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15579        }
15580        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15581            // This existing package was an external ASEC install when we have
15582            // the external flag without a UUID
15583            installFlags |= PackageManager.INSTALL_EXTERNAL;
15584        }
15585        if (ps.isForwardLocked()) {
15586            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15587        }
15588        return installFlags;
15589    }
15590
15591    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15592        if (isExternal(pkg)) {
15593            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15594                return StorageManager.UUID_PRIMARY_PHYSICAL;
15595            } else {
15596                return pkg.volumeUuid;
15597            }
15598        } else {
15599            return StorageManager.UUID_PRIVATE_INTERNAL;
15600        }
15601    }
15602
15603    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15604        if (isExternal(pkg)) {
15605            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15606                return mSettings.getExternalVersion();
15607            } else {
15608                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15609            }
15610        } else {
15611            return mSettings.getInternalVersion();
15612        }
15613    }
15614
15615    private void deleteTempPackageFiles() {
15616        final FilenameFilter filter = new FilenameFilter() {
15617            public boolean accept(File dir, String name) {
15618                return name.startsWith("vmdl") && name.endsWith(".tmp");
15619            }
15620        };
15621        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15622            file.delete();
15623        }
15624    }
15625
15626    @Override
15627    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15628            int flags) {
15629        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15630                flags);
15631    }
15632
15633    @Override
15634    public void deletePackage(final String packageName,
15635            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15636        mContext.enforceCallingOrSelfPermission(
15637                android.Manifest.permission.DELETE_PACKAGES, null);
15638        Preconditions.checkNotNull(packageName);
15639        Preconditions.checkNotNull(observer);
15640        final int uid = Binder.getCallingUid();
15641        if (!isOrphaned(packageName)
15642                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15643            try {
15644                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15645                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15646                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15647                observer.onUserActionRequired(intent);
15648            } catch (RemoteException re) {
15649            }
15650            return;
15651        }
15652        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15653        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15654        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15655            mContext.enforceCallingOrSelfPermission(
15656                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15657                    "deletePackage for user " + userId);
15658        }
15659
15660        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15661            try {
15662                observer.onPackageDeleted(packageName,
15663                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15664            } catch (RemoteException re) {
15665            }
15666            return;
15667        }
15668
15669        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15670            try {
15671                observer.onPackageDeleted(packageName,
15672                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15673            } catch (RemoteException re) {
15674            }
15675            return;
15676        }
15677
15678        if (DEBUG_REMOVE) {
15679            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15680                    + " deleteAllUsers: " + deleteAllUsers );
15681        }
15682        // Queue up an async operation since the package deletion may take a little while.
15683        mHandler.post(new Runnable() {
15684            public void run() {
15685                mHandler.removeCallbacks(this);
15686                int returnCode;
15687                if (!deleteAllUsers) {
15688                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15689                } else {
15690                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15691                    // If nobody is blocking uninstall, proceed with delete for all users
15692                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15693                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15694                    } else {
15695                        // Otherwise uninstall individually for users with blockUninstalls=false
15696                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15697                        for (int userId : users) {
15698                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15699                                returnCode = deletePackageX(packageName, userId, userFlags);
15700                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15701                                    Slog.w(TAG, "Package delete failed for user " + userId
15702                                            + ", returnCode " + returnCode);
15703                                }
15704                            }
15705                        }
15706                        // The app has only been marked uninstalled for certain users.
15707                        // We still need to report that delete was blocked
15708                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15709                    }
15710                }
15711                try {
15712                    observer.onPackageDeleted(packageName, returnCode, null);
15713                } catch (RemoteException e) {
15714                    Log.i(TAG, "Observer no longer exists.");
15715                } //end catch
15716            } //end run
15717        });
15718    }
15719
15720    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15721        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15722              || callingUid == Process.SYSTEM_UID) {
15723            return true;
15724        }
15725        final int callingUserId = UserHandle.getUserId(callingUid);
15726        // If the caller installed the pkgName, then allow it to silently uninstall.
15727        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15728            return true;
15729        }
15730
15731        // Allow package verifier to silently uninstall.
15732        if (mRequiredVerifierPackage != null &&
15733                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15734            return true;
15735        }
15736
15737        // Allow package uninstaller to silently uninstall.
15738        if (mRequiredUninstallerPackage != null &&
15739                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15740            return true;
15741        }
15742
15743        // Allow storage manager to silently uninstall.
15744        if (mStorageManagerPackage != null &&
15745                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15746            return true;
15747        }
15748        return false;
15749    }
15750
15751    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15752        int[] result = EMPTY_INT_ARRAY;
15753        for (int userId : userIds) {
15754            if (getBlockUninstallForUser(packageName, userId)) {
15755                result = ArrayUtils.appendInt(result, userId);
15756            }
15757        }
15758        return result;
15759    }
15760
15761    @Override
15762    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15763        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15764    }
15765
15766    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15767        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15768                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15769        try {
15770            if (dpm != null) {
15771                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15772                        /* callingUserOnly =*/ false);
15773                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15774                        : deviceOwnerComponentName.getPackageName();
15775                // Does the package contains the device owner?
15776                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15777                // this check is probably not needed, since DO should be registered as a device
15778                // admin on some user too. (Original bug for this: b/17657954)
15779                if (packageName.equals(deviceOwnerPackageName)) {
15780                    return true;
15781                }
15782                // Does it contain a device admin for any user?
15783                int[] users;
15784                if (userId == UserHandle.USER_ALL) {
15785                    users = sUserManager.getUserIds();
15786                } else {
15787                    users = new int[]{userId};
15788                }
15789                for (int i = 0; i < users.length; ++i) {
15790                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15791                        return true;
15792                    }
15793                }
15794            }
15795        } catch (RemoteException e) {
15796        }
15797        return false;
15798    }
15799
15800    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15801        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15802    }
15803
15804    /**
15805     *  This method is an internal method that could be get invoked either
15806     *  to delete an installed package or to clean up a failed installation.
15807     *  After deleting an installed package, a broadcast is sent to notify any
15808     *  listeners that the package has been removed. For cleaning up a failed
15809     *  installation, the broadcast is not necessary since the package's
15810     *  installation wouldn't have sent the initial broadcast either
15811     *  The key steps in deleting a package are
15812     *  deleting the package information in internal structures like mPackages,
15813     *  deleting the packages base directories through installd
15814     *  updating mSettings to reflect current status
15815     *  persisting settings for later use
15816     *  sending a broadcast if necessary
15817     */
15818    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15819        final PackageRemovedInfo info = new PackageRemovedInfo();
15820        final boolean res;
15821
15822        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15823                ? UserHandle.USER_ALL : userId;
15824
15825        if (isPackageDeviceAdmin(packageName, removeUser)) {
15826            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15827            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15828        }
15829
15830        PackageSetting uninstalledPs = null;
15831
15832        // for the uninstall-updates case and restricted profiles, remember the per-
15833        // user handle installed state
15834        int[] allUsers;
15835        synchronized (mPackages) {
15836            uninstalledPs = mSettings.mPackages.get(packageName);
15837            if (uninstalledPs == null) {
15838                Slog.w(TAG, "Not removing non-existent package " + packageName);
15839                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15840            }
15841            allUsers = sUserManager.getUserIds();
15842            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15843        }
15844
15845        final int freezeUser;
15846        if (isUpdatedSystemApp(uninstalledPs)
15847                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15848            // We're downgrading a system app, which will apply to all users, so
15849            // freeze them all during the downgrade
15850            freezeUser = UserHandle.USER_ALL;
15851        } else {
15852            freezeUser = removeUser;
15853        }
15854
15855        synchronized (mInstallLock) {
15856            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15857            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15858                    deleteFlags, "deletePackageX")) {
15859                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15860                        deleteFlags | REMOVE_CHATTY, info, true, null);
15861            }
15862            synchronized (mPackages) {
15863                if (res) {
15864                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15865                }
15866            }
15867        }
15868
15869        if (res) {
15870            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15871            info.sendPackageRemovedBroadcasts(killApp);
15872            info.sendSystemPackageUpdatedBroadcasts();
15873            info.sendSystemPackageAppearedBroadcasts();
15874        }
15875        // Force a gc here.
15876        Runtime.getRuntime().gc();
15877        // Delete the resources here after sending the broadcast to let
15878        // other processes clean up before deleting resources.
15879        if (info.args != null) {
15880            synchronized (mInstallLock) {
15881                info.args.doPostDeleteLI(true);
15882            }
15883        }
15884
15885        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15886    }
15887
15888    class PackageRemovedInfo {
15889        String removedPackage;
15890        int uid = -1;
15891        int removedAppId = -1;
15892        int[] origUsers;
15893        int[] removedUsers = null;
15894        boolean isRemovedPackageSystemUpdate = false;
15895        boolean isUpdate;
15896        boolean dataRemoved;
15897        boolean removedForAllUsers;
15898        // Clean up resources deleted packages.
15899        InstallArgs args = null;
15900        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15901        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15902
15903        void sendPackageRemovedBroadcasts(boolean killApp) {
15904            sendPackageRemovedBroadcastInternal(killApp);
15905            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15906            for (int i = 0; i < childCount; i++) {
15907                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15908                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15909            }
15910        }
15911
15912        void sendSystemPackageUpdatedBroadcasts() {
15913            if (isRemovedPackageSystemUpdate) {
15914                sendSystemPackageUpdatedBroadcastsInternal();
15915                final int childCount = (removedChildPackages != null)
15916                        ? removedChildPackages.size() : 0;
15917                for (int i = 0; i < childCount; i++) {
15918                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15919                    if (childInfo.isRemovedPackageSystemUpdate) {
15920                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15921                    }
15922                }
15923            }
15924        }
15925
15926        void sendSystemPackageAppearedBroadcasts() {
15927            final int packageCount = (appearedChildPackages != null)
15928                    ? appearedChildPackages.size() : 0;
15929            for (int i = 0; i < packageCount; i++) {
15930                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15931                for (int userId : installedInfo.newUsers) {
15932                    sendPackageAddedForUser(installedInfo.name, true,
15933                            UserHandle.getAppId(installedInfo.uid), userId);
15934                }
15935            }
15936        }
15937
15938        private void sendSystemPackageUpdatedBroadcastsInternal() {
15939            Bundle extras = new Bundle(2);
15940            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15941            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15942            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15943                    extras, 0, null, null, null);
15944            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15945                    extras, 0, null, null, null);
15946            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15947                    null, 0, removedPackage, null, null);
15948        }
15949
15950        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15951            Bundle extras = new Bundle(2);
15952            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15953            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15954            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15955            if (isUpdate || isRemovedPackageSystemUpdate) {
15956                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15957            }
15958            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15959            if (removedPackage != null) {
15960                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15961                        extras, 0, null, null, removedUsers);
15962                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15963                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15964                            removedPackage, extras, 0, null, null, removedUsers);
15965                }
15966            }
15967            if (removedAppId >= 0) {
15968                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15969                        removedUsers);
15970            }
15971        }
15972    }
15973
15974    /*
15975     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15976     * flag is not set, the data directory is removed as well.
15977     * make sure this flag is set for partially installed apps. If not its meaningless to
15978     * delete a partially installed application.
15979     */
15980    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15981            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15982        String packageName = ps.name;
15983        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15984        // Retrieve object to delete permissions for shared user later on
15985        final PackageParser.Package deletedPkg;
15986        final PackageSetting deletedPs;
15987        // reader
15988        synchronized (mPackages) {
15989            deletedPkg = mPackages.get(packageName);
15990            deletedPs = mSettings.mPackages.get(packageName);
15991            if (outInfo != null) {
15992                outInfo.removedPackage = packageName;
15993                outInfo.removedUsers = deletedPs != null
15994                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15995                        : null;
15996            }
15997        }
15998
15999        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16000
16001        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16002            final PackageParser.Package resolvedPkg;
16003            if (deletedPkg != null) {
16004                resolvedPkg = deletedPkg;
16005            } else {
16006                // We don't have a parsed package when it lives on an ejected
16007                // adopted storage device, so fake something together
16008                resolvedPkg = new PackageParser.Package(ps.name);
16009                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16010            }
16011            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16012                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16013            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16014            if (outInfo != null) {
16015                outInfo.dataRemoved = true;
16016            }
16017            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16018        }
16019
16020        // writer
16021        synchronized (mPackages) {
16022            if (deletedPs != null) {
16023                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16024                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16025                    clearDefaultBrowserIfNeeded(packageName);
16026                    if (outInfo != null) {
16027                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16028                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16029                    }
16030                    updatePermissionsLPw(deletedPs.name, null, 0);
16031                    if (deletedPs.sharedUser != null) {
16032                        // Remove permissions associated with package. Since runtime
16033                        // permissions are per user we have to kill the removed package
16034                        // or packages running under the shared user of the removed
16035                        // package if revoking the permissions requested only by the removed
16036                        // package is successful and this causes a change in gids.
16037                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16038                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16039                                    userId);
16040                            if (userIdToKill == UserHandle.USER_ALL
16041                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16042                                // If gids changed for this user, kill all affected packages.
16043                                mHandler.post(new Runnable() {
16044                                    @Override
16045                                    public void run() {
16046                                        // This has to happen with no lock held.
16047                                        killApplication(deletedPs.name, deletedPs.appId,
16048                                                KILL_APP_REASON_GIDS_CHANGED);
16049                                    }
16050                                });
16051                                break;
16052                            }
16053                        }
16054                    }
16055                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16056                }
16057                // make sure to preserve per-user disabled state if this removal was just
16058                // a downgrade of a system app to the factory package
16059                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16060                    if (DEBUG_REMOVE) {
16061                        Slog.d(TAG, "Propagating install state across downgrade");
16062                    }
16063                    for (int userId : allUserHandles) {
16064                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16065                        if (DEBUG_REMOVE) {
16066                            Slog.d(TAG, "    user " + userId + " => " + installed);
16067                        }
16068                        ps.setInstalled(installed, userId);
16069                    }
16070                }
16071            }
16072            // can downgrade to reader
16073            if (writeSettings) {
16074                // Save settings now
16075                mSettings.writeLPr();
16076            }
16077        }
16078        if (outInfo != null) {
16079            // A user ID was deleted here. Go through all users and remove it
16080            // from KeyStore.
16081            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16082        }
16083    }
16084
16085    static boolean locationIsPrivileged(File path) {
16086        try {
16087            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16088                    .getCanonicalPath();
16089            return path.getCanonicalPath().startsWith(privilegedAppDir);
16090        } catch (IOException e) {
16091            Slog.e(TAG, "Unable to access code path " + path);
16092        }
16093        return false;
16094    }
16095
16096    /*
16097     * Tries to delete system package.
16098     */
16099    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16100            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16101            boolean writeSettings) {
16102        if (deletedPs.parentPackageName != null) {
16103            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16104            return false;
16105        }
16106
16107        final boolean applyUserRestrictions
16108                = (allUserHandles != null) && (outInfo.origUsers != null);
16109        final PackageSetting disabledPs;
16110        // Confirm if the system package has been updated
16111        // An updated system app can be deleted. This will also have to restore
16112        // the system pkg from system partition
16113        // reader
16114        synchronized (mPackages) {
16115            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16116        }
16117
16118        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16119                + " disabledPs=" + disabledPs);
16120
16121        if (disabledPs == null) {
16122            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16123            return false;
16124        } else if (DEBUG_REMOVE) {
16125            Slog.d(TAG, "Deleting system pkg from data partition");
16126        }
16127
16128        if (DEBUG_REMOVE) {
16129            if (applyUserRestrictions) {
16130                Slog.d(TAG, "Remembering install states:");
16131                for (int userId : allUserHandles) {
16132                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16133                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16134                }
16135            }
16136        }
16137
16138        // Delete the updated package
16139        outInfo.isRemovedPackageSystemUpdate = true;
16140        if (outInfo.removedChildPackages != null) {
16141            final int childCount = (deletedPs.childPackageNames != null)
16142                    ? deletedPs.childPackageNames.size() : 0;
16143            for (int i = 0; i < childCount; i++) {
16144                String childPackageName = deletedPs.childPackageNames.get(i);
16145                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16146                        .contains(childPackageName)) {
16147                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16148                            childPackageName);
16149                    if (childInfo != null) {
16150                        childInfo.isRemovedPackageSystemUpdate = true;
16151                    }
16152                }
16153            }
16154        }
16155
16156        if (disabledPs.versionCode < deletedPs.versionCode) {
16157            // Delete data for downgrades
16158            flags &= ~PackageManager.DELETE_KEEP_DATA;
16159        } else {
16160            // Preserve data by setting flag
16161            flags |= PackageManager.DELETE_KEEP_DATA;
16162        }
16163
16164        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16165                outInfo, writeSettings, disabledPs.pkg);
16166        if (!ret) {
16167            return false;
16168        }
16169
16170        // writer
16171        synchronized (mPackages) {
16172            // Reinstate the old system package
16173            enableSystemPackageLPw(disabledPs.pkg);
16174            // Remove any native libraries from the upgraded package.
16175            removeNativeBinariesLI(deletedPs);
16176        }
16177
16178        // Install the system package
16179        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16180        int parseFlags = mDefParseFlags
16181                | PackageParser.PARSE_MUST_BE_APK
16182                | PackageParser.PARSE_IS_SYSTEM
16183                | PackageParser.PARSE_IS_SYSTEM_DIR;
16184        if (locationIsPrivileged(disabledPs.codePath)) {
16185            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16186        }
16187
16188        final PackageParser.Package newPkg;
16189        try {
16190            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16191        } catch (PackageManagerException e) {
16192            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16193                    + e.getMessage());
16194            return false;
16195        }
16196        try {
16197            // update shared libraries for the newly re-installed system package
16198            updateSharedLibrariesLPr(newPkg, null);
16199        } catch (PackageManagerException e) {
16200            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16201        }
16202
16203        prepareAppDataAfterInstallLIF(newPkg);
16204
16205        // writer
16206        synchronized (mPackages) {
16207            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16208
16209            // Propagate the permissions state as we do not want to drop on the floor
16210            // runtime permissions. The update permissions method below will take
16211            // care of removing obsolete permissions and grant install permissions.
16212            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16213            updatePermissionsLPw(newPkg.packageName, newPkg,
16214                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16215
16216            if (applyUserRestrictions) {
16217                if (DEBUG_REMOVE) {
16218                    Slog.d(TAG, "Propagating install state across reinstall");
16219                }
16220                for (int userId : allUserHandles) {
16221                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16222                    if (DEBUG_REMOVE) {
16223                        Slog.d(TAG, "    user " + userId + " => " + installed);
16224                    }
16225                    ps.setInstalled(installed, userId);
16226
16227                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16228                }
16229                // Regardless of writeSettings we need to ensure that this restriction
16230                // state propagation is persisted
16231                mSettings.writeAllUsersPackageRestrictionsLPr();
16232            }
16233            // can downgrade to reader here
16234            if (writeSettings) {
16235                mSettings.writeLPr();
16236            }
16237        }
16238        return true;
16239    }
16240
16241    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16242            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16243            PackageRemovedInfo outInfo, boolean writeSettings,
16244            PackageParser.Package replacingPackage) {
16245        synchronized (mPackages) {
16246            if (outInfo != null) {
16247                outInfo.uid = ps.appId;
16248            }
16249
16250            if (outInfo != null && outInfo.removedChildPackages != null) {
16251                final int childCount = (ps.childPackageNames != null)
16252                        ? ps.childPackageNames.size() : 0;
16253                for (int i = 0; i < childCount; i++) {
16254                    String childPackageName = ps.childPackageNames.get(i);
16255                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16256                    if (childPs == null) {
16257                        return false;
16258                    }
16259                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16260                            childPackageName);
16261                    if (childInfo != null) {
16262                        childInfo.uid = childPs.appId;
16263                    }
16264                }
16265            }
16266        }
16267
16268        // Delete package data from internal structures and also remove data if flag is set
16269        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16270
16271        // Delete the child packages data
16272        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16273        for (int i = 0; i < childCount; i++) {
16274            PackageSetting childPs;
16275            synchronized (mPackages) {
16276                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16277            }
16278            if (childPs != null) {
16279                PackageRemovedInfo childOutInfo = (outInfo != null
16280                        && outInfo.removedChildPackages != null)
16281                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16282                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16283                        && (replacingPackage != null
16284                        && !replacingPackage.hasChildPackage(childPs.name))
16285                        ? flags & ~DELETE_KEEP_DATA : flags;
16286                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16287                        deleteFlags, writeSettings);
16288            }
16289        }
16290
16291        // Delete application code and resources only for parent packages
16292        if (ps.parentPackageName == null) {
16293            if (deleteCodeAndResources && (outInfo != null)) {
16294                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16295                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16296                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16297            }
16298        }
16299
16300        return true;
16301    }
16302
16303    @Override
16304    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16305            int userId) {
16306        mContext.enforceCallingOrSelfPermission(
16307                android.Manifest.permission.DELETE_PACKAGES, null);
16308        synchronized (mPackages) {
16309            PackageSetting ps = mSettings.mPackages.get(packageName);
16310            if (ps == null) {
16311                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16312                return false;
16313            }
16314            if (!ps.getInstalled(userId)) {
16315                // Can't block uninstall for an app that is not installed or enabled.
16316                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16317                return false;
16318            }
16319            ps.setBlockUninstall(blockUninstall, userId);
16320            mSettings.writePackageRestrictionsLPr(userId);
16321        }
16322        return true;
16323    }
16324
16325    @Override
16326    public boolean getBlockUninstallForUser(String packageName, int userId) {
16327        synchronized (mPackages) {
16328            PackageSetting ps = mSettings.mPackages.get(packageName);
16329            if (ps == null) {
16330                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16331                return false;
16332            }
16333            return ps.getBlockUninstall(userId);
16334        }
16335    }
16336
16337    @Override
16338    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16339        int callingUid = Binder.getCallingUid();
16340        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16341            throw new SecurityException(
16342                    "setRequiredForSystemUser can only be run by the system or root");
16343        }
16344        synchronized (mPackages) {
16345            PackageSetting ps = mSettings.mPackages.get(packageName);
16346            if (ps == null) {
16347                Log.w(TAG, "Package doesn't exist: " + packageName);
16348                return false;
16349            }
16350            if (systemUserApp) {
16351                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16352            } else {
16353                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16354            }
16355            mSettings.writeLPr();
16356        }
16357        return true;
16358    }
16359
16360    /*
16361     * This method handles package deletion in general
16362     */
16363    private boolean deletePackageLIF(String packageName, UserHandle user,
16364            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16365            PackageRemovedInfo outInfo, boolean writeSettings,
16366            PackageParser.Package replacingPackage) {
16367        if (packageName == null) {
16368            Slog.w(TAG, "Attempt to delete null packageName.");
16369            return false;
16370        }
16371
16372        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16373
16374        PackageSetting ps;
16375
16376        synchronized (mPackages) {
16377            ps = mSettings.mPackages.get(packageName);
16378            if (ps == null) {
16379                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16380                return false;
16381            }
16382
16383            if (ps.parentPackageName != null && (!isSystemApp(ps)
16384                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16385                if (DEBUG_REMOVE) {
16386                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16387                            + ((user == null) ? UserHandle.USER_ALL : user));
16388                }
16389                final int removedUserId = (user != null) ? user.getIdentifier()
16390                        : UserHandle.USER_ALL;
16391                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16392                    return false;
16393                }
16394                markPackageUninstalledForUserLPw(ps, user);
16395                scheduleWritePackageRestrictionsLocked(user);
16396                return true;
16397            }
16398        }
16399
16400        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16401                && user.getIdentifier() != UserHandle.USER_ALL)) {
16402            // The caller is asking that the package only be deleted for a single
16403            // user.  To do this, we just mark its uninstalled state and delete
16404            // its data. If this is a system app, we only allow this to happen if
16405            // they have set the special DELETE_SYSTEM_APP which requests different
16406            // semantics than normal for uninstalling system apps.
16407            markPackageUninstalledForUserLPw(ps, user);
16408
16409            if (!isSystemApp(ps)) {
16410                // Do not uninstall the APK if an app should be cached
16411                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16412                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16413                    // Other user still have this package installed, so all
16414                    // we need to do is clear this user's data and save that
16415                    // it is uninstalled.
16416                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16417                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16418                        return false;
16419                    }
16420                    scheduleWritePackageRestrictionsLocked(user);
16421                    return true;
16422                } else {
16423                    // We need to set it back to 'installed' so the uninstall
16424                    // broadcasts will be sent correctly.
16425                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16426                    ps.setInstalled(true, user.getIdentifier());
16427                }
16428            } else {
16429                // This is a system app, so we assume that the
16430                // other users still have this package installed, so all
16431                // we need to do is clear this user's data and save that
16432                // it is uninstalled.
16433                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16434                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16435                    return false;
16436                }
16437                scheduleWritePackageRestrictionsLocked(user);
16438                return true;
16439            }
16440        }
16441
16442        // If we are deleting a composite package for all users, keep track
16443        // of result for each child.
16444        if (ps.childPackageNames != null && outInfo != null) {
16445            synchronized (mPackages) {
16446                final int childCount = ps.childPackageNames.size();
16447                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16448                for (int i = 0; i < childCount; i++) {
16449                    String childPackageName = ps.childPackageNames.get(i);
16450                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16451                    childInfo.removedPackage = childPackageName;
16452                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16453                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16454                    if (childPs != null) {
16455                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16456                    }
16457                }
16458            }
16459        }
16460
16461        boolean ret = false;
16462        if (isSystemApp(ps)) {
16463            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16464            // When an updated system application is deleted we delete the existing resources
16465            // as well and fall back to existing code in system partition
16466            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16467        } else {
16468            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16469            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16470                    outInfo, writeSettings, replacingPackage);
16471        }
16472
16473        // Take a note whether we deleted the package for all users
16474        if (outInfo != null) {
16475            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16476            if (outInfo.removedChildPackages != null) {
16477                synchronized (mPackages) {
16478                    final int childCount = outInfo.removedChildPackages.size();
16479                    for (int i = 0; i < childCount; i++) {
16480                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16481                        if (childInfo != null) {
16482                            childInfo.removedForAllUsers = mPackages.get(
16483                                    childInfo.removedPackage) == null;
16484                        }
16485                    }
16486                }
16487            }
16488            // If we uninstalled an update to a system app there may be some
16489            // child packages that appeared as they are declared in the system
16490            // app but were not declared in the update.
16491            if (isSystemApp(ps)) {
16492                synchronized (mPackages) {
16493                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16494                    final int childCount = (updatedPs.childPackageNames != null)
16495                            ? updatedPs.childPackageNames.size() : 0;
16496                    for (int i = 0; i < childCount; i++) {
16497                        String childPackageName = updatedPs.childPackageNames.get(i);
16498                        if (outInfo.removedChildPackages == null
16499                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16500                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16501                            if (childPs == null) {
16502                                continue;
16503                            }
16504                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16505                            installRes.name = childPackageName;
16506                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16507                            installRes.pkg = mPackages.get(childPackageName);
16508                            installRes.uid = childPs.pkg.applicationInfo.uid;
16509                            if (outInfo.appearedChildPackages == null) {
16510                                outInfo.appearedChildPackages = new ArrayMap<>();
16511                            }
16512                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16513                        }
16514                    }
16515                }
16516            }
16517        }
16518
16519        return ret;
16520    }
16521
16522    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16523        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16524                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16525        for (int nextUserId : userIds) {
16526            if (DEBUG_REMOVE) {
16527                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16528            }
16529            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16530                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16531                    false /*hidden*/, false /*suspended*/, null, null, null,
16532                    false /*blockUninstall*/,
16533                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16534        }
16535    }
16536
16537    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16538            PackageRemovedInfo outInfo) {
16539        final PackageParser.Package pkg;
16540        synchronized (mPackages) {
16541            pkg = mPackages.get(ps.name);
16542        }
16543
16544        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16545                : new int[] {userId};
16546        for (int nextUserId : userIds) {
16547            if (DEBUG_REMOVE) {
16548                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16549                        + nextUserId);
16550            }
16551
16552            destroyAppDataLIF(pkg, userId,
16553                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16554            destroyAppProfilesLIF(pkg, userId);
16555            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16556            schedulePackageCleaning(ps.name, nextUserId, false);
16557            synchronized (mPackages) {
16558                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16559                    scheduleWritePackageRestrictionsLocked(nextUserId);
16560                }
16561                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16562            }
16563        }
16564
16565        if (outInfo != null) {
16566            outInfo.removedPackage = ps.name;
16567            outInfo.removedAppId = ps.appId;
16568            outInfo.removedUsers = userIds;
16569        }
16570
16571        return true;
16572    }
16573
16574    private final class ClearStorageConnection implements ServiceConnection {
16575        IMediaContainerService mContainerService;
16576
16577        @Override
16578        public void onServiceConnected(ComponentName name, IBinder service) {
16579            synchronized (this) {
16580                mContainerService = IMediaContainerService.Stub.asInterface(service);
16581                notifyAll();
16582            }
16583        }
16584
16585        @Override
16586        public void onServiceDisconnected(ComponentName name) {
16587        }
16588    }
16589
16590    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16591        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16592
16593        final boolean mounted;
16594        if (Environment.isExternalStorageEmulated()) {
16595            mounted = true;
16596        } else {
16597            final String status = Environment.getExternalStorageState();
16598
16599            mounted = status.equals(Environment.MEDIA_MOUNTED)
16600                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16601        }
16602
16603        if (!mounted) {
16604            return;
16605        }
16606
16607        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16608        int[] users;
16609        if (userId == UserHandle.USER_ALL) {
16610            users = sUserManager.getUserIds();
16611        } else {
16612            users = new int[] { userId };
16613        }
16614        final ClearStorageConnection conn = new ClearStorageConnection();
16615        if (mContext.bindServiceAsUser(
16616                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16617            try {
16618                for (int curUser : users) {
16619                    long timeout = SystemClock.uptimeMillis() + 5000;
16620                    synchronized (conn) {
16621                        long now;
16622                        while (conn.mContainerService == null &&
16623                                (now = SystemClock.uptimeMillis()) < timeout) {
16624                            try {
16625                                conn.wait(timeout - now);
16626                            } catch (InterruptedException e) {
16627                            }
16628                        }
16629                    }
16630                    if (conn.mContainerService == null) {
16631                        return;
16632                    }
16633
16634                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16635                    clearDirectory(conn.mContainerService,
16636                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16637                    if (allData) {
16638                        clearDirectory(conn.mContainerService,
16639                                userEnv.buildExternalStorageAppDataDirs(packageName));
16640                        clearDirectory(conn.mContainerService,
16641                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16642                    }
16643                }
16644            } finally {
16645                mContext.unbindService(conn);
16646            }
16647        }
16648    }
16649
16650    @Override
16651    public void clearApplicationProfileData(String packageName) {
16652        enforceSystemOrRoot("Only the system can clear all profile data");
16653
16654        final PackageParser.Package pkg;
16655        synchronized (mPackages) {
16656            pkg = mPackages.get(packageName);
16657        }
16658
16659        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16660            synchronized (mInstallLock) {
16661                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16662                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16663                        true /* removeBaseMarker */);
16664            }
16665        }
16666    }
16667
16668    @Override
16669    public void clearApplicationUserData(final String packageName,
16670            final IPackageDataObserver observer, final int userId) {
16671        mContext.enforceCallingOrSelfPermission(
16672                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16673
16674        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16675                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16676
16677        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16678            throw new SecurityException("Cannot clear data for a protected package: "
16679                    + packageName);
16680        }
16681        // Queue up an async operation since the package deletion may take a little while.
16682        mHandler.post(new Runnable() {
16683            public void run() {
16684                mHandler.removeCallbacks(this);
16685                final boolean succeeded;
16686                try (PackageFreezer freezer = freezePackage(packageName,
16687                        "clearApplicationUserData")) {
16688                    synchronized (mInstallLock) {
16689                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16690                    }
16691                    clearExternalStorageDataSync(packageName, userId, true);
16692                }
16693                if (succeeded) {
16694                    // invoke DeviceStorageMonitor's update method to clear any notifications
16695                    DeviceStorageMonitorInternal dsm = LocalServices
16696                            .getService(DeviceStorageMonitorInternal.class);
16697                    if (dsm != null) {
16698                        dsm.checkMemory();
16699                    }
16700                }
16701                if(observer != null) {
16702                    try {
16703                        observer.onRemoveCompleted(packageName, succeeded);
16704                    } catch (RemoteException e) {
16705                        Log.i(TAG, "Observer no longer exists.");
16706                    }
16707                } //end if observer
16708            } //end run
16709        });
16710    }
16711
16712    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16713        if (packageName == null) {
16714            Slog.w(TAG, "Attempt to delete null packageName.");
16715            return false;
16716        }
16717
16718        // Try finding details about the requested package
16719        PackageParser.Package pkg;
16720        synchronized (mPackages) {
16721            pkg = mPackages.get(packageName);
16722            if (pkg == null) {
16723                final PackageSetting ps = mSettings.mPackages.get(packageName);
16724                if (ps != null) {
16725                    pkg = ps.pkg;
16726                }
16727            }
16728
16729            if (pkg == null) {
16730                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16731                return false;
16732            }
16733
16734            PackageSetting ps = (PackageSetting) pkg.mExtras;
16735            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16736        }
16737
16738        clearAppDataLIF(pkg, userId,
16739                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16740
16741        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16742        removeKeystoreDataIfNeeded(userId, appId);
16743
16744        UserManagerInternal umInternal = getUserManagerInternal();
16745        final int flags;
16746        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16747            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16748        } else if (umInternal.isUserRunning(userId)) {
16749            flags = StorageManager.FLAG_STORAGE_DE;
16750        } else {
16751            flags = 0;
16752        }
16753        prepareAppDataContentsLIF(pkg, userId, flags);
16754
16755        return true;
16756    }
16757
16758    /**
16759     * Reverts user permission state changes (permissions and flags) in
16760     * all packages for a given user.
16761     *
16762     * @param userId The device user for which to do a reset.
16763     */
16764    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16765        final int packageCount = mPackages.size();
16766        for (int i = 0; i < packageCount; i++) {
16767            PackageParser.Package pkg = mPackages.valueAt(i);
16768            PackageSetting ps = (PackageSetting) pkg.mExtras;
16769            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16770        }
16771    }
16772
16773    private void resetNetworkPolicies(int userId) {
16774        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16775    }
16776
16777    /**
16778     * Reverts user permission state changes (permissions and flags).
16779     *
16780     * @param ps The package for which to reset.
16781     * @param userId The device user for which to do a reset.
16782     */
16783    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16784            final PackageSetting ps, final int userId) {
16785        if (ps.pkg == null) {
16786            return;
16787        }
16788
16789        // These are flags that can change base on user actions.
16790        final int userSettableMask = FLAG_PERMISSION_USER_SET
16791                | FLAG_PERMISSION_USER_FIXED
16792                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16793                | FLAG_PERMISSION_REVIEW_REQUIRED;
16794
16795        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16796                | FLAG_PERMISSION_POLICY_FIXED;
16797
16798        boolean writeInstallPermissions = false;
16799        boolean writeRuntimePermissions = false;
16800
16801        final int permissionCount = ps.pkg.requestedPermissions.size();
16802        for (int i = 0; i < permissionCount; i++) {
16803            String permission = ps.pkg.requestedPermissions.get(i);
16804
16805            BasePermission bp = mSettings.mPermissions.get(permission);
16806            if (bp == null) {
16807                continue;
16808            }
16809
16810            // If shared user we just reset the state to which only this app contributed.
16811            if (ps.sharedUser != null) {
16812                boolean used = false;
16813                final int packageCount = ps.sharedUser.packages.size();
16814                for (int j = 0; j < packageCount; j++) {
16815                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16816                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16817                            && pkg.pkg.requestedPermissions.contains(permission)) {
16818                        used = true;
16819                        break;
16820                    }
16821                }
16822                if (used) {
16823                    continue;
16824                }
16825            }
16826
16827            PermissionsState permissionsState = ps.getPermissionsState();
16828
16829            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16830
16831            // Always clear the user settable flags.
16832            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16833                    bp.name) != null;
16834            // If permission review is enabled and this is a legacy app, mark the
16835            // permission as requiring a review as this is the initial state.
16836            int flags = 0;
16837            if (mPermissionReviewRequired
16838                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16839                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16840            }
16841            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16842                if (hasInstallState) {
16843                    writeInstallPermissions = true;
16844                } else {
16845                    writeRuntimePermissions = true;
16846                }
16847            }
16848
16849            // Below is only runtime permission handling.
16850            if (!bp.isRuntime()) {
16851                continue;
16852            }
16853
16854            // Never clobber system or policy.
16855            if ((oldFlags & policyOrSystemFlags) != 0) {
16856                continue;
16857            }
16858
16859            // If this permission was granted by default, make sure it is.
16860            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16861                if (permissionsState.grantRuntimePermission(bp, userId)
16862                        != PERMISSION_OPERATION_FAILURE) {
16863                    writeRuntimePermissions = true;
16864                }
16865            // If permission review is enabled the permissions for a legacy apps
16866            // are represented as constantly granted runtime ones, so don't revoke.
16867            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16868                // Otherwise, reset the permission.
16869                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16870                switch (revokeResult) {
16871                    case PERMISSION_OPERATION_SUCCESS:
16872                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16873                        writeRuntimePermissions = true;
16874                        final int appId = ps.appId;
16875                        mHandler.post(new Runnable() {
16876                            @Override
16877                            public void run() {
16878                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16879                            }
16880                        });
16881                    } break;
16882                }
16883            }
16884        }
16885
16886        // Synchronously write as we are taking permissions away.
16887        if (writeRuntimePermissions) {
16888            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16889        }
16890
16891        // Synchronously write as we are taking permissions away.
16892        if (writeInstallPermissions) {
16893            mSettings.writeLPr();
16894        }
16895    }
16896
16897    /**
16898     * Remove entries from the keystore daemon. Will only remove it if the
16899     * {@code appId} is valid.
16900     */
16901    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16902        if (appId < 0) {
16903            return;
16904        }
16905
16906        final KeyStore keyStore = KeyStore.getInstance();
16907        if (keyStore != null) {
16908            if (userId == UserHandle.USER_ALL) {
16909                for (final int individual : sUserManager.getUserIds()) {
16910                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16911                }
16912            } else {
16913                keyStore.clearUid(UserHandle.getUid(userId, appId));
16914            }
16915        } else {
16916            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16917        }
16918    }
16919
16920    @Override
16921    public void deleteApplicationCacheFiles(final String packageName,
16922            final IPackageDataObserver observer) {
16923        final int userId = UserHandle.getCallingUserId();
16924        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16925    }
16926
16927    @Override
16928    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16929            final IPackageDataObserver observer) {
16930        mContext.enforceCallingOrSelfPermission(
16931                android.Manifest.permission.DELETE_CACHE_FILES, null);
16932        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16933                /* requireFullPermission= */ true, /* checkShell= */ false,
16934                "delete application cache files");
16935
16936        final PackageParser.Package pkg;
16937        synchronized (mPackages) {
16938            pkg = mPackages.get(packageName);
16939        }
16940
16941        // Queue up an async operation since the package deletion may take a little while.
16942        mHandler.post(new Runnable() {
16943            public void run() {
16944                synchronized (mInstallLock) {
16945                    final int flags = StorageManager.FLAG_STORAGE_DE
16946                            | StorageManager.FLAG_STORAGE_CE;
16947                    // We're only clearing cache files, so we don't care if the
16948                    // app is unfrozen and still able to run
16949                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16950                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16951                }
16952                clearExternalStorageDataSync(packageName, userId, false);
16953                if (observer != null) {
16954                    try {
16955                        observer.onRemoveCompleted(packageName, true);
16956                    } catch (RemoteException e) {
16957                        Log.i(TAG, "Observer no longer exists.");
16958                    }
16959                }
16960            }
16961        });
16962    }
16963
16964    @Override
16965    public void getPackageSizeInfo(final String packageName, int userHandle,
16966            final IPackageStatsObserver observer) {
16967        mContext.enforceCallingOrSelfPermission(
16968                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16969        if (packageName == null) {
16970            throw new IllegalArgumentException("Attempt to get size of null packageName");
16971        }
16972
16973        PackageStats stats = new PackageStats(packageName, userHandle);
16974
16975        /*
16976         * Queue up an async operation since the package measurement may take a
16977         * little while.
16978         */
16979        Message msg = mHandler.obtainMessage(INIT_COPY);
16980        msg.obj = new MeasureParams(stats, observer);
16981        mHandler.sendMessage(msg);
16982    }
16983
16984    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16985        final PackageSetting ps;
16986        synchronized (mPackages) {
16987            ps = mSettings.mPackages.get(packageName);
16988            if (ps == null) {
16989                Slog.w(TAG, "Failed to find settings for " + packageName);
16990                return false;
16991            }
16992        }
16993        try {
16994            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16995                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16996                    ps.getCeDataInode(userId), ps.codePathString, stats);
16997        } catch (InstallerException e) {
16998            Slog.w(TAG, String.valueOf(e));
16999            return false;
17000        }
17001
17002        // For now, ignore code size of packages on system partition
17003        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17004            stats.codeSize = 0;
17005        }
17006
17007        return true;
17008    }
17009
17010    private int getUidTargetSdkVersionLockedLPr(int uid) {
17011        Object obj = mSettings.getUserIdLPr(uid);
17012        if (obj instanceof SharedUserSetting) {
17013            final SharedUserSetting sus = (SharedUserSetting) obj;
17014            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17015            final Iterator<PackageSetting> it = sus.packages.iterator();
17016            while (it.hasNext()) {
17017                final PackageSetting ps = it.next();
17018                if (ps.pkg != null) {
17019                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17020                    if (v < vers) vers = v;
17021                }
17022            }
17023            return vers;
17024        } else if (obj instanceof PackageSetting) {
17025            final PackageSetting ps = (PackageSetting) obj;
17026            if (ps.pkg != null) {
17027                return ps.pkg.applicationInfo.targetSdkVersion;
17028            }
17029        }
17030        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17031    }
17032
17033    @Override
17034    public void addPreferredActivity(IntentFilter filter, int match,
17035            ComponentName[] set, ComponentName activity, int userId) {
17036        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17037                "Adding preferred");
17038    }
17039
17040    private void addPreferredActivityInternal(IntentFilter filter, int match,
17041            ComponentName[] set, ComponentName activity, boolean always, int userId,
17042            String opname) {
17043        // writer
17044        int callingUid = Binder.getCallingUid();
17045        enforceCrossUserPermission(callingUid, userId,
17046                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17047        if (filter.countActions() == 0) {
17048            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17049            return;
17050        }
17051        synchronized (mPackages) {
17052            if (mContext.checkCallingOrSelfPermission(
17053                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17054                    != PackageManager.PERMISSION_GRANTED) {
17055                if (getUidTargetSdkVersionLockedLPr(callingUid)
17056                        < Build.VERSION_CODES.FROYO) {
17057                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17058                            + callingUid);
17059                    return;
17060                }
17061                mContext.enforceCallingOrSelfPermission(
17062                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17063            }
17064
17065            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17066            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17067                    + userId + ":");
17068            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17069            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17070            scheduleWritePackageRestrictionsLocked(userId);
17071            postPreferredActivityChangedBroadcast(userId);
17072        }
17073    }
17074
17075    private void postPreferredActivityChangedBroadcast(int userId) {
17076        mHandler.post(() -> {
17077            final IActivityManager am = ActivityManagerNative.getDefault();
17078            if (am == null) {
17079                return;
17080            }
17081
17082            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17083            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17084            try {
17085                am.broadcastIntent(null, intent, null, null,
17086                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17087                        null, false, false, userId);
17088            } catch (RemoteException e) {
17089            }
17090        });
17091    }
17092
17093    @Override
17094    public void replacePreferredActivity(IntentFilter filter, int match,
17095            ComponentName[] set, ComponentName activity, int userId) {
17096        if (filter.countActions() != 1) {
17097            throw new IllegalArgumentException(
17098                    "replacePreferredActivity expects filter to have only 1 action.");
17099        }
17100        if (filter.countDataAuthorities() != 0
17101                || filter.countDataPaths() != 0
17102                || filter.countDataSchemes() > 1
17103                || filter.countDataTypes() != 0) {
17104            throw new IllegalArgumentException(
17105                    "replacePreferredActivity expects filter to have no data authorities, " +
17106                    "paths, or types; and at most one scheme.");
17107        }
17108
17109        final int callingUid = Binder.getCallingUid();
17110        enforceCrossUserPermission(callingUid, userId,
17111                true /* requireFullPermission */, false /* checkShell */,
17112                "replace preferred activity");
17113        synchronized (mPackages) {
17114            if (mContext.checkCallingOrSelfPermission(
17115                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17116                    != PackageManager.PERMISSION_GRANTED) {
17117                if (getUidTargetSdkVersionLockedLPr(callingUid)
17118                        < Build.VERSION_CODES.FROYO) {
17119                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17120                            + Binder.getCallingUid());
17121                    return;
17122                }
17123                mContext.enforceCallingOrSelfPermission(
17124                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17125            }
17126
17127            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17128            if (pir != null) {
17129                // Get all of the existing entries that exactly match this filter.
17130                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17131                if (existing != null && existing.size() == 1) {
17132                    PreferredActivity cur = existing.get(0);
17133                    if (DEBUG_PREFERRED) {
17134                        Slog.i(TAG, "Checking replace of preferred:");
17135                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17136                        if (!cur.mPref.mAlways) {
17137                            Slog.i(TAG, "  -- CUR; not mAlways!");
17138                        } else {
17139                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17140                            Slog.i(TAG, "  -- CUR: mSet="
17141                                    + Arrays.toString(cur.mPref.mSetComponents));
17142                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17143                            Slog.i(TAG, "  -- NEW: mMatch="
17144                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17145                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17146                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17147                        }
17148                    }
17149                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17150                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17151                            && cur.mPref.sameSet(set)) {
17152                        // Setting the preferred activity to what it happens to be already
17153                        if (DEBUG_PREFERRED) {
17154                            Slog.i(TAG, "Replacing with same preferred activity "
17155                                    + cur.mPref.mShortComponent + " for user "
17156                                    + userId + ":");
17157                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17158                        }
17159                        return;
17160                    }
17161                }
17162
17163                if (existing != null) {
17164                    if (DEBUG_PREFERRED) {
17165                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17166                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17167                    }
17168                    for (int i = 0; i < existing.size(); i++) {
17169                        PreferredActivity pa = existing.get(i);
17170                        if (DEBUG_PREFERRED) {
17171                            Slog.i(TAG, "Removing existing preferred activity "
17172                                    + pa.mPref.mComponent + ":");
17173                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17174                        }
17175                        pir.removeFilter(pa);
17176                    }
17177                }
17178            }
17179            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17180                    "Replacing preferred");
17181        }
17182    }
17183
17184    @Override
17185    public void clearPackagePreferredActivities(String packageName) {
17186        final int uid = Binder.getCallingUid();
17187        // writer
17188        synchronized (mPackages) {
17189            PackageParser.Package pkg = mPackages.get(packageName);
17190            if (pkg == null || pkg.applicationInfo.uid != uid) {
17191                if (mContext.checkCallingOrSelfPermission(
17192                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17193                        != PackageManager.PERMISSION_GRANTED) {
17194                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17195                            < Build.VERSION_CODES.FROYO) {
17196                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17197                                + Binder.getCallingUid());
17198                        return;
17199                    }
17200                    mContext.enforceCallingOrSelfPermission(
17201                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17202                }
17203            }
17204
17205            int user = UserHandle.getCallingUserId();
17206            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17207                scheduleWritePackageRestrictionsLocked(user);
17208            }
17209        }
17210    }
17211
17212    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17213    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17214        ArrayList<PreferredActivity> removed = null;
17215        boolean changed = false;
17216        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17217            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17218            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17219            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17220                continue;
17221            }
17222            Iterator<PreferredActivity> it = pir.filterIterator();
17223            while (it.hasNext()) {
17224                PreferredActivity pa = it.next();
17225                // Mark entry for removal only if it matches the package name
17226                // and the entry is of type "always".
17227                if (packageName == null ||
17228                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17229                                && pa.mPref.mAlways)) {
17230                    if (removed == null) {
17231                        removed = new ArrayList<PreferredActivity>();
17232                    }
17233                    removed.add(pa);
17234                }
17235            }
17236            if (removed != null) {
17237                for (int j=0; j<removed.size(); j++) {
17238                    PreferredActivity pa = removed.get(j);
17239                    pir.removeFilter(pa);
17240                }
17241                changed = true;
17242            }
17243        }
17244        if (changed) {
17245            postPreferredActivityChangedBroadcast(userId);
17246        }
17247        return changed;
17248    }
17249
17250    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17251    private void clearIntentFilterVerificationsLPw(int userId) {
17252        final int packageCount = mPackages.size();
17253        for (int i = 0; i < packageCount; i++) {
17254            PackageParser.Package pkg = mPackages.valueAt(i);
17255            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17256        }
17257    }
17258
17259    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17260    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17261        if (userId == UserHandle.USER_ALL) {
17262            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17263                    sUserManager.getUserIds())) {
17264                for (int oneUserId : sUserManager.getUserIds()) {
17265                    scheduleWritePackageRestrictionsLocked(oneUserId);
17266                }
17267            }
17268        } else {
17269            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17270                scheduleWritePackageRestrictionsLocked(userId);
17271            }
17272        }
17273    }
17274
17275    void clearDefaultBrowserIfNeeded(String packageName) {
17276        for (int oneUserId : sUserManager.getUserIds()) {
17277            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17278            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17279            if (packageName.equals(defaultBrowserPackageName)) {
17280                setDefaultBrowserPackageName(null, oneUserId);
17281            }
17282        }
17283    }
17284
17285    @Override
17286    public void resetApplicationPreferences(int userId) {
17287        mContext.enforceCallingOrSelfPermission(
17288                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17289        final long identity = Binder.clearCallingIdentity();
17290        // writer
17291        try {
17292            synchronized (mPackages) {
17293                clearPackagePreferredActivitiesLPw(null, userId);
17294                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17295                // TODO: We have to reset the default SMS and Phone. This requires
17296                // significant refactoring to keep all default apps in the package
17297                // manager (cleaner but more work) or have the services provide
17298                // callbacks to the package manager to request a default app reset.
17299                applyFactoryDefaultBrowserLPw(userId);
17300                clearIntentFilterVerificationsLPw(userId);
17301                primeDomainVerificationsLPw(userId);
17302                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17303                scheduleWritePackageRestrictionsLocked(userId);
17304            }
17305            resetNetworkPolicies(userId);
17306        } finally {
17307            Binder.restoreCallingIdentity(identity);
17308        }
17309    }
17310
17311    @Override
17312    public int getPreferredActivities(List<IntentFilter> outFilters,
17313            List<ComponentName> outActivities, String packageName) {
17314
17315        int num = 0;
17316        final int userId = UserHandle.getCallingUserId();
17317        // reader
17318        synchronized (mPackages) {
17319            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17320            if (pir != null) {
17321                final Iterator<PreferredActivity> it = pir.filterIterator();
17322                while (it.hasNext()) {
17323                    final PreferredActivity pa = it.next();
17324                    if (packageName == null
17325                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17326                                    && pa.mPref.mAlways)) {
17327                        if (outFilters != null) {
17328                            outFilters.add(new IntentFilter(pa));
17329                        }
17330                        if (outActivities != null) {
17331                            outActivities.add(pa.mPref.mComponent);
17332                        }
17333                    }
17334                }
17335            }
17336        }
17337
17338        return num;
17339    }
17340
17341    @Override
17342    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17343            int userId) {
17344        int callingUid = Binder.getCallingUid();
17345        if (callingUid != Process.SYSTEM_UID) {
17346            throw new SecurityException(
17347                    "addPersistentPreferredActivity can only be run by the system");
17348        }
17349        if (filter.countActions() == 0) {
17350            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17351            return;
17352        }
17353        synchronized (mPackages) {
17354            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17355                    ":");
17356            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17357            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17358                    new PersistentPreferredActivity(filter, activity));
17359            scheduleWritePackageRestrictionsLocked(userId);
17360            postPreferredActivityChangedBroadcast(userId);
17361        }
17362    }
17363
17364    @Override
17365    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17366        int callingUid = Binder.getCallingUid();
17367        if (callingUid != Process.SYSTEM_UID) {
17368            throw new SecurityException(
17369                    "clearPackagePersistentPreferredActivities can only be run by the system");
17370        }
17371        ArrayList<PersistentPreferredActivity> removed = null;
17372        boolean changed = false;
17373        synchronized (mPackages) {
17374            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17375                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17376                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17377                        .valueAt(i);
17378                if (userId != thisUserId) {
17379                    continue;
17380                }
17381                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17382                while (it.hasNext()) {
17383                    PersistentPreferredActivity ppa = it.next();
17384                    // Mark entry for removal only if it matches the package name.
17385                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17386                        if (removed == null) {
17387                            removed = new ArrayList<PersistentPreferredActivity>();
17388                        }
17389                        removed.add(ppa);
17390                    }
17391                }
17392                if (removed != null) {
17393                    for (int j=0; j<removed.size(); j++) {
17394                        PersistentPreferredActivity ppa = removed.get(j);
17395                        ppir.removeFilter(ppa);
17396                    }
17397                    changed = true;
17398                }
17399            }
17400
17401            if (changed) {
17402                scheduleWritePackageRestrictionsLocked(userId);
17403                postPreferredActivityChangedBroadcast(userId);
17404            }
17405        }
17406    }
17407
17408    /**
17409     * Common machinery for picking apart a restored XML blob and passing
17410     * it to a caller-supplied functor to be applied to the running system.
17411     */
17412    private void restoreFromXml(XmlPullParser parser, int userId,
17413            String expectedStartTag, BlobXmlRestorer functor)
17414            throws IOException, XmlPullParserException {
17415        int type;
17416        while ((type = parser.next()) != XmlPullParser.START_TAG
17417                && type != XmlPullParser.END_DOCUMENT) {
17418        }
17419        if (type != XmlPullParser.START_TAG) {
17420            // oops didn't find a start tag?!
17421            if (DEBUG_BACKUP) {
17422                Slog.e(TAG, "Didn't find start tag during restore");
17423            }
17424            return;
17425        }
17426Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17427        // this is supposed to be TAG_PREFERRED_BACKUP
17428        if (!expectedStartTag.equals(parser.getName())) {
17429            if (DEBUG_BACKUP) {
17430                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17431            }
17432            return;
17433        }
17434
17435        // skip interfering stuff, then we're aligned with the backing implementation
17436        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17437Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17438        functor.apply(parser, userId);
17439    }
17440
17441    private interface BlobXmlRestorer {
17442        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17443    }
17444
17445    /**
17446     * Non-Binder method, support for the backup/restore mechanism: write the
17447     * full set of preferred activities in its canonical XML format.  Returns the
17448     * XML output as a byte array, or null if there is none.
17449     */
17450    @Override
17451    public byte[] getPreferredActivityBackup(int userId) {
17452        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17453            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17454        }
17455
17456        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17457        try {
17458            final XmlSerializer serializer = new FastXmlSerializer();
17459            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17460            serializer.startDocument(null, true);
17461            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17462
17463            synchronized (mPackages) {
17464                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17465            }
17466
17467            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17468            serializer.endDocument();
17469            serializer.flush();
17470        } catch (Exception e) {
17471            if (DEBUG_BACKUP) {
17472                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17473            }
17474            return null;
17475        }
17476
17477        return dataStream.toByteArray();
17478    }
17479
17480    @Override
17481    public void restorePreferredActivities(byte[] backup, int userId) {
17482        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17483            throw new SecurityException("Only the system may call restorePreferredActivities()");
17484        }
17485
17486        try {
17487            final XmlPullParser parser = Xml.newPullParser();
17488            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17489            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17490                    new BlobXmlRestorer() {
17491                        @Override
17492                        public void apply(XmlPullParser parser, int userId)
17493                                throws XmlPullParserException, IOException {
17494                            synchronized (mPackages) {
17495                                mSettings.readPreferredActivitiesLPw(parser, userId);
17496                            }
17497                        }
17498                    } );
17499        } catch (Exception e) {
17500            if (DEBUG_BACKUP) {
17501                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17502            }
17503        }
17504    }
17505
17506    /**
17507     * Non-Binder method, support for the backup/restore mechanism: write the
17508     * default browser (etc) settings in its canonical XML format.  Returns the default
17509     * browser XML representation as a byte array, or null if there is none.
17510     */
17511    @Override
17512    public byte[] getDefaultAppsBackup(int userId) {
17513        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17514            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17515        }
17516
17517        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17518        try {
17519            final XmlSerializer serializer = new FastXmlSerializer();
17520            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17521            serializer.startDocument(null, true);
17522            serializer.startTag(null, TAG_DEFAULT_APPS);
17523
17524            synchronized (mPackages) {
17525                mSettings.writeDefaultAppsLPr(serializer, userId);
17526            }
17527
17528            serializer.endTag(null, TAG_DEFAULT_APPS);
17529            serializer.endDocument();
17530            serializer.flush();
17531        } catch (Exception e) {
17532            if (DEBUG_BACKUP) {
17533                Slog.e(TAG, "Unable to write default apps for backup", e);
17534            }
17535            return null;
17536        }
17537
17538        return dataStream.toByteArray();
17539    }
17540
17541    @Override
17542    public void restoreDefaultApps(byte[] backup, int userId) {
17543        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17544            throw new SecurityException("Only the system may call restoreDefaultApps()");
17545        }
17546
17547        try {
17548            final XmlPullParser parser = Xml.newPullParser();
17549            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17550            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17551                    new BlobXmlRestorer() {
17552                        @Override
17553                        public void apply(XmlPullParser parser, int userId)
17554                                throws XmlPullParserException, IOException {
17555                            synchronized (mPackages) {
17556                                mSettings.readDefaultAppsLPw(parser, userId);
17557                            }
17558                        }
17559                    } );
17560        } catch (Exception e) {
17561            if (DEBUG_BACKUP) {
17562                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17563            }
17564        }
17565    }
17566
17567    @Override
17568    public byte[] getIntentFilterVerificationBackup(int userId) {
17569        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17570            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17571        }
17572
17573        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17574        try {
17575            final XmlSerializer serializer = new FastXmlSerializer();
17576            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17577            serializer.startDocument(null, true);
17578            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17579
17580            synchronized (mPackages) {
17581                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17582            }
17583
17584            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17585            serializer.endDocument();
17586            serializer.flush();
17587        } catch (Exception e) {
17588            if (DEBUG_BACKUP) {
17589                Slog.e(TAG, "Unable to write default apps for backup", e);
17590            }
17591            return null;
17592        }
17593
17594        return dataStream.toByteArray();
17595    }
17596
17597    @Override
17598    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17599        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17600            throw new SecurityException("Only the system may call restorePreferredActivities()");
17601        }
17602
17603        try {
17604            final XmlPullParser parser = Xml.newPullParser();
17605            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17606            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17607                    new BlobXmlRestorer() {
17608                        @Override
17609                        public void apply(XmlPullParser parser, int userId)
17610                                throws XmlPullParserException, IOException {
17611                            synchronized (mPackages) {
17612                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17613                                mSettings.writeLPr();
17614                            }
17615                        }
17616                    } );
17617        } catch (Exception e) {
17618            if (DEBUG_BACKUP) {
17619                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17620            }
17621        }
17622    }
17623
17624    @Override
17625    public byte[] getPermissionGrantBackup(int userId) {
17626        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17627            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17628        }
17629
17630        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17631        try {
17632            final XmlSerializer serializer = new FastXmlSerializer();
17633            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17634            serializer.startDocument(null, true);
17635            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17636
17637            synchronized (mPackages) {
17638                serializeRuntimePermissionGrantsLPr(serializer, userId);
17639            }
17640
17641            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17642            serializer.endDocument();
17643            serializer.flush();
17644        } catch (Exception e) {
17645            if (DEBUG_BACKUP) {
17646                Slog.e(TAG, "Unable to write default apps for backup", e);
17647            }
17648            return null;
17649        }
17650
17651        return dataStream.toByteArray();
17652    }
17653
17654    @Override
17655    public void restorePermissionGrants(byte[] backup, int userId) {
17656        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17657            throw new SecurityException("Only the system may call restorePermissionGrants()");
17658        }
17659
17660        try {
17661            final XmlPullParser parser = Xml.newPullParser();
17662            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17663            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17664                    new BlobXmlRestorer() {
17665                        @Override
17666                        public void apply(XmlPullParser parser, int userId)
17667                                throws XmlPullParserException, IOException {
17668                            synchronized (mPackages) {
17669                                processRestoredPermissionGrantsLPr(parser, userId);
17670                            }
17671                        }
17672                    } );
17673        } catch (Exception e) {
17674            if (DEBUG_BACKUP) {
17675                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17676            }
17677        }
17678    }
17679
17680    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17681            throws IOException {
17682        serializer.startTag(null, TAG_ALL_GRANTS);
17683
17684        final int N = mSettings.mPackages.size();
17685        for (int i = 0; i < N; i++) {
17686            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17687            boolean pkgGrantsKnown = false;
17688
17689            PermissionsState packagePerms = ps.getPermissionsState();
17690
17691            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17692                final int grantFlags = state.getFlags();
17693                // only look at grants that are not system/policy fixed
17694                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17695                    final boolean isGranted = state.isGranted();
17696                    // And only back up the user-twiddled state bits
17697                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17698                        final String packageName = mSettings.mPackages.keyAt(i);
17699                        if (!pkgGrantsKnown) {
17700                            serializer.startTag(null, TAG_GRANT);
17701                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17702                            pkgGrantsKnown = true;
17703                        }
17704
17705                        final boolean userSet =
17706                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17707                        final boolean userFixed =
17708                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17709                        final boolean revoke =
17710                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17711
17712                        serializer.startTag(null, TAG_PERMISSION);
17713                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17714                        if (isGranted) {
17715                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17716                        }
17717                        if (userSet) {
17718                            serializer.attribute(null, ATTR_USER_SET, "true");
17719                        }
17720                        if (userFixed) {
17721                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17722                        }
17723                        if (revoke) {
17724                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17725                        }
17726                        serializer.endTag(null, TAG_PERMISSION);
17727                    }
17728                }
17729            }
17730
17731            if (pkgGrantsKnown) {
17732                serializer.endTag(null, TAG_GRANT);
17733            }
17734        }
17735
17736        serializer.endTag(null, TAG_ALL_GRANTS);
17737    }
17738
17739    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17740            throws XmlPullParserException, IOException {
17741        String pkgName = null;
17742        int outerDepth = parser.getDepth();
17743        int type;
17744        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17745                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17746            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17747                continue;
17748            }
17749
17750            final String tagName = parser.getName();
17751            if (tagName.equals(TAG_GRANT)) {
17752                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17753                if (DEBUG_BACKUP) {
17754                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17755                }
17756            } else if (tagName.equals(TAG_PERMISSION)) {
17757
17758                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17759                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17760
17761                int newFlagSet = 0;
17762                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17763                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17764                }
17765                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17766                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17767                }
17768                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17769                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17770                }
17771                if (DEBUG_BACKUP) {
17772                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17773                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17774                }
17775                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17776                if (ps != null) {
17777                    // Already installed so we apply the grant immediately
17778                    if (DEBUG_BACKUP) {
17779                        Slog.v(TAG, "        + already installed; applying");
17780                    }
17781                    PermissionsState perms = ps.getPermissionsState();
17782                    BasePermission bp = mSettings.mPermissions.get(permName);
17783                    if (bp != null) {
17784                        if (isGranted) {
17785                            perms.grantRuntimePermission(bp, userId);
17786                        }
17787                        if (newFlagSet != 0) {
17788                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17789                        }
17790                    }
17791                } else {
17792                    // Need to wait for post-restore install to apply the grant
17793                    if (DEBUG_BACKUP) {
17794                        Slog.v(TAG, "        - not yet installed; saving for later");
17795                    }
17796                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17797                            isGranted, newFlagSet, userId);
17798                }
17799            } else {
17800                PackageManagerService.reportSettingsProblem(Log.WARN,
17801                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17802                XmlUtils.skipCurrentTag(parser);
17803            }
17804        }
17805
17806        scheduleWriteSettingsLocked();
17807        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17808    }
17809
17810    @Override
17811    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17812            int sourceUserId, int targetUserId, int flags) {
17813        mContext.enforceCallingOrSelfPermission(
17814                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17815        int callingUid = Binder.getCallingUid();
17816        enforceOwnerRights(ownerPackage, callingUid);
17817        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17818        if (intentFilter.countActions() == 0) {
17819            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17820            return;
17821        }
17822        synchronized (mPackages) {
17823            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17824                    ownerPackage, targetUserId, flags);
17825            CrossProfileIntentResolver resolver =
17826                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17827            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17828            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17829            if (existing != null) {
17830                int size = existing.size();
17831                for (int i = 0; i < size; i++) {
17832                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17833                        return;
17834                    }
17835                }
17836            }
17837            resolver.addFilter(newFilter);
17838            scheduleWritePackageRestrictionsLocked(sourceUserId);
17839        }
17840    }
17841
17842    @Override
17843    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17844        mContext.enforceCallingOrSelfPermission(
17845                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17846        int callingUid = Binder.getCallingUid();
17847        enforceOwnerRights(ownerPackage, callingUid);
17848        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17849        synchronized (mPackages) {
17850            CrossProfileIntentResolver resolver =
17851                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17852            ArraySet<CrossProfileIntentFilter> set =
17853                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17854            for (CrossProfileIntentFilter filter : set) {
17855                if (filter.getOwnerPackage().equals(ownerPackage)) {
17856                    resolver.removeFilter(filter);
17857                }
17858            }
17859            scheduleWritePackageRestrictionsLocked(sourceUserId);
17860        }
17861    }
17862
17863    // Enforcing that callingUid is owning pkg on userId
17864    private void enforceOwnerRights(String pkg, int callingUid) {
17865        // The system owns everything.
17866        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17867            return;
17868        }
17869        int callingUserId = UserHandle.getUserId(callingUid);
17870        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17871        if (pi == null) {
17872            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17873                    + callingUserId);
17874        }
17875        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17876            throw new SecurityException("Calling uid " + callingUid
17877                    + " does not own package " + pkg);
17878        }
17879    }
17880
17881    @Override
17882    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17883        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17884    }
17885
17886    private Intent getHomeIntent() {
17887        Intent intent = new Intent(Intent.ACTION_MAIN);
17888        intent.addCategory(Intent.CATEGORY_HOME);
17889        intent.addCategory(Intent.CATEGORY_DEFAULT);
17890        return intent;
17891    }
17892
17893    private IntentFilter getHomeFilter() {
17894        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17895        filter.addCategory(Intent.CATEGORY_HOME);
17896        filter.addCategory(Intent.CATEGORY_DEFAULT);
17897        return filter;
17898    }
17899
17900    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17901            int userId) {
17902        Intent intent  = getHomeIntent();
17903        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17904                PackageManager.GET_META_DATA, userId);
17905        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17906                true, false, false, userId);
17907
17908        allHomeCandidates.clear();
17909        if (list != null) {
17910            for (ResolveInfo ri : list) {
17911                allHomeCandidates.add(ri);
17912            }
17913        }
17914        return (preferred == null || preferred.activityInfo == null)
17915                ? null
17916                : new ComponentName(preferred.activityInfo.packageName,
17917                        preferred.activityInfo.name);
17918    }
17919
17920    @Override
17921    public void setHomeActivity(ComponentName comp, int userId) {
17922        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17923        getHomeActivitiesAsUser(homeActivities, userId);
17924
17925        boolean found = false;
17926
17927        final int size = homeActivities.size();
17928        final ComponentName[] set = new ComponentName[size];
17929        for (int i = 0; i < size; i++) {
17930            final ResolveInfo candidate = homeActivities.get(i);
17931            final ActivityInfo info = candidate.activityInfo;
17932            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17933            set[i] = activityName;
17934            if (!found && activityName.equals(comp)) {
17935                found = true;
17936            }
17937        }
17938        if (!found) {
17939            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17940                    + userId);
17941        }
17942        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17943                set, comp, userId);
17944    }
17945
17946    private @Nullable String getSetupWizardPackageName() {
17947        final Intent intent = new Intent(Intent.ACTION_MAIN);
17948        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17949
17950        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17951                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17952                        | MATCH_DISABLED_COMPONENTS,
17953                UserHandle.myUserId());
17954        if (matches.size() == 1) {
17955            return matches.get(0).getComponentInfo().packageName;
17956        } else {
17957            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17958                    + ": matches=" + matches);
17959            return null;
17960        }
17961    }
17962
17963    private @Nullable String getStorageManagerPackageName() {
17964        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17965
17966        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17967                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17968                        | MATCH_DISABLED_COMPONENTS,
17969                UserHandle.myUserId());
17970        if (matches.size() == 1) {
17971            return matches.get(0).getComponentInfo().packageName;
17972        } else {
17973            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17974                    + matches.size() + ": matches=" + matches);
17975            return null;
17976        }
17977    }
17978
17979    @Override
17980    public void setApplicationEnabledSetting(String appPackageName,
17981            int newState, int flags, int userId, String callingPackage) {
17982        if (!sUserManager.exists(userId)) return;
17983        if (callingPackage == null) {
17984            callingPackage = Integer.toString(Binder.getCallingUid());
17985        }
17986        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17987    }
17988
17989    @Override
17990    public void setComponentEnabledSetting(ComponentName componentName,
17991            int newState, int flags, int userId) {
17992        if (!sUserManager.exists(userId)) return;
17993        setEnabledSetting(componentName.getPackageName(),
17994                componentName.getClassName(), newState, flags, userId, null);
17995    }
17996
17997    private void setEnabledSetting(final String packageName, String className, int newState,
17998            final int flags, int userId, String callingPackage) {
17999        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18000              || newState == COMPONENT_ENABLED_STATE_ENABLED
18001              || newState == COMPONENT_ENABLED_STATE_DISABLED
18002              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18003              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18004            throw new IllegalArgumentException("Invalid new component state: "
18005                    + newState);
18006        }
18007        PackageSetting pkgSetting;
18008        final int uid = Binder.getCallingUid();
18009        final int permission;
18010        if (uid == Process.SYSTEM_UID) {
18011            permission = PackageManager.PERMISSION_GRANTED;
18012        } else {
18013            permission = mContext.checkCallingOrSelfPermission(
18014                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18015        }
18016        enforceCrossUserPermission(uid, userId,
18017                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18018        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18019        boolean sendNow = false;
18020        boolean isApp = (className == null);
18021        String componentName = isApp ? packageName : className;
18022        int packageUid = -1;
18023        ArrayList<String> components;
18024
18025        // writer
18026        synchronized (mPackages) {
18027            pkgSetting = mSettings.mPackages.get(packageName);
18028            if (pkgSetting == null) {
18029                if (className == null) {
18030                    throw new IllegalArgumentException("Unknown package: " + packageName);
18031                }
18032                throw new IllegalArgumentException(
18033                        "Unknown component: " + packageName + "/" + className);
18034            }
18035        }
18036
18037        // Limit who can change which apps
18038        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18039            // Don't allow apps that don't have permission to modify other apps
18040            if (!allowedByPermission) {
18041                throw new SecurityException(
18042                        "Permission Denial: attempt to change component state from pid="
18043                        + Binder.getCallingPid()
18044                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18045            }
18046            // Don't allow changing protected packages.
18047            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18048                throw new SecurityException("Cannot disable a protected package: " + packageName);
18049            }
18050        }
18051
18052        synchronized (mPackages) {
18053            if (uid == Process.SHELL_UID) {
18054                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18055                int oldState = pkgSetting.getEnabled(userId);
18056                if (className == null
18057                    &&
18058                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18059                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18060                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18061                    &&
18062                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18063                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18064                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18065                    // ok
18066                } else {
18067                    throw new SecurityException(
18068                            "Shell cannot change component state for " + packageName + "/"
18069                            + className + " to " + newState);
18070                }
18071            }
18072            if (className == null) {
18073                // We're dealing with an application/package level state change
18074                if (pkgSetting.getEnabled(userId) == newState) {
18075                    // Nothing to do
18076                    return;
18077                }
18078                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18079                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18080                    // Don't care about who enables an app.
18081                    callingPackage = null;
18082                }
18083                pkgSetting.setEnabled(newState, userId, callingPackage);
18084                // pkgSetting.pkg.mSetEnabled = newState;
18085            } else {
18086                // We're dealing with a component level state change
18087                // First, verify that this is a valid class name.
18088                PackageParser.Package pkg = pkgSetting.pkg;
18089                if (pkg == null || !pkg.hasComponentClassName(className)) {
18090                    if (pkg != null &&
18091                            pkg.applicationInfo.targetSdkVersion >=
18092                                    Build.VERSION_CODES.JELLY_BEAN) {
18093                        throw new IllegalArgumentException("Component class " + className
18094                                + " does not exist in " + packageName);
18095                    } else {
18096                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18097                                + className + " does not exist in " + packageName);
18098                    }
18099                }
18100                switch (newState) {
18101                case COMPONENT_ENABLED_STATE_ENABLED:
18102                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18103                        return;
18104                    }
18105                    break;
18106                case COMPONENT_ENABLED_STATE_DISABLED:
18107                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18108                        return;
18109                    }
18110                    break;
18111                case COMPONENT_ENABLED_STATE_DEFAULT:
18112                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18113                        return;
18114                    }
18115                    break;
18116                default:
18117                    Slog.e(TAG, "Invalid new component state: " + newState);
18118                    return;
18119                }
18120            }
18121            scheduleWritePackageRestrictionsLocked(userId);
18122            components = mPendingBroadcasts.get(userId, packageName);
18123            final boolean newPackage = components == null;
18124            if (newPackage) {
18125                components = new ArrayList<String>();
18126            }
18127            if (!components.contains(componentName)) {
18128                components.add(componentName);
18129            }
18130            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18131                sendNow = true;
18132                // Purge entry from pending broadcast list if another one exists already
18133                // since we are sending one right away.
18134                mPendingBroadcasts.remove(userId, packageName);
18135            } else {
18136                if (newPackage) {
18137                    mPendingBroadcasts.put(userId, packageName, components);
18138                }
18139                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18140                    // Schedule a message
18141                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18142                }
18143            }
18144        }
18145
18146        long callingId = Binder.clearCallingIdentity();
18147        try {
18148            if (sendNow) {
18149                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18150                sendPackageChangedBroadcast(packageName,
18151                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18152            }
18153        } finally {
18154            Binder.restoreCallingIdentity(callingId);
18155        }
18156    }
18157
18158    @Override
18159    public void flushPackageRestrictionsAsUser(int userId) {
18160        if (!sUserManager.exists(userId)) {
18161            return;
18162        }
18163        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18164                false /* checkShell */, "flushPackageRestrictions");
18165        synchronized (mPackages) {
18166            mSettings.writePackageRestrictionsLPr(userId);
18167            mDirtyUsers.remove(userId);
18168            if (mDirtyUsers.isEmpty()) {
18169                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18170            }
18171        }
18172    }
18173
18174    private void sendPackageChangedBroadcast(String packageName,
18175            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18176        if (DEBUG_INSTALL)
18177            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18178                    + componentNames);
18179        Bundle extras = new Bundle(4);
18180        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18181        String nameList[] = new String[componentNames.size()];
18182        componentNames.toArray(nameList);
18183        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18184        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18185        extras.putInt(Intent.EXTRA_UID, packageUid);
18186        // If this is not reporting a change of the overall package, then only send it
18187        // to registered receivers.  We don't want to launch a swath of apps for every
18188        // little component state change.
18189        final int flags = !componentNames.contains(packageName)
18190                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18191        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18192                new int[] {UserHandle.getUserId(packageUid)});
18193    }
18194
18195    @Override
18196    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18197        if (!sUserManager.exists(userId)) return;
18198        final int uid = Binder.getCallingUid();
18199        final int permission = mContext.checkCallingOrSelfPermission(
18200                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18201        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18202        enforceCrossUserPermission(uid, userId,
18203                true /* requireFullPermission */, true /* checkShell */, "stop package");
18204        // writer
18205        synchronized (mPackages) {
18206            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18207                    allowedByPermission, uid, userId)) {
18208                scheduleWritePackageRestrictionsLocked(userId);
18209            }
18210        }
18211    }
18212
18213    @Override
18214    public String getInstallerPackageName(String packageName) {
18215        // reader
18216        synchronized (mPackages) {
18217            return mSettings.getInstallerPackageNameLPr(packageName);
18218        }
18219    }
18220
18221    public boolean isOrphaned(String packageName) {
18222        // reader
18223        synchronized (mPackages) {
18224            return mSettings.isOrphaned(packageName);
18225        }
18226    }
18227
18228    @Override
18229    public int getApplicationEnabledSetting(String packageName, int userId) {
18230        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18231        int uid = Binder.getCallingUid();
18232        enforceCrossUserPermission(uid, userId,
18233                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18234        // reader
18235        synchronized (mPackages) {
18236            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18237        }
18238    }
18239
18240    @Override
18241    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18242        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18243        int uid = Binder.getCallingUid();
18244        enforceCrossUserPermission(uid, userId,
18245                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18246        // reader
18247        synchronized (mPackages) {
18248            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18249        }
18250    }
18251
18252    @Override
18253    public void enterSafeMode() {
18254        enforceSystemOrRoot("Only the system can request entering safe mode");
18255
18256        if (!mSystemReady) {
18257            mSafeMode = true;
18258        }
18259    }
18260
18261    @Override
18262    public void systemReady() {
18263        mSystemReady = true;
18264
18265        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18266        // disabled after already being started.
18267        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18268                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18269
18270        // Read the compatibilty setting when the system is ready.
18271        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18272                mContext.getContentResolver(),
18273                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18274        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18275        if (DEBUG_SETTINGS) {
18276            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18277        }
18278
18279        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18280
18281        synchronized (mPackages) {
18282            // Verify that all of the preferred activity components actually
18283            // exist.  It is possible for applications to be updated and at
18284            // that point remove a previously declared activity component that
18285            // had been set as a preferred activity.  We try to clean this up
18286            // the next time we encounter that preferred activity, but it is
18287            // possible for the user flow to never be able to return to that
18288            // situation so here we do a sanity check to make sure we haven't
18289            // left any junk around.
18290            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18291            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18292                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18293                removed.clear();
18294                for (PreferredActivity pa : pir.filterSet()) {
18295                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18296                        removed.add(pa);
18297                    }
18298                }
18299                if (removed.size() > 0) {
18300                    for (int r=0; r<removed.size(); r++) {
18301                        PreferredActivity pa = removed.get(r);
18302                        Slog.w(TAG, "Removing dangling preferred activity: "
18303                                + pa.mPref.mComponent);
18304                        pir.removeFilter(pa);
18305                    }
18306                    mSettings.writePackageRestrictionsLPr(
18307                            mSettings.mPreferredActivities.keyAt(i));
18308                }
18309            }
18310
18311            for (int userId : UserManagerService.getInstance().getUserIds()) {
18312                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18313                    grantPermissionsUserIds = ArrayUtils.appendInt(
18314                            grantPermissionsUserIds, userId);
18315                }
18316            }
18317        }
18318        sUserManager.systemReady();
18319
18320        // If we upgraded grant all default permissions before kicking off.
18321        for (int userId : grantPermissionsUserIds) {
18322            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18323        }
18324
18325        // If we did not grant default permissions, we preload from this the
18326        // default permission exceptions lazily to ensure we don't hit the
18327        // disk on a new user creation.
18328        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18329            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18330        }
18331
18332        // Kick off any messages waiting for system ready
18333        if (mPostSystemReadyMessages != null) {
18334            for (Message msg : mPostSystemReadyMessages) {
18335                msg.sendToTarget();
18336            }
18337            mPostSystemReadyMessages = null;
18338        }
18339
18340        // Watch for external volumes that come and go over time
18341        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18342        storage.registerListener(mStorageListener);
18343
18344        mInstallerService.systemReady();
18345        mPackageDexOptimizer.systemReady();
18346
18347        MountServiceInternal mountServiceInternal = LocalServices.getService(
18348                MountServiceInternal.class);
18349        mountServiceInternal.addExternalStoragePolicy(
18350                new MountServiceInternal.ExternalStorageMountPolicy() {
18351            @Override
18352            public int getMountMode(int uid, String packageName) {
18353                if (Process.isIsolated(uid)) {
18354                    return Zygote.MOUNT_EXTERNAL_NONE;
18355                }
18356                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18357                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18358                }
18359                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18360                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18361                }
18362                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18363                    return Zygote.MOUNT_EXTERNAL_READ;
18364                }
18365                return Zygote.MOUNT_EXTERNAL_WRITE;
18366            }
18367
18368            @Override
18369            public boolean hasExternalStorage(int uid, String packageName) {
18370                return true;
18371            }
18372        });
18373
18374        // Now that we're mostly running, clean up stale users and apps
18375        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18376        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18377    }
18378
18379    @Override
18380    public boolean isSafeMode() {
18381        return mSafeMode;
18382    }
18383
18384    @Override
18385    public boolean hasSystemUidErrors() {
18386        return mHasSystemUidErrors;
18387    }
18388
18389    static String arrayToString(int[] array) {
18390        StringBuffer buf = new StringBuffer(128);
18391        buf.append('[');
18392        if (array != null) {
18393            for (int i=0; i<array.length; i++) {
18394                if (i > 0) buf.append(", ");
18395                buf.append(array[i]);
18396            }
18397        }
18398        buf.append(']');
18399        return buf.toString();
18400    }
18401
18402    static class DumpState {
18403        public static final int DUMP_LIBS = 1 << 0;
18404        public static final int DUMP_FEATURES = 1 << 1;
18405        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18406        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18407        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18408        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18409        public static final int DUMP_PERMISSIONS = 1 << 6;
18410        public static final int DUMP_PACKAGES = 1 << 7;
18411        public static final int DUMP_SHARED_USERS = 1 << 8;
18412        public static final int DUMP_MESSAGES = 1 << 9;
18413        public static final int DUMP_PROVIDERS = 1 << 10;
18414        public static final int DUMP_VERIFIERS = 1 << 11;
18415        public static final int DUMP_PREFERRED = 1 << 12;
18416        public static final int DUMP_PREFERRED_XML = 1 << 13;
18417        public static final int DUMP_KEYSETS = 1 << 14;
18418        public static final int DUMP_VERSION = 1 << 15;
18419        public static final int DUMP_INSTALLS = 1 << 16;
18420        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18421        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18422        public static final int DUMP_FROZEN = 1 << 19;
18423        public static final int DUMP_DEXOPT = 1 << 20;
18424        public static final int DUMP_COMPILER_STATS = 1 << 21;
18425
18426        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18427
18428        private int mTypes;
18429
18430        private int mOptions;
18431
18432        private boolean mTitlePrinted;
18433
18434        private SharedUserSetting mSharedUser;
18435
18436        public boolean isDumping(int type) {
18437            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18438                return true;
18439            }
18440
18441            return (mTypes & type) != 0;
18442        }
18443
18444        public void setDump(int type) {
18445            mTypes |= type;
18446        }
18447
18448        public boolean isOptionEnabled(int option) {
18449            return (mOptions & option) != 0;
18450        }
18451
18452        public void setOptionEnabled(int option) {
18453            mOptions |= option;
18454        }
18455
18456        public boolean onTitlePrinted() {
18457            final boolean printed = mTitlePrinted;
18458            mTitlePrinted = true;
18459            return printed;
18460        }
18461
18462        public boolean getTitlePrinted() {
18463            return mTitlePrinted;
18464        }
18465
18466        public void setTitlePrinted(boolean enabled) {
18467            mTitlePrinted = enabled;
18468        }
18469
18470        public SharedUserSetting getSharedUser() {
18471            return mSharedUser;
18472        }
18473
18474        public void setSharedUser(SharedUserSetting user) {
18475            mSharedUser = user;
18476        }
18477    }
18478
18479    @Override
18480    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18481            FileDescriptor err, String[] args, ShellCallback callback,
18482            ResultReceiver resultReceiver) {
18483        (new PackageManagerShellCommand(this)).exec(
18484                this, in, out, err, args, callback, resultReceiver);
18485    }
18486
18487    @Override
18488    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18489        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18490                != PackageManager.PERMISSION_GRANTED) {
18491            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18492                    + Binder.getCallingPid()
18493                    + ", uid=" + Binder.getCallingUid()
18494                    + " without permission "
18495                    + android.Manifest.permission.DUMP);
18496            return;
18497        }
18498
18499        DumpState dumpState = new DumpState();
18500        boolean fullPreferred = false;
18501        boolean checkin = false;
18502
18503        String packageName = null;
18504        ArraySet<String> permissionNames = null;
18505
18506        int opti = 0;
18507        while (opti < args.length) {
18508            String opt = args[opti];
18509            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18510                break;
18511            }
18512            opti++;
18513
18514            if ("-a".equals(opt)) {
18515                // Right now we only know how to print all.
18516            } else if ("-h".equals(opt)) {
18517                pw.println("Package manager dump options:");
18518                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18519                pw.println("    --checkin: dump for a checkin");
18520                pw.println("    -f: print details of intent filters");
18521                pw.println("    -h: print this help");
18522                pw.println("  cmd may be one of:");
18523                pw.println("    l[ibraries]: list known shared libraries");
18524                pw.println("    f[eatures]: list device features");
18525                pw.println("    k[eysets]: print known keysets");
18526                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18527                pw.println("    perm[issions]: dump permissions");
18528                pw.println("    permission [name ...]: dump declaration and use of given permission");
18529                pw.println("    pref[erred]: print preferred package settings");
18530                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18531                pw.println("    prov[iders]: dump content providers");
18532                pw.println("    p[ackages]: dump installed packages");
18533                pw.println("    s[hared-users]: dump shared user IDs");
18534                pw.println("    m[essages]: print collected runtime messages");
18535                pw.println("    v[erifiers]: print package verifier info");
18536                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18537                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18538                pw.println("    version: print database version info");
18539                pw.println("    write: write current settings now");
18540                pw.println("    installs: details about install sessions");
18541                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18542                pw.println("    dexopt: dump dexopt state");
18543                pw.println("    compiler-stats: dump compiler statistics");
18544                pw.println("    <package.name>: info about given package");
18545                return;
18546            } else if ("--checkin".equals(opt)) {
18547                checkin = true;
18548            } else if ("-f".equals(opt)) {
18549                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18550            } else {
18551                pw.println("Unknown argument: " + opt + "; use -h for help");
18552            }
18553        }
18554
18555        // Is the caller requesting to dump a particular piece of data?
18556        if (opti < args.length) {
18557            String cmd = args[opti];
18558            opti++;
18559            // Is this a package name?
18560            if ("android".equals(cmd) || cmd.contains(".")) {
18561                packageName = cmd;
18562                // When dumping a single package, we always dump all of its
18563                // filter information since the amount of data will be reasonable.
18564                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18565            } else if ("check-permission".equals(cmd)) {
18566                if (opti >= args.length) {
18567                    pw.println("Error: check-permission missing permission argument");
18568                    return;
18569                }
18570                String perm = args[opti];
18571                opti++;
18572                if (opti >= args.length) {
18573                    pw.println("Error: check-permission missing package argument");
18574                    return;
18575                }
18576                String pkg = args[opti];
18577                opti++;
18578                int user = UserHandle.getUserId(Binder.getCallingUid());
18579                if (opti < args.length) {
18580                    try {
18581                        user = Integer.parseInt(args[opti]);
18582                    } catch (NumberFormatException e) {
18583                        pw.println("Error: check-permission user argument is not a number: "
18584                                + args[opti]);
18585                        return;
18586                    }
18587                }
18588                pw.println(checkPermission(perm, pkg, user));
18589                return;
18590            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18591                dumpState.setDump(DumpState.DUMP_LIBS);
18592            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18593                dumpState.setDump(DumpState.DUMP_FEATURES);
18594            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18595                if (opti >= args.length) {
18596                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18597                            | DumpState.DUMP_SERVICE_RESOLVERS
18598                            | DumpState.DUMP_RECEIVER_RESOLVERS
18599                            | DumpState.DUMP_CONTENT_RESOLVERS);
18600                } else {
18601                    while (opti < args.length) {
18602                        String name = args[opti];
18603                        if ("a".equals(name) || "activity".equals(name)) {
18604                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18605                        } else if ("s".equals(name) || "service".equals(name)) {
18606                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18607                        } else if ("r".equals(name) || "receiver".equals(name)) {
18608                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18609                        } else if ("c".equals(name) || "content".equals(name)) {
18610                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18611                        } else {
18612                            pw.println("Error: unknown resolver table type: " + name);
18613                            return;
18614                        }
18615                        opti++;
18616                    }
18617                }
18618            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18619                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18620            } else if ("permission".equals(cmd)) {
18621                if (opti >= args.length) {
18622                    pw.println("Error: permission requires permission name");
18623                    return;
18624                }
18625                permissionNames = new ArraySet<>();
18626                while (opti < args.length) {
18627                    permissionNames.add(args[opti]);
18628                    opti++;
18629                }
18630                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18631                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18632            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18633                dumpState.setDump(DumpState.DUMP_PREFERRED);
18634            } else if ("preferred-xml".equals(cmd)) {
18635                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18636                if (opti < args.length && "--full".equals(args[opti])) {
18637                    fullPreferred = true;
18638                    opti++;
18639                }
18640            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18641                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18642            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18643                dumpState.setDump(DumpState.DUMP_PACKAGES);
18644            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18645                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18646            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18647                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18648            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18649                dumpState.setDump(DumpState.DUMP_MESSAGES);
18650            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18651                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18652            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18653                    || "intent-filter-verifiers".equals(cmd)) {
18654                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18655            } else if ("version".equals(cmd)) {
18656                dumpState.setDump(DumpState.DUMP_VERSION);
18657            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18658                dumpState.setDump(DumpState.DUMP_KEYSETS);
18659            } else if ("installs".equals(cmd)) {
18660                dumpState.setDump(DumpState.DUMP_INSTALLS);
18661            } else if ("frozen".equals(cmd)) {
18662                dumpState.setDump(DumpState.DUMP_FROZEN);
18663            } else if ("dexopt".equals(cmd)) {
18664                dumpState.setDump(DumpState.DUMP_DEXOPT);
18665            } else if ("compiler-stats".equals(cmd)) {
18666                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18667            } else if ("write".equals(cmd)) {
18668                synchronized (mPackages) {
18669                    mSettings.writeLPr();
18670                    pw.println("Settings written.");
18671                    return;
18672                }
18673            }
18674        }
18675
18676        if (checkin) {
18677            pw.println("vers,1");
18678        }
18679
18680        // reader
18681        synchronized (mPackages) {
18682            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18683                if (!checkin) {
18684                    if (dumpState.onTitlePrinted())
18685                        pw.println();
18686                    pw.println("Database versions:");
18687                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18688                }
18689            }
18690
18691            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18692                if (!checkin) {
18693                    if (dumpState.onTitlePrinted())
18694                        pw.println();
18695                    pw.println("Verifiers:");
18696                    pw.print("  Required: ");
18697                    pw.print(mRequiredVerifierPackage);
18698                    pw.print(" (uid=");
18699                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18700                            UserHandle.USER_SYSTEM));
18701                    pw.println(")");
18702                } else if (mRequiredVerifierPackage != null) {
18703                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18704                    pw.print(",");
18705                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18706                            UserHandle.USER_SYSTEM));
18707                }
18708            }
18709
18710            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18711                    packageName == null) {
18712                if (mIntentFilterVerifierComponent != null) {
18713                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18714                    if (!checkin) {
18715                        if (dumpState.onTitlePrinted())
18716                            pw.println();
18717                        pw.println("Intent Filter Verifier:");
18718                        pw.print("  Using: ");
18719                        pw.print(verifierPackageName);
18720                        pw.print(" (uid=");
18721                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18722                                UserHandle.USER_SYSTEM));
18723                        pw.println(")");
18724                    } else if (verifierPackageName != null) {
18725                        pw.print("ifv,"); pw.print(verifierPackageName);
18726                        pw.print(",");
18727                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18728                                UserHandle.USER_SYSTEM));
18729                    }
18730                } else {
18731                    pw.println();
18732                    pw.println("No Intent Filter Verifier available!");
18733                }
18734            }
18735
18736            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18737                boolean printedHeader = false;
18738                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18739                while (it.hasNext()) {
18740                    String name = it.next();
18741                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18742                    if (!checkin) {
18743                        if (!printedHeader) {
18744                            if (dumpState.onTitlePrinted())
18745                                pw.println();
18746                            pw.println("Libraries:");
18747                            printedHeader = true;
18748                        }
18749                        pw.print("  ");
18750                    } else {
18751                        pw.print("lib,");
18752                    }
18753                    pw.print(name);
18754                    if (!checkin) {
18755                        pw.print(" -> ");
18756                    }
18757                    if (ent.path != null) {
18758                        if (!checkin) {
18759                            pw.print("(jar) ");
18760                            pw.print(ent.path);
18761                        } else {
18762                            pw.print(",jar,");
18763                            pw.print(ent.path);
18764                        }
18765                    } else {
18766                        if (!checkin) {
18767                            pw.print("(apk) ");
18768                            pw.print(ent.apk);
18769                        } else {
18770                            pw.print(",apk,");
18771                            pw.print(ent.apk);
18772                        }
18773                    }
18774                    pw.println();
18775                }
18776            }
18777
18778            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18779                if (dumpState.onTitlePrinted())
18780                    pw.println();
18781                if (!checkin) {
18782                    pw.println("Features:");
18783                }
18784
18785                for (FeatureInfo feat : mAvailableFeatures.values()) {
18786                    if (checkin) {
18787                        pw.print("feat,");
18788                        pw.print(feat.name);
18789                        pw.print(",");
18790                        pw.println(feat.version);
18791                    } else {
18792                        pw.print("  ");
18793                        pw.print(feat.name);
18794                        if (feat.version > 0) {
18795                            pw.print(" version=");
18796                            pw.print(feat.version);
18797                        }
18798                        pw.println();
18799                    }
18800                }
18801            }
18802
18803            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18804                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18805                        : "Activity Resolver Table:", "  ", packageName,
18806                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18807                    dumpState.setTitlePrinted(true);
18808                }
18809            }
18810            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18811                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18812                        : "Receiver Resolver Table:", "  ", packageName,
18813                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18814                    dumpState.setTitlePrinted(true);
18815                }
18816            }
18817            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18818                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18819                        : "Service Resolver Table:", "  ", packageName,
18820                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18821                    dumpState.setTitlePrinted(true);
18822                }
18823            }
18824            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18825                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18826                        : "Provider Resolver Table:", "  ", packageName,
18827                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18828                    dumpState.setTitlePrinted(true);
18829                }
18830            }
18831
18832            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18833                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18834                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18835                    int user = mSettings.mPreferredActivities.keyAt(i);
18836                    if (pir.dump(pw,
18837                            dumpState.getTitlePrinted()
18838                                ? "\nPreferred Activities User " + user + ":"
18839                                : "Preferred Activities User " + user + ":", "  ",
18840                            packageName, true, false)) {
18841                        dumpState.setTitlePrinted(true);
18842                    }
18843                }
18844            }
18845
18846            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18847                pw.flush();
18848                FileOutputStream fout = new FileOutputStream(fd);
18849                BufferedOutputStream str = new BufferedOutputStream(fout);
18850                XmlSerializer serializer = new FastXmlSerializer();
18851                try {
18852                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18853                    serializer.startDocument(null, true);
18854                    serializer.setFeature(
18855                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18856                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18857                    serializer.endDocument();
18858                    serializer.flush();
18859                } catch (IllegalArgumentException e) {
18860                    pw.println("Failed writing: " + e);
18861                } catch (IllegalStateException e) {
18862                    pw.println("Failed writing: " + e);
18863                } catch (IOException e) {
18864                    pw.println("Failed writing: " + e);
18865                }
18866            }
18867
18868            if (!checkin
18869                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18870                    && packageName == null) {
18871                pw.println();
18872                int count = mSettings.mPackages.size();
18873                if (count == 0) {
18874                    pw.println("No applications!");
18875                    pw.println();
18876                } else {
18877                    final String prefix = "  ";
18878                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18879                    if (allPackageSettings.size() == 0) {
18880                        pw.println("No domain preferred apps!");
18881                        pw.println();
18882                    } else {
18883                        pw.println("App verification status:");
18884                        pw.println();
18885                        count = 0;
18886                        for (PackageSetting ps : allPackageSettings) {
18887                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18888                            if (ivi == null || ivi.getPackageName() == null) continue;
18889                            pw.println(prefix + "Package: " + ivi.getPackageName());
18890                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18891                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18892                            pw.println();
18893                            count++;
18894                        }
18895                        if (count == 0) {
18896                            pw.println(prefix + "No app verification established.");
18897                            pw.println();
18898                        }
18899                        for (int userId : sUserManager.getUserIds()) {
18900                            pw.println("App linkages for user " + userId + ":");
18901                            pw.println();
18902                            count = 0;
18903                            for (PackageSetting ps : allPackageSettings) {
18904                                final long status = ps.getDomainVerificationStatusForUser(userId);
18905                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18906                                    continue;
18907                                }
18908                                pw.println(prefix + "Package: " + ps.name);
18909                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18910                                String statusStr = IntentFilterVerificationInfo.
18911                                        getStatusStringFromValue(status);
18912                                pw.println(prefix + "Status:  " + statusStr);
18913                                pw.println();
18914                                count++;
18915                            }
18916                            if (count == 0) {
18917                                pw.println(prefix + "No configured app linkages.");
18918                                pw.println();
18919                            }
18920                        }
18921                    }
18922                }
18923            }
18924
18925            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18926                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18927                if (packageName == null && permissionNames == null) {
18928                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18929                        if (iperm == 0) {
18930                            if (dumpState.onTitlePrinted())
18931                                pw.println();
18932                            pw.println("AppOp Permissions:");
18933                        }
18934                        pw.print("  AppOp Permission ");
18935                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18936                        pw.println(":");
18937                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18938                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18939                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18940                        }
18941                    }
18942                }
18943            }
18944
18945            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18946                boolean printedSomething = false;
18947                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18948                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18949                        continue;
18950                    }
18951                    if (!printedSomething) {
18952                        if (dumpState.onTitlePrinted())
18953                            pw.println();
18954                        pw.println("Registered ContentProviders:");
18955                        printedSomething = true;
18956                    }
18957                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18958                    pw.print("    "); pw.println(p.toString());
18959                }
18960                printedSomething = false;
18961                for (Map.Entry<String, PackageParser.Provider> entry :
18962                        mProvidersByAuthority.entrySet()) {
18963                    PackageParser.Provider p = entry.getValue();
18964                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18965                        continue;
18966                    }
18967                    if (!printedSomething) {
18968                        if (dumpState.onTitlePrinted())
18969                            pw.println();
18970                        pw.println("ContentProvider Authorities:");
18971                        printedSomething = true;
18972                    }
18973                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18974                    pw.print("    "); pw.println(p.toString());
18975                    if (p.info != null && p.info.applicationInfo != null) {
18976                        final String appInfo = p.info.applicationInfo.toString();
18977                        pw.print("      applicationInfo="); pw.println(appInfo);
18978                    }
18979                }
18980            }
18981
18982            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18983                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18984            }
18985
18986            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18987                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18988            }
18989
18990            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18991                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18992            }
18993
18994            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18995                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18996            }
18997
18998            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && 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                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19003            }
19004
19005            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19006                // XXX should handle packageName != null by dumping only install data that
19007                // the given package is involved with.
19008                if (dumpState.onTitlePrinted()) pw.println();
19009
19010                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19011                ipw.println();
19012                ipw.println("Frozen packages:");
19013                ipw.increaseIndent();
19014                if (mFrozenPackages.size() == 0) {
19015                    ipw.println("(none)");
19016                } else {
19017                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19018                        ipw.println(mFrozenPackages.valueAt(i));
19019                    }
19020                }
19021                ipw.decreaseIndent();
19022            }
19023
19024            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19025                if (dumpState.onTitlePrinted()) pw.println();
19026                dumpDexoptStateLPr(pw, packageName);
19027            }
19028
19029            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19030                if (dumpState.onTitlePrinted()) pw.println();
19031                dumpCompilerStatsLPr(pw, packageName);
19032            }
19033
19034            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19035                if (dumpState.onTitlePrinted()) pw.println();
19036                mSettings.dumpReadMessagesLPr(pw, dumpState);
19037
19038                pw.println();
19039                pw.println("Package warning messages:");
19040                BufferedReader in = null;
19041                String line = null;
19042                try {
19043                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19044                    while ((line = in.readLine()) != null) {
19045                        if (line.contains("ignored: updated version")) continue;
19046                        pw.println(line);
19047                    }
19048                } catch (IOException ignored) {
19049                } finally {
19050                    IoUtils.closeQuietly(in);
19051                }
19052            }
19053
19054            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19055                BufferedReader in = null;
19056                String line = null;
19057                try {
19058                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19059                    while ((line = in.readLine()) != null) {
19060                        if (line.contains("ignored: updated version")) continue;
19061                        pw.print("msg,");
19062                        pw.println(line);
19063                    }
19064                } catch (IOException ignored) {
19065                } finally {
19066                    IoUtils.closeQuietly(in);
19067                }
19068            }
19069        }
19070    }
19071
19072    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19073        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19074        ipw.println();
19075        ipw.println("Dexopt state:");
19076        ipw.increaseIndent();
19077        Collection<PackageParser.Package> packages = null;
19078        if (packageName != null) {
19079            PackageParser.Package targetPackage = mPackages.get(packageName);
19080            if (targetPackage != null) {
19081                packages = Collections.singletonList(targetPackage);
19082            } else {
19083                ipw.println("Unable to find package: " + packageName);
19084                return;
19085            }
19086        } else {
19087            packages = mPackages.values();
19088        }
19089
19090        for (PackageParser.Package pkg : packages) {
19091            ipw.println("[" + pkg.packageName + "]");
19092            ipw.increaseIndent();
19093            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19094            ipw.decreaseIndent();
19095        }
19096    }
19097
19098    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19099        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19100        ipw.println();
19101        ipw.println("Compiler stats:");
19102        ipw.increaseIndent();
19103        Collection<PackageParser.Package> packages = null;
19104        if (packageName != null) {
19105            PackageParser.Package targetPackage = mPackages.get(packageName);
19106            if (targetPackage != null) {
19107                packages = Collections.singletonList(targetPackage);
19108            } else {
19109                ipw.println("Unable to find package: " + packageName);
19110                return;
19111            }
19112        } else {
19113            packages = mPackages.values();
19114        }
19115
19116        for (PackageParser.Package pkg : packages) {
19117            ipw.println("[" + pkg.packageName + "]");
19118            ipw.increaseIndent();
19119
19120            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19121            if (stats == null) {
19122                ipw.println("(No recorded stats)");
19123            } else {
19124                stats.dump(ipw);
19125            }
19126            ipw.decreaseIndent();
19127        }
19128    }
19129
19130    private String dumpDomainString(String packageName) {
19131        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19132                .getList();
19133        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19134
19135        ArraySet<String> result = new ArraySet<>();
19136        if (iviList.size() > 0) {
19137            for (IntentFilterVerificationInfo ivi : iviList) {
19138                for (String host : ivi.getDomains()) {
19139                    result.add(host);
19140                }
19141            }
19142        }
19143        if (filters != null && filters.size() > 0) {
19144            for (IntentFilter filter : filters) {
19145                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19146                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19147                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19148                    result.addAll(filter.getHostsList());
19149                }
19150            }
19151        }
19152
19153        StringBuilder sb = new StringBuilder(result.size() * 16);
19154        for (String domain : result) {
19155            if (sb.length() > 0) sb.append(" ");
19156            sb.append(domain);
19157        }
19158        return sb.toString();
19159    }
19160
19161    // ------- apps on sdcard specific code -------
19162    static final boolean DEBUG_SD_INSTALL = false;
19163
19164    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19165
19166    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19167
19168    private boolean mMediaMounted = false;
19169
19170    static String getEncryptKey() {
19171        try {
19172            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19173                    SD_ENCRYPTION_KEYSTORE_NAME);
19174            if (sdEncKey == null) {
19175                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19176                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19177                if (sdEncKey == null) {
19178                    Slog.e(TAG, "Failed to create encryption keys");
19179                    return null;
19180                }
19181            }
19182            return sdEncKey;
19183        } catch (NoSuchAlgorithmException nsae) {
19184            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19185            return null;
19186        } catch (IOException ioe) {
19187            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19188            return null;
19189        }
19190    }
19191
19192    /*
19193     * Update media status on PackageManager.
19194     */
19195    @Override
19196    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19197        int callingUid = Binder.getCallingUid();
19198        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19199            throw new SecurityException("Media status can only be updated by the system");
19200        }
19201        // reader; this apparently protects mMediaMounted, but should probably
19202        // be a different lock in that case.
19203        synchronized (mPackages) {
19204            Log.i(TAG, "Updating external media status from "
19205                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19206                    + (mediaStatus ? "mounted" : "unmounted"));
19207            if (DEBUG_SD_INSTALL)
19208                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19209                        + ", mMediaMounted=" + mMediaMounted);
19210            if (mediaStatus == mMediaMounted) {
19211                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19212                        : 0, -1);
19213                mHandler.sendMessage(msg);
19214                return;
19215            }
19216            mMediaMounted = mediaStatus;
19217        }
19218        // Queue up an async operation since the package installation may take a
19219        // little while.
19220        mHandler.post(new Runnable() {
19221            public void run() {
19222                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19223            }
19224        });
19225    }
19226
19227    /**
19228     * Called by MountService when the initial ASECs to scan are available.
19229     * Should block until all the ASEC containers are finished being scanned.
19230     */
19231    public void scanAvailableAsecs() {
19232        updateExternalMediaStatusInner(true, false, false);
19233    }
19234
19235    /*
19236     * Collect information of applications on external media, map them against
19237     * existing containers and update information based on current mount status.
19238     * Please note that we always have to report status if reportStatus has been
19239     * set to true especially when unloading packages.
19240     */
19241    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19242            boolean externalStorage) {
19243        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19244        int[] uidArr = EmptyArray.INT;
19245
19246        final String[] list = PackageHelper.getSecureContainerList();
19247        if (ArrayUtils.isEmpty(list)) {
19248            Log.i(TAG, "No secure containers found");
19249        } else {
19250            // Process list of secure containers and categorize them
19251            // as active or stale based on their package internal state.
19252
19253            // reader
19254            synchronized (mPackages) {
19255                for (String cid : list) {
19256                    // Leave stages untouched for now; installer service owns them
19257                    if (PackageInstallerService.isStageName(cid)) continue;
19258
19259                    if (DEBUG_SD_INSTALL)
19260                        Log.i(TAG, "Processing container " + cid);
19261                    String pkgName = getAsecPackageName(cid);
19262                    if (pkgName == null) {
19263                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19264                        continue;
19265                    }
19266                    if (DEBUG_SD_INSTALL)
19267                        Log.i(TAG, "Looking for pkg : " + pkgName);
19268
19269                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19270                    if (ps == null) {
19271                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19272                        continue;
19273                    }
19274
19275                    /*
19276                     * Skip packages that are not external if we're unmounting
19277                     * external storage.
19278                     */
19279                    if (externalStorage && !isMounted && !isExternal(ps)) {
19280                        continue;
19281                    }
19282
19283                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19284                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19285                    // The package status is changed only if the code path
19286                    // matches between settings and the container id.
19287                    if (ps.codePathString != null
19288                            && ps.codePathString.startsWith(args.getCodePath())) {
19289                        if (DEBUG_SD_INSTALL) {
19290                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19291                                    + " at code path: " + ps.codePathString);
19292                        }
19293
19294                        // We do have a valid package installed on sdcard
19295                        processCids.put(args, ps.codePathString);
19296                        final int uid = ps.appId;
19297                        if (uid != -1) {
19298                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19299                        }
19300                    } else {
19301                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19302                                + ps.codePathString);
19303                    }
19304                }
19305            }
19306
19307            Arrays.sort(uidArr);
19308        }
19309
19310        // Process packages with valid entries.
19311        if (isMounted) {
19312            if (DEBUG_SD_INSTALL)
19313                Log.i(TAG, "Loading packages");
19314            loadMediaPackages(processCids, uidArr, externalStorage);
19315            startCleaningPackages();
19316            mInstallerService.onSecureContainersAvailable();
19317        } else {
19318            if (DEBUG_SD_INSTALL)
19319                Log.i(TAG, "Unloading packages");
19320            unloadMediaPackages(processCids, uidArr, reportStatus);
19321        }
19322    }
19323
19324    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19325            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19326        final int size = infos.size();
19327        final String[] packageNames = new String[size];
19328        final int[] packageUids = new int[size];
19329        for (int i = 0; i < size; i++) {
19330            final ApplicationInfo info = infos.get(i);
19331            packageNames[i] = info.packageName;
19332            packageUids[i] = info.uid;
19333        }
19334        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19335                finishedReceiver);
19336    }
19337
19338    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19339            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19340        sendResourcesChangedBroadcast(mediaStatus, replacing,
19341                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19342    }
19343
19344    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19345            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19346        int size = pkgList.length;
19347        if (size > 0) {
19348            // Send broadcasts here
19349            Bundle extras = new Bundle();
19350            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19351            if (uidArr != null) {
19352                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19353            }
19354            if (replacing) {
19355                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19356            }
19357            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19358                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19359            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19360        }
19361    }
19362
19363   /*
19364     * Look at potentially valid container ids from processCids If package
19365     * information doesn't match the one on record or package scanning fails,
19366     * the cid is added to list of removeCids. We currently don't delete stale
19367     * containers.
19368     */
19369    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19370            boolean externalStorage) {
19371        ArrayList<String> pkgList = new ArrayList<String>();
19372        Set<AsecInstallArgs> keys = processCids.keySet();
19373
19374        for (AsecInstallArgs args : keys) {
19375            String codePath = processCids.get(args);
19376            if (DEBUG_SD_INSTALL)
19377                Log.i(TAG, "Loading container : " + args.cid);
19378            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19379            try {
19380                // Make sure there are no container errors first.
19381                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19382                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19383                            + " when installing from sdcard");
19384                    continue;
19385                }
19386                // Check code path here.
19387                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19388                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19389                            + " does not match one in settings " + codePath);
19390                    continue;
19391                }
19392                // Parse package
19393                int parseFlags = mDefParseFlags;
19394                if (args.isExternalAsec()) {
19395                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19396                }
19397                if (args.isFwdLocked()) {
19398                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19399                }
19400
19401                synchronized (mInstallLock) {
19402                    PackageParser.Package pkg = null;
19403                    try {
19404                        // Sadly we don't know the package name yet to freeze it
19405                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19406                                SCAN_IGNORE_FROZEN, 0, null);
19407                    } catch (PackageManagerException e) {
19408                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19409                    }
19410                    // Scan the package
19411                    if (pkg != null) {
19412                        /*
19413                         * TODO why is the lock being held? doPostInstall is
19414                         * called in other places without the lock. This needs
19415                         * to be straightened out.
19416                         */
19417                        // writer
19418                        synchronized (mPackages) {
19419                            retCode = PackageManager.INSTALL_SUCCEEDED;
19420                            pkgList.add(pkg.packageName);
19421                            // Post process args
19422                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19423                                    pkg.applicationInfo.uid);
19424                        }
19425                    } else {
19426                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19427                    }
19428                }
19429
19430            } finally {
19431                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19432                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19433                }
19434            }
19435        }
19436        // writer
19437        synchronized (mPackages) {
19438            // If the platform SDK has changed since the last time we booted,
19439            // we need to re-grant app permission to catch any new ones that
19440            // appear. This is really a hack, and means that apps can in some
19441            // cases get permissions that the user didn't initially explicitly
19442            // allow... it would be nice to have some better way to handle
19443            // this situation.
19444            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19445                    : mSettings.getInternalVersion();
19446            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19447                    : StorageManager.UUID_PRIVATE_INTERNAL;
19448
19449            int updateFlags = UPDATE_PERMISSIONS_ALL;
19450            if (ver.sdkVersion != mSdkVersion) {
19451                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19452                        + mSdkVersion + "; regranting permissions for external");
19453                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19454            }
19455            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19456
19457            // Yay, everything is now upgraded
19458            ver.forceCurrent();
19459
19460            // can downgrade to reader
19461            // Persist settings
19462            mSettings.writeLPr();
19463        }
19464        // Send a broadcast to let everyone know we are done processing
19465        if (pkgList.size() > 0) {
19466            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19467        }
19468    }
19469
19470   /*
19471     * Utility method to unload a list of specified containers
19472     */
19473    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19474        // Just unmount all valid containers.
19475        for (AsecInstallArgs arg : cidArgs) {
19476            synchronized (mInstallLock) {
19477                arg.doPostDeleteLI(false);
19478           }
19479       }
19480   }
19481
19482    /*
19483     * Unload packages mounted on external media. This involves deleting package
19484     * data from internal structures, sending broadcasts about disabled packages,
19485     * gc'ing to free up references, unmounting all secure containers
19486     * corresponding to packages on external media, and posting a
19487     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19488     * that we always have to post this message if status has been requested no
19489     * matter what.
19490     */
19491    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19492            final boolean reportStatus) {
19493        if (DEBUG_SD_INSTALL)
19494            Log.i(TAG, "unloading media packages");
19495        ArrayList<String> pkgList = new ArrayList<String>();
19496        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19497        final Set<AsecInstallArgs> keys = processCids.keySet();
19498        for (AsecInstallArgs args : keys) {
19499            String pkgName = args.getPackageName();
19500            if (DEBUG_SD_INSTALL)
19501                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19502            // Delete package internally
19503            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19504            synchronized (mInstallLock) {
19505                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19506                final boolean res;
19507                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19508                        "unloadMediaPackages")) {
19509                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19510                            null);
19511                }
19512                if (res) {
19513                    pkgList.add(pkgName);
19514                } else {
19515                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19516                    failedList.add(args);
19517                }
19518            }
19519        }
19520
19521        // reader
19522        synchronized (mPackages) {
19523            // We didn't update the settings after removing each package;
19524            // write them now for all packages.
19525            mSettings.writeLPr();
19526        }
19527
19528        // We have to absolutely send UPDATED_MEDIA_STATUS only
19529        // after confirming that all the receivers processed the ordered
19530        // broadcast when packages get disabled, force a gc to clean things up.
19531        // and unload all the containers.
19532        if (pkgList.size() > 0) {
19533            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19534                    new IIntentReceiver.Stub() {
19535                public void performReceive(Intent intent, int resultCode, String data,
19536                        Bundle extras, boolean ordered, boolean sticky,
19537                        int sendingUser) throws RemoteException {
19538                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19539                            reportStatus ? 1 : 0, 1, keys);
19540                    mHandler.sendMessage(msg);
19541                }
19542            });
19543        } else {
19544            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19545                    keys);
19546            mHandler.sendMessage(msg);
19547        }
19548    }
19549
19550    private void loadPrivatePackages(final VolumeInfo vol) {
19551        mHandler.post(new Runnable() {
19552            @Override
19553            public void run() {
19554                loadPrivatePackagesInner(vol);
19555            }
19556        });
19557    }
19558
19559    private void loadPrivatePackagesInner(VolumeInfo vol) {
19560        final String volumeUuid = vol.fsUuid;
19561        if (TextUtils.isEmpty(volumeUuid)) {
19562            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19563            return;
19564        }
19565
19566        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19567        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19568        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19569
19570        final VersionInfo ver;
19571        final List<PackageSetting> packages;
19572        synchronized (mPackages) {
19573            ver = mSettings.findOrCreateVersion(volumeUuid);
19574            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19575        }
19576
19577        for (PackageSetting ps : packages) {
19578            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19579            synchronized (mInstallLock) {
19580                final PackageParser.Package pkg;
19581                try {
19582                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19583                    loaded.add(pkg.applicationInfo);
19584
19585                } catch (PackageManagerException e) {
19586                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19587                }
19588
19589                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19590                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19591                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19592                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19593                }
19594            }
19595        }
19596
19597        // Reconcile app data for all started/unlocked users
19598        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19599        final UserManager um = mContext.getSystemService(UserManager.class);
19600        UserManagerInternal umInternal = getUserManagerInternal();
19601        for (UserInfo user : um.getUsers()) {
19602            final int flags;
19603            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19604                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19605            } else if (umInternal.isUserRunning(user.id)) {
19606                flags = StorageManager.FLAG_STORAGE_DE;
19607            } else {
19608                continue;
19609            }
19610
19611            try {
19612                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19613                synchronized (mInstallLock) {
19614                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19615                }
19616            } catch (IllegalStateException e) {
19617                // Device was probably ejected, and we'll process that event momentarily
19618                Slog.w(TAG, "Failed to prepare storage: " + e);
19619            }
19620        }
19621
19622        synchronized (mPackages) {
19623            int updateFlags = UPDATE_PERMISSIONS_ALL;
19624            if (ver.sdkVersion != mSdkVersion) {
19625                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19626                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19627                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19628            }
19629            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19630
19631            // Yay, everything is now upgraded
19632            ver.forceCurrent();
19633
19634            mSettings.writeLPr();
19635        }
19636
19637        for (PackageFreezer freezer : freezers) {
19638            freezer.close();
19639        }
19640
19641        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19642        sendResourcesChangedBroadcast(true, false, loaded, null);
19643    }
19644
19645    private void unloadPrivatePackages(final VolumeInfo vol) {
19646        mHandler.post(new Runnable() {
19647            @Override
19648            public void run() {
19649                unloadPrivatePackagesInner(vol);
19650            }
19651        });
19652    }
19653
19654    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19655        final String volumeUuid = vol.fsUuid;
19656        if (TextUtils.isEmpty(volumeUuid)) {
19657            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19658            return;
19659        }
19660
19661        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19662        synchronized (mInstallLock) {
19663        synchronized (mPackages) {
19664            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19665            for (PackageSetting ps : packages) {
19666                if (ps.pkg == null) continue;
19667
19668                final ApplicationInfo info = ps.pkg.applicationInfo;
19669                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19670                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19671
19672                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19673                        "unloadPrivatePackagesInner")) {
19674                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19675                            false, null)) {
19676                        unloaded.add(info);
19677                    } else {
19678                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19679                    }
19680                }
19681
19682                // Try very hard to release any references to this package
19683                // so we don't risk the system server being killed due to
19684                // open FDs
19685                AttributeCache.instance().removePackage(ps.name);
19686            }
19687
19688            mSettings.writeLPr();
19689        }
19690        }
19691
19692        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19693        sendResourcesChangedBroadcast(false, false, unloaded, null);
19694
19695        // Try very hard to release any references to this path so we don't risk
19696        // the system server being killed due to open FDs
19697        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19698
19699        for (int i = 0; i < 3; i++) {
19700            System.gc();
19701            System.runFinalization();
19702        }
19703    }
19704
19705    /**
19706     * Prepare storage areas for given user on all mounted devices.
19707     */
19708    void prepareUserData(int userId, int userSerial, int flags) {
19709        synchronized (mInstallLock) {
19710            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19711            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19712                final String volumeUuid = vol.getFsUuid();
19713                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19714            }
19715        }
19716    }
19717
19718    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19719            boolean allowRecover) {
19720        // Prepare storage and verify that serial numbers are consistent; if
19721        // there's a mismatch we need to destroy to avoid leaking data
19722        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19723        try {
19724            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19725
19726            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19727                UserManagerService.enforceSerialNumber(
19728                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19729                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19730                    UserManagerService.enforceSerialNumber(
19731                            Environment.getDataSystemDeDirectory(userId), userSerial);
19732                }
19733            }
19734            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19735                UserManagerService.enforceSerialNumber(
19736                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19737                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19738                    UserManagerService.enforceSerialNumber(
19739                            Environment.getDataSystemCeDirectory(userId), userSerial);
19740                }
19741            }
19742
19743            synchronized (mInstallLock) {
19744                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19745            }
19746        } catch (Exception e) {
19747            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19748                    + " because we failed to prepare: " + e);
19749            destroyUserDataLI(volumeUuid, userId,
19750                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19751
19752            if (allowRecover) {
19753                // Try one last time; if we fail again we're really in trouble
19754                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19755            }
19756        }
19757    }
19758
19759    /**
19760     * Destroy storage areas for given user on all mounted devices.
19761     */
19762    void destroyUserData(int userId, int flags) {
19763        synchronized (mInstallLock) {
19764            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19765            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19766                final String volumeUuid = vol.getFsUuid();
19767                destroyUserDataLI(volumeUuid, userId, flags);
19768            }
19769        }
19770    }
19771
19772    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19773        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19774        try {
19775            // Clean up app data, profile data, and media data
19776            mInstaller.destroyUserData(volumeUuid, userId, flags);
19777
19778            // Clean up system data
19779            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19780                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19781                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19782                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19783                }
19784                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19785                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19786                }
19787            }
19788
19789            // Data with special labels is now gone, so finish the job
19790            storage.destroyUserStorage(volumeUuid, userId, flags);
19791
19792        } catch (Exception e) {
19793            logCriticalInfo(Log.WARN,
19794                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19795        }
19796    }
19797
19798    /**
19799     * Examine all users present on given mounted volume, and destroy data
19800     * belonging to users that are no longer valid, or whose user ID has been
19801     * recycled.
19802     */
19803    private void reconcileUsers(String volumeUuid) {
19804        final List<File> files = new ArrayList<>();
19805        Collections.addAll(files, FileUtils
19806                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19807        Collections.addAll(files, FileUtils
19808                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19809        Collections.addAll(files, FileUtils
19810                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19811        Collections.addAll(files, FileUtils
19812                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19813        for (File file : files) {
19814            if (!file.isDirectory()) continue;
19815
19816            final int userId;
19817            final UserInfo info;
19818            try {
19819                userId = Integer.parseInt(file.getName());
19820                info = sUserManager.getUserInfo(userId);
19821            } catch (NumberFormatException e) {
19822                Slog.w(TAG, "Invalid user directory " + file);
19823                continue;
19824            }
19825
19826            boolean destroyUser = false;
19827            if (info == null) {
19828                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19829                        + " because no matching user was found");
19830                destroyUser = true;
19831            } else if (!mOnlyCore) {
19832                try {
19833                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19834                } catch (IOException e) {
19835                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19836                            + " because we failed to enforce serial number: " + e);
19837                    destroyUser = true;
19838                }
19839            }
19840
19841            if (destroyUser) {
19842                synchronized (mInstallLock) {
19843                    destroyUserDataLI(volumeUuid, userId,
19844                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19845                }
19846            }
19847        }
19848    }
19849
19850    private void assertPackageKnown(String volumeUuid, String packageName)
19851            throws PackageManagerException {
19852        synchronized (mPackages) {
19853            final PackageSetting ps = mSettings.mPackages.get(packageName);
19854            if (ps == null) {
19855                throw new PackageManagerException("Package " + packageName + " is unknown");
19856            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19857                throw new PackageManagerException(
19858                        "Package " + packageName + " found on unknown volume " + volumeUuid
19859                                + "; expected volume " + ps.volumeUuid);
19860            }
19861        }
19862    }
19863
19864    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19865            throws PackageManagerException {
19866        synchronized (mPackages) {
19867            final PackageSetting ps = mSettings.mPackages.get(packageName);
19868            if (ps == null) {
19869                throw new PackageManagerException("Package " + packageName + " is unknown");
19870            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19871                throw new PackageManagerException(
19872                        "Package " + packageName + " found on unknown volume " + volumeUuid
19873                                + "; expected volume " + ps.volumeUuid);
19874            } else if (!ps.getInstalled(userId)) {
19875                throw new PackageManagerException(
19876                        "Package " + packageName + " not installed for user " + userId);
19877            }
19878        }
19879    }
19880
19881    /**
19882     * Examine all apps present on given mounted volume, and destroy apps that
19883     * aren't expected, either due to uninstallation or reinstallation on
19884     * another volume.
19885     */
19886    private void reconcileApps(String volumeUuid) {
19887        final File[] files = FileUtils
19888                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19889        for (File file : files) {
19890            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19891                    && !PackageInstallerService.isStageName(file.getName());
19892            if (!isPackage) {
19893                // Ignore entries which are not packages
19894                continue;
19895            }
19896
19897            try {
19898                final PackageLite pkg = PackageParser.parsePackageLite(file,
19899                        PackageParser.PARSE_MUST_BE_APK);
19900                assertPackageKnown(volumeUuid, pkg.packageName);
19901
19902            } catch (PackageParserException | PackageManagerException e) {
19903                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19904                synchronized (mInstallLock) {
19905                    removeCodePathLI(file);
19906                }
19907            }
19908        }
19909    }
19910
19911    /**
19912     * Reconcile all app data for the given user.
19913     * <p>
19914     * Verifies that directories exist and that ownership and labeling is
19915     * correct for all installed apps on all mounted volumes.
19916     */
19917    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19918        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19919        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19920            final String volumeUuid = vol.getFsUuid();
19921            synchronized (mInstallLock) {
19922                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19923            }
19924        }
19925    }
19926
19927    /**
19928     * Reconcile all app data on given mounted volume.
19929     * <p>
19930     * Destroys app data that isn't expected, either due to uninstallation or
19931     * reinstallation on another volume.
19932     * <p>
19933     * Verifies that directories exist and that ownership and labeling is
19934     * correct for all installed apps.
19935     */
19936    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19937            boolean migrateAppData) {
19938        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19939                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19940
19941        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19942        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19943
19944        // First look for stale data that doesn't belong, and check if things
19945        // have changed since we did our last restorecon
19946        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19947            if (StorageManager.isFileEncryptedNativeOrEmulated()
19948                    && !StorageManager.isUserKeyUnlocked(userId)) {
19949                throw new RuntimeException(
19950                        "Yikes, someone asked us to reconcile CE storage while " + userId
19951                                + " was still locked; this would have caused massive data loss!");
19952            }
19953
19954            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19955            for (File file : files) {
19956                final String packageName = file.getName();
19957                try {
19958                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19959                } catch (PackageManagerException e) {
19960                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19961                    try {
19962                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19963                                StorageManager.FLAG_STORAGE_CE, 0);
19964                    } catch (InstallerException e2) {
19965                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19966                    }
19967                }
19968            }
19969        }
19970        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19971            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19972            for (File file : files) {
19973                final String packageName = file.getName();
19974                try {
19975                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19976                } catch (PackageManagerException e) {
19977                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19978                    try {
19979                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19980                                StorageManager.FLAG_STORAGE_DE, 0);
19981                    } catch (InstallerException e2) {
19982                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19983                    }
19984                }
19985            }
19986        }
19987
19988        // Ensure that data directories are ready to roll for all packages
19989        // installed for this volume and user
19990        final List<PackageSetting> packages;
19991        synchronized (mPackages) {
19992            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19993        }
19994        int preparedCount = 0;
19995        for (PackageSetting ps : packages) {
19996            final String packageName = ps.name;
19997            if (ps.pkg == null) {
19998                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19999                // TODO: might be due to legacy ASEC apps; we should circle back
20000                // and reconcile again once they're scanned
20001                continue;
20002            }
20003
20004            if (ps.getInstalled(userId)) {
20005                prepareAppDataLIF(ps.pkg, userId, flags);
20006
20007                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20008                    // We may have just shuffled around app data directories, so
20009                    // prepare them one more time
20010                    prepareAppDataLIF(ps.pkg, userId, flags);
20011                }
20012
20013                preparedCount++;
20014            }
20015        }
20016
20017        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20018    }
20019
20020    /**
20021     * Prepare app data for the given app just after it was installed or
20022     * upgraded. This method carefully only touches users that it's installed
20023     * for, and it forces a restorecon to handle any seinfo changes.
20024     * <p>
20025     * Verifies that directories exist and that ownership and labeling is
20026     * correct for all installed apps. If there is an ownership mismatch, it
20027     * will try recovering system apps by wiping data; third-party app data is
20028     * left intact.
20029     * <p>
20030     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20031     */
20032    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20033        final PackageSetting ps;
20034        synchronized (mPackages) {
20035            ps = mSettings.mPackages.get(pkg.packageName);
20036            mSettings.writeKernelMappingLPr(ps);
20037        }
20038
20039        final UserManager um = mContext.getSystemService(UserManager.class);
20040        UserManagerInternal umInternal = getUserManagerInternal();
20041        for (UserInfo user : um.getUsers()) {
20042            final int flags;
20043            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20044                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20045            } else if (umInternal.isUserRunning(user.id)) {
20046                flags = StorageManager.FLAG_STORAGE_DE;
20047            } else {
20048                continue;
20049            }
20050
20051            if (ps.getInstalled(user.id)) {
20052                // TODO: when user data is locked, mark that we're still dirty
20053                prepareAppDataLIF(pkg, user.id, flags);
20054            }
20055        }
20056    }
20057
20058    /**
20059     * Prepare app data for the given app.
20060     * <p>
20061     * Verifies that directories exist and that ownership and labeling is
20062     * correct for all installed apps. If there is an ownership mismatch, this
20063     * will try recovering system apps by wiping data; third-party app data is
20064     * left intact.
20065     */
20066    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20067        if (pkg == null) {
20068            Slog.wtf(TAG, "Package was null!", new Throwable());
20069            return;
20070        }
20071        prepareAppDataLeafLIF(pkg, userId, flags);
20072        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20073        for (int i = 0; i < childCount; i++) {
20074            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20075        }
20076    }
20077
20078    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20079        if (DEBUG_APP_DATA) {
20080            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20081                    + Integer.toHexString(flags));
20082        }
20083
20084        final String volumeUuid = pkg.volumeUuid;
20085        final String packageName = pkg.packageName;
20086        final ApplicationInfo app = pkg.applicationInfo;
20087        final int appId = UserHandle.getAppId(app.uid);
20088
20089        Preconditions.checkNotNull(app.seinfo);
20090
20091        try {
20092            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20093                    appId, app.seinfo, app.targetSdkVersion);
20094        } catch (InstallerException e) {
20095            if (app.isSystemApp()) {
20096                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20097                        + ", but trying to recover: " + e);
20098                destroyAppDataLeafLIF(pkg, userId, flags);
20099                try {
20100                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20101                            appId, app.seinfo, app.targetSdkVersion);
20102                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20103                } catch (InstallerException e2) {
20104                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20105                }
20106            } else {
20107                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20108            }
20109        }
20110
20111        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20112            try {
20113                // CE storage is unlocked right now, so read out the inode and
20114                // remember for use later when it's locked
20115                // TODO: mark this structure as dirty so we persist it!
20116                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20117                        StorageManager.FLAG_STORAGE_CE);
20118                synchronized (mPackages) {
20119                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20120                    if (ps != null) {
20121                        ps.setCeDataInode(ceDataInode, userId);
20122                    }
20123                }
20124            } catch (InstallerException e) {
20125                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20126            }
20127        }
20128
20129        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20130    }
20131
20132    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20133        if (pkg == null) {
20134            Slog.wtf(TAG, "Package was null!", new Throwable());
20135            return;
20136        }
20137        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20138        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20139        for (int i = 0; i < childCount; i++) {
20140            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20141        }
20142    }
20143
20144    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20145        final String volumeUuid = pkg.volumeUuid;
20146        final String packageName = pkg.packageName;
20147        final ApplicationInfo app = pkg.applicationInfo;
20148
20149        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20150            // Create a native library symlink only if we have native libraries
20151            // and if the native libraries are 32 bit libraries. We do not provide
20152            // this symlink for 64 bit libraries.
20153            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20154                final String nativeLibPath = app.nativeLibraryDir;
20155                try {
20156                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20157                            nativeLibPath, userId);
20158                } catch (InstallerException e) {
20159                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20160                }
20161            }
20162        }
20163    }
20164
20165    /**
20166     * For system apps on non-FBE devices, this method migrates any existing
20167     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20168     * requested by the app.
20169     */
20170    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20171        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20172                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20173            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20174                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20175            try {
20176                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20177                        storageTarget);
20178            } catch (InstallerException e) {
20179                logCriticalInfo(Log.WARN,
20180                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20181            }
20182            return true;
20183        } else {
20184            return false;
20185        }
20186    }
20187
20188    public PackageFreezer freezePackage(String packageName, String killReason) {
20189        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20190    }
20191
20192    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20193        return new PackageFreezer(packageName, userId, killReason);
20194    }
20195
20196    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20197            String killReason) {
20198        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20199    }
20200
20201    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20202            String killReason) {
20203        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20204            return new PackageFreezer();
20205        } else {
20206            return freezePackage(packageName, userId, killReason);
20207        }
20208    }
20209
20210    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20211            String killReason) {
20212        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20213    }
20214
20215    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20216            String killReason) {
20217        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20218            return new PackageFreezer();
20219        } else {
20220            return freezePackage(packageName, userId, killReason);
20221        }
20222    }
20223
20224    /**
20225     * Class that freezes and kills the given package upon creation, and
20226     * unfreezes it upon closing. This is typically used when doing surgery on
20227     * app code/data to prevent the app from running while you're working.
20228     */
20229    private class PackageFreezer implements AutoCloseable {
20230        private final String mPackageName;
20231        private final PackageFreezer[] mChildren;
20232
20233        private final boolean mWeFroze;
20234
20235        private final AtomicBoolean mClosed = new AtomicBoolean();
20236        private final CloseGuard mCloseGuard = CloseGuard.get();
20237
20238        /**
20239         * Create and return a stub freezer that doesn't actually do anything,
20240         * typically used when someone requested
20241         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20242         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20243         */
20244        public PackageFreezer() {
20245            mPackageName = null;
20246            mChildren = null;
20247            mWeFroze = false;
20248            mCloseGuard.open("close");
20249        }
20250
20251        public PackageFreezer(String packageName, int userId, String killReason) {
20252            synchronized (mPackages) {
20253                mPackageName = packageName;
20254                mWeFroze = mFrozenPackages.add(mPackageName);
20255
20256                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20257                if (ps != null) {
20258                    killApplication(ps.name, ps.appId, userId, killReason);
20259                }
20260
20261                final PackageParser.Package p = mPackages.get(packageName);
20262                if (p != null && p.childPackages != null) {
20263                    final int N = p.childPackages.size();
20264                    mChildren = new PackageFreezer[N];
20265                    for (int i = 0; i < N; i++) {
20266                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20267                                userId, killReason);
20268                    }
20269                } else {
20270                    mChildren = null;
20271                }
20272            }
20273            mCloseGuard.open("close");
20274        }
20275
20276        @Override
20277        protected void finalize() throws Throwable {
20278            try {
20279                mCloseGuard.warnIfOpen();
20280                close();
20281            } finally {
20282                super.finalize();
20283            }
20284        }
20285
20286        @Override
20287        public void close() {
20288            mCloseGuard.close();
20289            if (mClosed.compareAndSet(false, true)) {
20290                synchronized (mPackages) {
20291                    if (mWeFroze) {
20292                        mFrozenPackages.remove(mPackageName);
20293                    }
20294
20295                    if (mChildren != null) {
20296                        for (PackageFreezer freezer : mChildren) {
20297                            freezer.close();
20298                        }
20299                    }
20300                }
20301            }
20302        }
20303    }
20304
20305    /**
20306     * Verify that given package is currently frozen.
20307     */
20308    private void checkPackageFrozen(String packageName) {
20309        synchronized (mPackages) {
20310            if (!mFrozenPackages.contains(packageName)) {
20311                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20312            }
20313        }
20314    }
20315
20316    @Override
20317    public int movePackage(final String packageName, final String volumeUuid) {
20318        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20319
20320        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20321        final int moveId = mNextMoveId.getAndIncrement();
20322        mHandler.post(new Runnable() {
20323            @Override
20324            public void run() {
20325                try {
20326                    movePackageInternal(packageName, volumeUuid, moveId, user);
20327                } catch (PackageManagerException e) {
20328                    Slog.w(TAG, "Failed to move " + packageName, e);
20329                    mMoveCallbacks.notifyStatusChanged(moveId,
20330                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20331                }
20332            }
20333        });
20334        return moveId;
20335    }
20336
20337    private void movePackageInternal(final String packageName, final String volumeUuid,
20338            final int moveId, UserHandle user) throws PackageManagerException {
20339        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20340        final PackageManager pm = mContext.getPackageManager();
20341
20342        final boolean currentAsec;
20343        final String currentVolumeUuid;
20344        final File codeFile;
20345        final String installerPackageName;
20346        final String packageAbiOverride;
20347        final int appId;
20348        final String seinfo;
20349        final String label;
20350        final int targetSdkVersion;
20351        final PackageFreezer freezer;
20352        final int[] installedUserIds;
20353
20354        // reader
20355        synchronized (mPackages) {
20356            final PackageParser.Package pkg = mPackages.get(packageName);
20357            final PackageSetting ps = mSettings.mPackages.get(packageName);
20358            if (pkg == null || ps == null) {
20359                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20360            }
20361
20362            if (pkg.applicationInfo.isSystemApp()) {
20363                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20364                        "Cannot move system application");
20365            }
20366
20367            if (pkg.applicationInfo.isExternalAsec()) {
20368                currentAsec = true;
20369                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20370            } else if (pkg.applicationInfo.isForwardLocked()) {
20371                currentAsec = true;
20372                currentVolumeUuid = "forward_locked";
20373            } else {
20374                currentAsec = false;
20375                currentVolumeUuid = ps.volumeUuid;
20376
20377                final File probe = new File(pkg.codePath);
20378                final File probeOat = new File(probe, "oat");
20379                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20380                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20381                            "Move only supported for modern cluster style installs");
20382                }
20383            }
20384
20385            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20386                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20387                        "Package already moved to " + volumeUuid);
20388            }
20389            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20390                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20391                        "Device admin cannot be moved");
20392            }
20393
20394            if (mFrozenPackages.contains(packageName)) {
20395                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20396                        "Failed to move already frozen package");
20397            }
20398
20399            codeFile = new File(pkg.codePath);
20400            installerPackageName = ps.installerPackageName;
20401            packageAbiOverride = ps.cpuAbiOverrideString;
20402            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20403            seinfo = pkg.applicationInfo.seinfo;
20404            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20405            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20406            freezer = freezePackage(packageName, "movePackageInternal");
20407            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20408        }
20409
20410        final Bundle extras = new Bundle();
20411        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20412        extras.putString(Intent.EXTRA_TITLE, label);
20413        mMoveCallbacks.notifyCreated(moveId, extras);
20414
20415        int installFlags;
20416        final boolean moveCompleteApp;
20417        final File measurePath;
20418
20419        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20420            installFlags = INSTALL_INTERNAL;
20421            moveCompleteApp = !currentAsec;
20422            measurePath = Environment.getDataAppDirectory(volumeUuid);
20423        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20424            installFlags = INSTALL_EXTERNAL;
20425            moveCompleteApp = false;
20426            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20427        } else {
20428            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20429            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20430                    || !volume.isMountedWritable()) {
20431                freezer.close();
20432                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20433                        "Move location not mounted private volume");
20434            }
20435
20436            Preconditions.checkState(!currentAsec);
20437
20438            installFlags = INSTALL_INTERNAL;
20439            moveCompleteApp = true;
20440            measurePath = Environment.getDataAppDirectory(volumeUuid);
20441        }
20442
20443        final PackageStats stats = new PackageStats(null, -1);
20444        synchronized (mInstaller) {
20445            for (int userId : installedUserIds) {
20446                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20447                    freezer.close();
20448                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20449                            "Failed to measure package size");
20450                }
20451            }
20452        }
20453
20454        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20455                + stats.dataSize);
20456
20457        final long startFreeBytes = measurePath.getFreeSpace();
20458        final long sizeBytes;
20459        if (moveCompleteApp) {
20460            sizeBytes = stats.codeSize + stats.dataSize;
20461        } else {
20462            sizeBytes = stats.codeSize;
20463        }
20464
20465        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20466            freezer.close();
20467            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20468                    "Not enough free space to move");
20469        }
20470
20471        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20472
20473        final CountDownLatch installedLatch = new CountDownLatch(1);
20474        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20475            @Override
20476            public void onUserActionRequired(Intent intent) throws RemoteException {
20477                throw new IllegalStateException();
20478            }
20479
20480            @Override
20481            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20482                    Bundle extras) throws RemoteException {
20483                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20484                        + PackageManager.installStatusToString(returnCode, msg));
20485
20486                installedLatch.countDown();
20487                freezer.close();
20488
20489                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20490                switch (status) {
20491                    case PackageInstaller.STATUS_SUCCESS:
20492                        mMoveCallbacks.notifyStatusChanged(moveId,
20493                                PackageManager.MOVE_SUCCEEDED);
20494                        break;
20495                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20496                        mMoveCallbacks.notifyStatusChanged(moveId,
20497                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20498                        break;
20499                    default:
20500                        mMoveCallbacks.notifyStatusChanged(moveId,
20501                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20502                        break;
20503                }
20504            }
20505        };
20506
20507        final MoveInfo move;
20508        if (moveCompleteApp) {
20509            // Kick off a thread to report progress estimates
20510            new Thread() {
20511                @Override
20512                public void run() {
20513                    while (true) {
20514                        try {
20515                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20516                                break;
20517                            }
20518                        } catch (InterruptedException ignored) {
20519                        }
20520
20521                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20522                        final int progress = 10 + (int) MathUtils.constrain(
20523                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20524                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20525                    }
20526                }
20527            }.start();
20528
20529            final String dataAppName = codeFile.getName();
20530            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20531                    dataAppName, appId, seinfo, targetSdkVersion);
20532        } else {
20533            move = null;
20534        }
20535
20536        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20537
20538        final Message msg = mHandler.obtainMessage(INIT_COPY);
20539        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20540        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20541                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20542                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20543        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20544        msg.obj = params;
20545
20546        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20547                System.identityHashCode(msg.obj));
20548        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20549                System.identityHashCode(msg.obj));
20550
20551        mHandler.sendMessage(msg);
20552    }
20553
20554    @Override
20555    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20556        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20557
20558        final int realMoveId = mNextMoveId.getAndIncrement();
20559        final Bundle extras = new Bundle();
20560        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20561        mMoveCallbacks.notifyCreated(realMoveId, extras);
20562
20563        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20564            @Override
20565            public void onCreated(int moveId, Bundle extras) {
20566                // Ignored
20567            }
20568
20569            @Override
20570            public void onStatusChanged(int moveId, int status, long estMillis) {
20571                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20572            }
20573        };
20574
20575        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20576        storage.setPrimaryStorageUuid(volumeUuid, callback);
20577        return realMoveId;
20578    }
20579
20580    @Override
20581    public int getMoveStatus(int moveId) {
20582        mContext.enforceCallingOrSelfPermission(
20583                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20584        return mMoveCallbacks.mLastStatus.get(moveId);
20585    }
20586
20587    @Override
20588    public void registerMoveCallback(IPackageMoveObserver callback) {
20589        mContext.enforceCallingOrSelfPermission(
20590                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20591        mMoveCallbacks.register(callback);
20592    }
20593
20594    @Override
20595    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20596        mContext.enforceCallingOrSelfPermission(
20597                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20598        mMoveCallbacks.unregister(callback);
20599    }
20600
20601    @Override
20602    public boolean setInstallLocation(int loc) {
20603        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20604                null);
20605        if (getInstallLocation() == loc) {
20606            return true;
20607        }
20608        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20609                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20610            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20611                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20612            return true;
20613        }
20614        return false;
20615   }
20616
20617    @Override
20618    public int getInstallLocation() {
20619        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20620                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20621                PackageHelper.APP_INSTALL_AUTO);
20622    }
20623
20624    /** Called by UserManagerService */
20625    void cleanUpUser(UserManagerService userManager, int userHandle) {
20626        synchronized (mPackages) {
20627            mDirtyUsers.remove(userHandle);
20628            mUserNeedsBadging.delete(userHandle);
20629            mSettings.removeUserLPw(userHandle);
20630            mPendingBroadcasts.remove(userHandle);
20631            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20632            removeUnusedPackagesLPw(userManager, userHandle);
20633        }
20634    }
20635
20636    /**
20637     * We're removing userHandle and would like to remove any downloaded packages
20638     * that are no longer in use by any other user.
20639     * @param userHandle the user being removed
20640     */
20641    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20642        final boolean DEBUG_CLEAN_APKS = false;
20643        int [] users = userManager.getUserIds();
20644        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20645        while (psit.hasNext()) {
20646            PackageSetting ps = psit.next();
20647            if (ps.pkg == null) {
20648                continue;
20649            }
20650            final String packageName = ps.pkg.packageName;
20651            // Skip over if system app
20652            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20653                continue;
20654            }
20655            if (DEBUG_CLEAN_APKS) {
20656                Slog.i(TAG, "Checking package " + packageName);
20657            }
20658            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20659            if (keep) {
20660                if (DEBUG_CLEAN_APKS) {
20661                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20662                }
20663            } else {
20664                for (int i = 0; i < users.length; i++) {
20665                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20666                        keep = true;
20667                        if (DEBUG_CLEAN_APKS) {
20668                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20669                                    + users[i]);
20670                        }
20671                        break;
20672                    }
20673                }
20674            }
20675            if (!keep) {
20676                if (DEBUG_CLEAN_APKS) {
20677                    Slog.i(TAG, "  Removing package " + packageName);
20678                }
20679                mHandler.post(new Runnable() {
20680                    public void run() {
20681                        deletePackageX(packageName, userHandle, 0);
20682                    } //end run
20683                });
20684            }
20685        }
20686    }
20687
20688    /** Called by UserManagerService */
20689    void createNewUser(int userId, String[] disallowedPackages) {
20690        synchronized (mInstallLock) {
20691            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20692        }
20693        synchronized (mPackages) {
20694            scheduleWritePackageRestrictionsLocked(userId);
20695            scheduleWritePackageListLocked(userId);
20696            applyFactoryDefaultBrowserLPw(userId);
20697            primeDomainVerificationsLPw(userId);
20698        }
20699    }
20700
20701    void onNewUserCreated(final int userId) {
20702        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20703        // If permission review for legacy apps is required, we represent
20704        // dagerous permissions for such apps as always granted runtime
20705        // permissions to keep per user flag state whether review is needed.
20706        // Hence, if a new user is added we have to propagate dangerous
20707        // permission grants for these legacy apps.
20708        if (mPermissionReviewRequired) {
20709            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20710                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20711        }
20712    }
20713
20714    @Override
20715    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20716        mContext.enforceCallingOrSelfPermission(
20717                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20718                "Only package verification agents can read the verifier device identity");
20719
20720        synchronized (mPackages) {
20721            return mSettings.getVerifierDeviceIdentityLPw();
20722        }
20723    }
20724
20725    @Override
20726    public void setPermissionEnforced(String permission, boolean enforced) {
20727        // TODO: Now that we no longer change GID for storage, this should to away.
20728        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20729                "setPermissionEnforced");
20730        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20731            synchronized (mPackages) {
20732                if (mSettings.mReadExternalStorageEnforced == null
20733                        || mSettings.mReadExternalStorageEnforced != enforced) {
20734                    mSettings.mReadExternalStorageEnforced = enforced;
20735                    mSettings.writeLPr();
20736                }
20737            }
20738            // kill any non-foreground processes so we restart them and
20739            // grant/revoke the GID.
20740            final IActivityManager am = ActivityManagerNative.getDefault();
20741            if (am != null) {
20742                final long token = Binder.clearCallingIdentity();
20743                try {
20744                    am.killProcessesBelowForeground("setPermissionEnforcement");
20745                } catch (RemoteException e) {
20746                } finally {
20747                    Binder.restoreCallingIdentity(token);
20748                }
20749            }
20750        } else {
20751            throw new IllegalArgumentException("No selective enforcement for " + permission);
20752        }
20753    }
20754
20755    @Override
20756    @Deprecated
20757    public boolean isPermissionEnforced(String permission) {
20758        return true;
20759    }
20760
20761    @Override
20762    public boolean isStorageLow() {
20763        final long token = Binder.clearCallingIdentity();
20764        try {
20765            final DeviceStorageMonitorInternal
20766                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20767            if (dsm != null) {
20768                return dsm.isMemoryLow();
20769            } else {
20770                return false;
20771            }
20772        } finally {
20773            Binder.restoreCallingIdentity(token);
20774        }
20775    }
20776
20777    @Override
20778    public IPackageInstaller getPackageInstaller() {
20779        return mInstallerService;
20780    }
20781
20782    private boolean userNeedsBadging(int userId) {
20783        int index = mUserNeedsBadging.indexOfKey(userId);
20784        if (index < 0) {
20785            final UserInfo userInfo;
20786            final long token = Binder.clearCallingIdentity();
20787            try {
20788                userInfo = sUserManager.getUserInfo(userId);
20789            } finally {
20790                Binder.restoreCallingIdentity(token);
20791            }
20792            final boolean b;
20793            if (userInfo != null && userInfo.isManagedProfile()) {
20794                b = true;
20795            } else {
20796                b = false;
20797            }
20798            mUserNeedsBadging.put(userId, b);
20799            return b;
20800        }
20801        return mUserNeedsBadging.valueAt(index);
20802    }
20803
20804    @Override
20805    public KeySet getKeySetByAlias(String packageName, String alias) {
20806        if (packageName == null || alias == null) {
20807            return null;
20808        }
20809        synchronized(mPackages) {
20810            final PackageParser.Package pkg = mPackages.get(packageName);
20811            if (pkg == null) {
20812                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20813                throw new IllegalArgumentException("Unknown package: " + packageName);
20814            }
20815            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20816            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20817        }
20818    }
20819
20820    @Override
20821    public KeySet getSigningKeySet(String packageName) {
20822        if (packageName == null) {
20823            return null;
20824        }
20825        synchronized(mPackages) {
20826            final PackageParser.Package pkg = mPackages.get(packageName);
20827            if (pkg == null) {
20828                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20829                throw new IllegalArgumentException("Unknown package: " + packageName);
20830            }
20831            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20832                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20833                throw new SecurityException("May not access signing KeySet of other apps.");
20834            }
20835            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20836            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20837        }
20838    }
20839
20840    @Override
20841    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20842        if (packageName == null || ks == null) {
20843            return false;
20844        }
20845        synchronized(mPackages) {
20846            final PackageParser.Package pkg = mPackages.get(packageName);
20847            if (pkg == null) {
20848                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20849                throw new IllegalArgumentException("Unknown package: " + packageName);
20850            }
20851            IBinder ksh = ks.getToken();
20852            if (ksh instanceof KeySetHandle) {
20853                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20854                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20855            }
20856            return false;
20857        }
20858    }
20859
20860    @Override
20861    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20862        if (packageName == null || ks == null) {
20863            return false;
20864        }
20865        synchronized(mPackages) {
20866            final PackageParser.Package pkg = mPackages.get(packageName);
20867            if (pkg == null) {
20868                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20869                throw new IllegalArgumentException("Unknown package: " + packageName);
20870            }
20871            IBinder ksh = ks.getToken();
20872            if (ksh instanceof KeySetHandle) {
20873                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20874                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20875            }
20876            return false;
20877        }
20878    }
20879
20880    private void deletePackageIfUnusedLPr(final String packageName) {
20881        PackageSetting ps = mSettings.mPackages.get(packageName);
20882        if (ps == null) {
20883            return;
20884        }
20885        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20886            // TODO Implement atomic delete if package is unused
20887            // It is currently possible that the package will be deleted even if it is installed
20888            // after this method returns.
20889            mHandler.post(new Runnable() {
20890                public void run() {
20891                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20892                }
20893            });
20894        }
20895    }
20896
20897    /**
20898     * Check and throw if the given before/after packages would be considered a
20899     * downgrade.
20900     */
20901    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20902            throws PackageManagerException {
20903        if (after.versionCode < before.mVersionCode) {
20904            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20905                    "Update version code " + after.versionCode + " is older than current "
20906                    + before.mVersionCode);
20907        } else if (after.versionCode == before.mVersionCode) {
20908            if (after.baseRevisionCode < before.baseRevisionCode) {
20909                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20910                        "Update base revision code " + after.baseRevisionCode
20911                        + " is older than current " + before.baseRevisionCode);
20912            }
20913
20914            if (!ArrayUtils.isEmpty(after.splitNames)) {
20915                for (int i = 0; i < after.splitNames.length; i++) {
20916                    final String splitName = after.splitNames[i];
20917                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20918                    if (j != -1) {
20919                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20920                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20921                                    "Update split " + splitName + " revision code "
20922                                    + after.splitRevisionCodes[i] + " is older than current "
20923                                    + before.splitRevisionCodes[j]);
20924                        }
20925                    }
20926                }
20927            }
20928        }
20929    }
20930
20931    private static class MoveCallbacks extends Handler {
20932        private static final int MSG_CREATED = 1;
20933        private static final int MSG_STATUS_CHANGED = 2;
20934
20935        private final RemoteCallbackList<IPackageMoveObserver>
20936                mCallbacks = new RemoteCallbackList<>();
20937
20938        private final SparseIntArray mLastStatus = new SparseIntArray();
20939
20940        public MoveCallbacks(Looper looper) {
20941            super(looper);
20942        }
20943
20944        public void register(IPackageMoveObserver callback) {
20945            mCallbacks.register(callback);
20946        }
20947
20948        public void unregister(IPackageMoveObserver callback) {
20949            mCallbacks.unregister(callback);
20950        }
20951
20952        @Override
20953        public void handleMessage(Message msg) {
20954            final SomeArgs args = (SomeArgs) msg.obj;
20955            final int n = mCallbacks.beginBroadcast();
20956            for (int i = 0; i < n; i++) {
20957                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20958                try {
20959                    invokeCallback(callback, msg.what, args);
20960                } catch (RemoteException ignored) {
20961                }
20962            }
20963            mCallbacks.finishBroadcast();
20964            args.recycle();
20965        }
20966
20967        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20968                throws RemoteException {
20969            switch (what) {
20970                case MSG_CREATED: {
20971                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20972                    break;
20973                }
20974                case MSG_STATUS_CHANGED: {
20975                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20976                    break;
20977                }
20978            }
20979        }
20980
20981        private void notifyCreated(int moveId, Bundle extras) {
20982            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20983
20984            final SomeArgs args = SomeArgs.obtain();
20985            args.argi1 = moveId;
20986            args.arg2 = extras;
20987            obtainMessage(MSG_CREATED, args).sendToTarget();
20988        }
20989
20990        private void notifyStatusChanged(int moveId, int status) {
20991            notifyStatusChanged(moveId, status, -1);
20992        }
20993
20994        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20995            Slog.v(TAG, "Move " + moveId + " status " + status);
20996
20997            final SomeArgs args = SomeArgs.obtain();
20998            args.argi1 = moveId;
20999            args.argi2 = status;
21000            args.arg3 = estMillis;
21001            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21002
21003            synchronized (mLastStatus) {
21004                mLastStatus.put(moveId, status);
21005            }
21006        }
21007    }
21008
21009    private final static class OnPermissionChangeListeners extends Handler {
21010        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21011
21012        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21013                new RemoteCallbackList<>();
21014
21015        public OnPermissionChangeListeners(Looper looper) {
21016            super(looper);
21017        }
21018
21019        @Override
21020        public void handleMessage(Message msg) {
21021            switch (msg.what) {
21022                case MSG_ON_PERMISSIONS_CHANGED: {
21023                    final int uid = msg.arg1;
21024                    handleOnPermissionsChanged(uid);
21025                } break;
21026            }
21027        }
21028
21029        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21030            mPermissionListeners.register(listener);
21031
21032        }
21033
21034        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21035            mPermissionListeners.unregister(listener);
21036        }
21037
21038        public void onPermissionsChanged(int uid) {
21039            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21040                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21041            }
21042        }
21043
21044        private void handleOnPermissionsChanged(int uid) {
21045            final int count = mPermissionListeners.beginBroadcast();
21046            try {
21047                for (int i = 0; i < count; i++) {
21048                    IOnPermissionsChangeListener callback = mPermissionListeners
21049                            .getBroadcastItem(i);
21050                    try {
21051                        callback.onPermissionsChanged(uid);
21052                    } catch (RemoteException e) {
21053                        Log.e(TAG, "Permission listener is dead", e);
21054                    }
21055                }
21056            } finally {
21057                mPermissionListeners.finishBroadcast();
21058            }
21059        }
21060    }
21061
21062    private class PackageManagerInternalImpl extends PackageManagerInternal {
21063        @Override
21064        public void setLocationPackagesProvider(PackagesProvider provider) {
21065            synchronized (mPackages) {
21066                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21067            }
21068        }
21069
21070        @Override
21071        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21072            synchronized (mPackages) {
21073                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21074            }
21075        }
21076
21077        @Override
21078        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21079            synchronized (mPackages) {
21080                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21081            }
21082        }
21083
21084        @Override
21085        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21086            synchronized (mPackages) {
21087                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21088            }
21089        }
21090
21091        @Override
21092        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21093            synchronized (mPackages) {
21094                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21095            }
21096        }
21097
21098        @Override
21099        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21100            synchronized (mPackages) {
21101                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21102            }
21103        }
21104
21105        @Override
21106        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21107            synchronized (mPackages) {
21108                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21109                        packageName, userId);
21110            }
21111        }
21112
21113        @Override
21114        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21115            synchronized (mPackages) {
21116                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21117                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21118                        packageName, userId);
21119            }
21120        }
21121
21122        @Override
21123        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21124            synchronized (mPackages) {
21125                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21126                        packageName, userId);
21127            }
21128        }
21129
21130        @Override
21131        public void setKeepUninstalledPackages(final List<String> packageList) {
21132            Preconditions.checkNotNull(packageList);
21133            List<String> removedFromList = null;
21134            synchronized (mPackages) {
21135                if (mKeepUninstalledPackages != null) {
21136                    final int packagesCount = mKeepUninstalledPackages.size();
21137                    for (int i = 0; i < packagesCount; i++) {
21138                        String oldPackage = mKeepUninstalledPackages.get(i);
21139                        if (packageList != null && packageList.contains(oldPackage)) {
21140                            continue;
21141                        }
21142                        if (removedFromList == null) {
21143                            removedFromList = new ArrayList<>();
21144                        }
21145                        removedFromList.add(oldPackage);
21146                    }
21147                }
21148                mKeepUninstalledPackages = new ArrayList<>(packageList);
21149                if (removedFromList != null) {
21150                    final int removedCount = removedFromList.size();
21151                    for (int i = 0; i < removedCount; i++) {
21152                        deletePackageIfUnusedLPr(removedFromList.get(i));
21153                    }
21154                }
21155            }
21156        }
21157
21158        @Override
21159        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21160            synchronized (mPackages) {
21161                // If we do not support permission review, done.
21162                if (!mPermissionReviewRequired) {
21163                    return false;
21164                }
21165
21166                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21167                if (packageSetting == null) {
21168                    return false;
21169                }
21170
21171                // Permission review applies only to apps not supporting the new permission model.
21172                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21173                    return false;
21174                }
21175
21176                // Legacy apps have the permission and get user consent on launch.
21177                PermissionsState permissionsState = packageSetting.getPermissionsState();
21178                return permissionsState.isPermissionReviewRequired(userId);
21179            }
21180        }
21181
21182        @Override
21183        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21184            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21185        }
21186
21187        @Override
21188        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21189                int userId) {
21190            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21191        }
21192
21193        @Override
21194        public void setDeviceAndProfileOwnerPackages(
21195                int deviceOwnerUserId, String deviceOwnerPackage,
21196                SparseArray<String> profileOwnerPackages) {
21197            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21198                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21199        }
21200
21201        @Override
21202        public boolean isPackageDataProtected(int userId, String packageName) {
21203            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21204        }
21205
21206        @Override
21207        public boolean wasPackageEverLaunched(String packageName, int userId) {
21208            synchronized (mPackages) {
21209                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21210            }
21211        }
21212
21213        @Override
21214        public void grantRuntimePermission(String packageName, String name, int userId,
21215                boolean overridePolicy) {
21216            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21217                    overridePolicy);
21218        }
21219
21220        @Override
21221        public void revokeRuntimePermission(String packageName, String name, int userId,
21222                boolean overridePolicy) {
21223            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21224                    overridePolicy);
21225        }
21226    }
21227
21228    @Override
21229    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21230        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21231        synchronized (mPackages) {
21232            final long identity = Binder.clearCallingIdentity();
21233            try {
21234                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21235                        packageNames, userId);
21236            } finally {
21237                Binder.restoreCallingIdentity(identity);
21238            }
21239        }
21240    }
21241
21242    private static void enforceSystemOrPhoneCaller(String tag) {
21243        int callingUid = Binder.getCallingUid();
21244        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21245            throw new SecurityException(
21246                    "Cannot call " + tag + " from UID " + callingUid);
21247        }
21248    }
21249
21250    boolean isHistoricalPackageUsageAvailable() {
21251        return mPackageUsage.isHistoricalPackageUsageAvailable();
21252    }
21253
21254    /**
21255     * Return a <b>copy</b> of the collection of packages known to the package manager.
21256     * @return A copy of the values of mPackages.
21257     */
21258    Collection<PackageParser.Package> getPackages() {
21259        synchronized (mPackages) {
21260            return new ArrayList<>(mPackages.values());
21261        }
21262    }
21263
21264    /**
21265     * Logs process start information (including base APK hash) to the security log.
21266     * @hide
21267     */
21268    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21269            String apkFile, int pid) {
21270        if (!SecurityLog.isLoggingEnabled()) {
21271            return;
21272        }
21273        Bundle data = new Bundle();
21274        data.putLong("startTimestamp", System.currentTimeMillis());
21275        data.putString("processName", processName);
21276        data.putInt("uid", uid);
21277        data.putString("seinfo", seinfo);
21278        data.putString("apkFile", apkFile);
21279        data.putInt("pid", pid);
21280        Message msg = mProcessLoggingHandler.obtainMessage(
21281                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21282        msg.setData(data);
21283        mProcessLoggingHandler.sendMessage(msg);
21284    }
21285
21286    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21287        return mCompilerStats.getPackageStats(pkgName);
21288    }
21289
21290    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21291        return getOrCreateCompilerPackageStats(pkg.packageName);
21292    }
21293
21294    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21295        return mCompilerStats.getOrCreatePackageStats(pkgName);
21296    }
21297
21298    public void deleteCompilerPackageStats(String pkgName) {
21299        mCompilerStats.deletePackageStats(pkgName);
21300    }
21301}
21302