PackageManagerService.java revision 141594b5ee928f99a9dc08b38f70301ef1e08a0b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.provider.Settings.Global;
200import android.provider.Settings.Secure;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.Pair;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.util.jar.StrictJarFile;
223import android.view.Display;
224
225import com.android.internal.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.app.IMediaContainerService;
228import com.android.internal.app.ResolverActivity;
229import com.android.internal.content.NativeLibraryHelper;
230import com.android.internal.content.PackageHelper;
231import com.android.internal.logging.MetricsLogger;
232import com.android.internal.os.IParcelFileDescriptorFactory;
233import com.android.internal.os.InstallerConnection.InstallerException;
234import com.android.internal.os.SomeArgs;
235import com.android.internal.os.Zygote;
236import com.android.internal.telephony.CarrierAppUtils;
237import com.android.internal.util.ArrayUtils;
238import com.android.internal.util.FastPrintWriter;
239import com.android.internal.util.FastXmlSerializer;
240import com.android.internal.util.IndentingPrintWriter;
241import com.android.internal.util.Preconditions;
242import com.android.internal.util.XmlUtils;
243import com.android.server.AttributeCache;
244import com.android.server.EventLogTags;
245import com.android.server.FgThread;
246import com.android.server.IntentResolver;
247import com.android.server.LocalServices;
248import com.android.server.ServiceThread;
249import com.android.server.SystemConfig;
250import com.android.server.Watchdog;
251import com.android.server.net.NetworkPolicyManagerInternal;
252import com.android.server.pm.PermissionsState.PermissionState;
253import com.android.server.pm.Settings.DatabaseVersion;
254import com.android.server.pm.Settings.VersionInfo;
255import com.android.server.storage.DeviceStorageMonitorInternal;
256
257import dalvik.system.CloseGuard;
258import dalvik.system.DexFile;
259import dalvik.system.VMRuntime;
260
261import libcore.io.IoUtils;
262import libcore.util.EmptyArray;
263
264import org.xmlpull.v1.XmlPullParser;
265import org.xmlpull.v1.XmlPullParserException;
266import org.xmlpull.v1.XmlSerializer;
267
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
368    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
369
370    private static final boolean DISABLE_EPHEMERAL_APPS = false;
371    private static final boolean HIDE_EPHEMERAL_APIS = true;
372
373    private static final int RADIO_UID = Process.PHONE_UID;
374    private static final int LOG_UID = Process.LOG_UID;
375    private static final int NFC_UID = Process.NFC_UID;
376    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377    private static final int SHELL_UID = Process.SHELL_UID;
378
379    // Cap the size of permission trees that 3rd party apps can define
380    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382    // Suffix used during package installation when copying/moving
383    // package apks to install directory.
384    private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386    static final int SCAN_NO_DEX = 1<<1;
387    static final int SCAN_FORCE_DEX = 1<<2;
388    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389    static final int SCAN_NEW_INSTALL = 1<<4;
390    static final int SCAN_NO_PATHS = 1<<5;
391    static final int SCAN_UPDATE_TIME = 1<<6;
392    static final int SCAN_DEFER_DEX = 1<<7;
393    static final int SCAN_BOOTING = 1<<8;
394    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396    static final int SCAN_REPLACING = 1<<11;
397    static final int SCAN_REQUIRE_KNOWN = 1<<12;
398    static final int SCAN_MOVE = 1<<13;
399    static final int SCAN_INITIAL = 1<<14;
400    static final int SCAN_CHECK_ONLY = 1<<15;
401    static final int SCAN_DONT_KILL_APP = 1<<17;
402    static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404    static final int REMOVE_CHATTY = 1<<16;
405
406    private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408    /**
409     * Timeout (in milliseconds) after which the watchdog should declare that
410     * our handler thread is wedged.  The usual default for such things is one
411     * minute but we sometimes do very lengthy I/O operations on this thread,
412     * such as installing multi-gigabyte applications, so ours needs to be longer.
413     */
414    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416    /**
417     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419     * settings entry if available, otherwise we use the hardcoded default.  If it's been
420     * more than this long since the last fstrim, we force one during the boot sequence.
421     *
422     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423     * one gets run at the next available charging+idle time.  This final mandatory
424     * no-fstrim check kicks in only of the other scheduling criteria is never met.
425     */
426    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428    /**
429     * Whether verification is enabled by default.
430     */
431    private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433    /**
434     * The default maximum time to wait for the verification agent to return in
435     * milliseconds.
436     */
437    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439    /**
440     * The default response for package verification timeout.
441     *
442     * This can be either PackageManager.VERIFICATION_ALLOW or
443     * PackageManager.VERIFICATION_REJECT.
444     */
445    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447    static final String PLATFORM_PACKAGE_NAME = "android";
448
449    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452            DEFAULT_CONTAINER_PACKAGE,
453            "com.android.defcontainer.DefaultContainerService");
454
455    private static final String KILL_APP_REASON_GIDS_CHANGED =
456            "permission grant or revoke changed gids";
457
458    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459            "permissions revoked";
460
461    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463    private static final String PACKAGE_SCHEME = "package";
464
465    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
468    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
469
470    /** Permission grant: not grant the permission. */
471    private static final int GRANT_DENIED = 1;
472
473    /** Permission grant: grant the permission as an install permission. */
474    private static final int GRANT_INSTALL = 2;
475
476    /** Permission grant: grant the permission as a runtime one. */
477    private static final int GRANT_RUNTIME = 3;
478
479    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
480    private static final int GRANT_UPGRADE = 4;
481
482    /** Canonical intent used to identify what counts as a "web browser" app */
483    private static final Intent sBrowserIntent;
484    static {
485        sBrowserIntent = new Intent();
486        sBrowserIntent.setAction(Intent.ACTION_VIEW);
487        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
488        sBrowserIntent.setData(Uri.parse("http:"));
489    }
490
491    /**
492     * The set of all protected actions [i.e. those actions for which a high priority
493     * intent filter is disallowed].
494     */
495    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
496    static {
497        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
499        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
500        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
501    }
502
503    // Compilation reasons.
504    public static final int REASON_FIRST_BOOT = 0;
505    public static final int REASON_BOOT = 1;
506    public static final int REASON_INSTALL = 2;
507    public static final int REASON_BACKGROUND_DEXOPT = 3;
508    public static final int REASON_AB_OTA = 4;
509    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
510    public static final int REASON_SHARED_APK = 6;
511    public static final int REASON_FORCED_DEXOPT = 7;
512    public static final int REASON_CORE_APP = 8;
513
514    public static final int REASON_LAST = REASON_CORE_APP;
515
516    /** Special library name that skips shared libraries check during compilation. */
517    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
518
519    final ServiceThread mHandlerThread;
520
521    final PackageHandler mHandler;
522
523    private final ProcessLoggingHandler mProcessLoggingHandler;
524
525    /**
526     * Messages for {@link #mHandler} that need to wait for system ready before
527     * being dispatched.
528     */
529    private ArrayList<Message> mPostSystemReadyMessages;
530
531    final int mSdkVersion = Build.VERSION.SDK_INT;
532
533    final Context mContext;
534    final boolean mFactoryTest;
535    final boolean mOnlyCore;
536    final DisplayMetrics mMetrics;
537    final int mDefParseFlags;
538    final String[] mSeparateProcesses;
539    final boolean mIsUpgrade;
540    final boolean mIsPreNUpgrade;
541    final boolean mIsPreNMR1Upgrade;
542
543    @GuardedBy("mPackages")
544    private boolean mDexOptDialogShown;
545
546    /** The location for ASEC container files on internal storage. */
547    final String mAsecInternalPath;
548
549    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
550    // LOCK HELD.  Can be called with mInstallLock held.
551    @GuardedBy("mInstallLock")
552    final Installer mInstaller;
553
554    /** Directory where installed third-party apps stored */
555    final File mAppInstallDir;
556    final File mEphemeralInstallDir;
557
558    /**
559     * Directory to which applications installed internally have their
560     * 32 bit native libraries copied.
561     */
562    private File mAppLib32InstallDir;
563
564    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
565    // apps.
566    final File mDrmAppPrivateInstallDir;
567
568    // ----------------------------------------------------------------
569
570    // Lock for state used when installing and doing other long running
571    // operations.  Methods that must be called with this lock held have
572    // the suffix "LI".
573    final Object mInstallLock = new Object();
574
575    // ----------------------------------------------------------------
576
577    // Keys are String (package name), values are Package.  This also serves
578    // as the lock for the global state.  Methods that must be called with
579    // this lock held have the prefix "LP".
580    @GuardedBy("mPackages")
581    final ArrayMap<String, PackageParser.Package> mPackages =
582            new ArrayMap<String, PackageParser.Package>();
583
584    final ArrayMap<String, Set<String>> mKnownCodebase =
585            new ArrayMap<String, Set<String>>();
586
587    // Tracks available target package names -> overlay package paths.
588    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
589        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
590
591    /**
592     * Tracks new system packages [received in an OTA] that we expect to
593     * find updated user-installed versions. Keys are package name, values
594     * are package location.
595     */
596    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
597    /**
598     * Tracks high priority intent filters for protected actions. During boot, certain
599     * filter actions are protected and should never be allowed to have a high priority
600     * intent filter for them. However, there is one, and only one exception -- the
601     * setup wizard. It must be able to define a high priority intent filter for these
602     * actions to ensure there are no escapes from the wizard. We need to delay processing
603     * of these during boot as we need to look at all of the system packages in order
604     * to know which component is the setup wizard.
605     */
606    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
607    /**
608     * Whether or not processing protected filters should be deferred.
609     */
610    private boolean mDeferProtectedFilters = true;
611
612    /**
613     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
614     */
615    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
616    /**
617     * Whether or not system app permissions should be promoted from install to runtime.
618     */
619    boolean mPromoteSystemApps;
620
621    @GuardedBy("mPackages")
622    final Settings mSettings;
623
624    /**
625     * Set of package names that are currently "frozen", which means active
626     * surgery is being done on the code/data for that package. The platform
627     * will refuse to launch frozen packages to avoid race conditions.
628     *
629     * @see PackageFreezer
630     */
631    @GuardedBy("mPackages")
632    final ArraySet<String> mFrozenPackages = new ArraySet<>();
633
634    final ProtectedPackages mProtectedPackages;
635
636    boolean mFirstBoot;
637
638    // System configuration read by SystemConfig.
639    final int[] mGlobalGids;
640    final SparseArray<ArraySet<String>> mSystemPermissions;
641    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
642
643    // If mac_permissions.xml was found for seinfo labeling.
644    boolean mFoundPolicyFile;
645
646    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
647
648    public static final class SharedLibraryEntry {
649        public final String path;
650        public final String apk;
651
652        SharedLibraryEntry(String _path, String _apk) {
653            path = _path;
654            apk = _apk;
655        }
656    }
657
658    // Currently known shared libraries.
659    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
660            new ArrayMap<String, SharedLibraryEntry>();
661
662    // All available activities, for your resolving pleasure.
663    final ActivityIntentResolver mActivities =
664            new ActivityIntentResolver();
665
666    // All available receivers, for your resolving pleasure.
667    final ActivityIntentResolver mReceivers =
668            new ActivityIntentResolver();
669
670    // All available services, for your resolving pleasure.
671    final ServiceIntentResolver mServices = new ServiceIntentResolver();
672
673    // All available providers, for your resolving pleasure.
674    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
675
676    // Mapping from provider base names (first directory in content URI codePath)
677    // to the provider information.
678    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
679            new ArrayMap<String, PackageParser.Provider>();
680
681    // Mapping from instrumentation class names to info about them.
682    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
683            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
684
685    // Mapping from permission names to info about them.
686    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
687            new ArrayMap<String, PackageParser.PermissionGroup>();
688
689    // Packages whose data we have transfered into another package, thus
690    // should no longer exist.
691    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
692
693    // Broadcast actions that are only available to the system.
694    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
695
696    /** List of packages waiting for verification. */
697    final SparseArray<PackageVerificationState> mPendingVerification
698            = new SparseArray<PackageVerificationState>();
699
700    /** Set of packages associated with each app op permission. */
701    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
702
703    final PackageInstallerService mInstallerService;
704
705    private final PackageDexOptimizer mPackageDexOptimizer;
706
707    private AtomicInteger mNextMoveId = new AtomicInteger();
708    private final MoveCallbacks mMoveCallbacks;
709
710    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
711
712    // Cache of users who need badging.
713    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
714
715    /** Token for keys in mPendingVerification. */
716    private int mPendingVerificationToken = 0;
717
718    volatile boolean mSystemReady;
719    volatile boolean mSafeMode;
720    volatile boolean mHasSystemUidErrors;
721
722    ApplicationInfo mAndroidApplication;
723    final ActivityInfo mResolveActivity = new ActivityInfo();
724    final ResolveInfo mResolveInfo = new ResolveInfo();
725    ComponentName mResolveComponentName;
726    PackageParser.Package mPlatformPackage;
727    ComponentName mCustomResolverComponentName;
728
729    boolean mResolverReplaced = false;
730
731    private final @Nullable ComponentName mIntentFilterVerifierComponent;
732    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
733
734    private int mIntentFilterVerificationToken = 0;
735
736    /** Component that knows whether or not an ephemeral application exists */
737    final ComponentName mEphemeralResolverComponent;
738    /** The service connection to the ephemeral resolver */
739    final EphemeralResolverConnection mEphemeralResolverConnection;
740
741    /** Component used to install ephemeral applications */
742    final ComponentName mEphemeralInstallerComponent;
743    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
744    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
745
746    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
747            = new SparseArray<IntentFilterVerificationState>();
748
749    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
750
751    // List of packages names to keep cached, even if they are uninstalled for all users
752    private List<String> mKeepUninstalledPackages;
753
754    private UserManagerInternal mUserManagerInternal;
755
756    private static class IFVerificationParams {
757        PackageParser.Package pkg;
758        boolean replacing;
759        int userId;
760        int verifierUid;
761
762        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
763                int _userId, int _verifierUid) {
764            pkg = _pkg;
765            replacing = _replacing;
766            userId = _userId;
767            replacing = _replacing;
768            verifierUid = _verifierUid;
769        }
770    }
771
772    private interface IntentFilterVerifier<T extends IntentFilter> {
773        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
774                                               T filter, String packageName);
775        void startVerifications(int userId);
776        void receiveVerificationResponse(int verificationId);
777    }
778
779    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
780        private Context mContext;
781        private ComponentName mIntentFilterVerifierComponent;
782        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
783
784        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
785            mContext = context;
786            mIntentFilterVerifierComponent = verifierComponent;
787        }
788
789        private String getDefaultScheme() {
790            return IntentFilter.SCHEME_HTTPS;
791        }
792
793        @Override
794        public void startVerifications(int userId) {
795            // Launch verifications requests
796            int count = mCurrentIntentFilterVerifications.size();
797            for (int n=0; n<count; n++) {
798                int verificationId = mCurrentIntentFilterVerifications.get(n);
799                final IntentFilterVerificationState ivs =
800                        mIntentFilterVerificationStates.get(verificationId);
801
802                String packageName = ivs.getPackageName();
803
804                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
805                final int filterCount = filters.size();
806                ArraySet<String> domainsSet = new ArraySet<>();
807                for (int m=0; m<filterCount; m++) {
808                    PackageParser.ActivityIntentInfo filter = filters.get(m);
809                    domainsSet.addAll(filter.getHostsList());
810                }
811                synchronized (mPackages) {
812                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
813                            packageName, domainsSet) != null) {
814                        scheduleWriteSettingsLocked();
815                    }
816                }
817                sendVerificationRequest(userId, verificationId, ivs);
818            }
819            mCurrentIntentFilterVerifications.clear();
820        }
821
822        private void sendVerificationRequest(int userId, int verificationId,
823                IntentFilterVerificationState ivs) {
824
825            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
828                    verificationId);
829            verificationIntent.putExtra(
830                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
831                    getDefaultScheme());
832            verificationIntent.putExtra(
833                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
834                    ivs.getHostsString());
835            verificationIntent.putExtra(
836                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
837                    ivs.getPackageName());
838            verificationIntent.setComponent(mIntentFilterVerifierComponent);
839            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
840
841            UserHandle user = new UserHandle(userId);
842            mContext.sendBroadcastAsUser(verificationIntent, user);
843            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
844                    "Sending IntentFilter verification broadcast");
845        }
846
847        public void receiveVerificationResponse(int verificationId) {
848            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
849
850            final boolean verified = ivs.isVerified();
851
852            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
853            final int count = filters.size();
854            if (DEBUG_DOMAIN_VERIFICATION) {
855                Slog.i(TAG, "Received verification response " + verificationId
856                        + " for " + count + " filters, verified=" + verified);
857            }
858            for (int n=0; n<count; n++) {
859                PackageParser.ActivityIntentInfo filter = filters.get(n);
860                filter.setVerified(verified);
861
862                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
863                        + " verified with result:" + verified + " and hosts:"
864                        + ivs.getHostsString());
865            }
866
867            mIntentFilterVerificationStates.remove(verificationId);
868
869            final String packageName = ivs.getPackageName();
870            IntentFilterVerificationInfo ivi = null;
871
872            synchronized (mPackages) {
873                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
874            }
875            if (ivi == null) {
876                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
877                        + verificationId + " packageName:" + packageName);
878                return;
879            }
880            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
881                    "Updating IntentFilterVerificationInfo for package " + packageName
882                            +" verificationId:" + verificationId);
883
884            synchronized (mPackages) {
885                if (verified) {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
887                } else {
888                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
889                }
890                scheduleWriteSettingsLocked();
891
892                final int userId = ivs.getUserId();
893                if (userId != UserHandle.USER_ALL) {
894                    final int userStatus =
895                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
896
897                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
898                    boolean needUpdate = false;
899
900                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
901                    // already been set by the User thru the Disambiguation dialog
902                    switch (userStatus) {
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                            } else {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
908                            }
909                            needUpdate = true;
910                            break;
911
912                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
913                            if (verified) {
914                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
915                                needUpdate = true;
916                            }
917                            break;
918
919                        default:
920                            // Nothing to do
921                    }
922
923                    if (needUpdate) {
924                        mSettings.updateIntentFilterVerificationStatusLPw(
925                                packageName, updatedStatus, userId);
926                        scheduleWritePackageRestrictionsLocked(userId);
927                    }
928                }
929            }
930        }
931
932        @Override
933        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
934                    ActivityIntentInfo filter, String packageName) {
935            if (!hasValidDomains(filter)) {
936                return false;
937            }
938            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
939            if (ivs == null) {
940                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
941                        packageName);
942            }
943            if (DEBUG_DOMAIN_VERIFICATION) {
944                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
945            }
946            ivs.addFilter(filter);
947            return true;
948        }
949
950        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
951                int userId, int verificationId, String packageName) {
952            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
953                    verifierUid, userId, packageName);
954            ivs.setPendingState();
955            synchronized (mPackages) {
956                mIntentFilterVerificationStates.append(verificationId, ivs);
957                mCurrentIntentFilterVerifications.add(verificationId);
958            }
959            return ivs;
960        }
961    }
962
963    private static boolean hasValidDomains(ActivityIntentInfo filter) {
964        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
965                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
966                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
967    }
968
969    // Set of pending broadcasts for aggregating enable/disable of components.
970    static class PendingPackageBroadcasts {
971        // for each user id, a map of <package name -> components within that package>
972        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
973
974        public PendingPackageBroadcasts() {
975            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
976        }
977
978        public ArrayList<String> get(int userId, String packageName) {
979            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
980            return packages.get(packageName);
981        }
982
983        public void put(int userId, String packageName, ArrayList<String> components) {
984            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
985            packages.put(packageName, components);
986        }
987
988        public void remove(int userId, String packageName) {
989            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
990            if (packages != null) {
991                packages.remove(packageName);
992            }
993        }
994
995        public void remove(int userId) {
996            mUidMap.remove(userId);
997        }
998
999        public int userIdCount() {
1000            return mUidMap.size();
1001        }
1002
1003        public int userIdAt(int n) {
1004            return mUidMap.keyAt(n);
1005        }
1006
1007        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1008            return mUidMap.get(userId);
1009        }
1010
1011        public int size() {
1012            // total number of pending broadcast entries across all userIds
1013            int num = 0;
1014            for (int i = 0; i< mUidMap.size(); i++) {
1015                num += mUidMap.valueAt(i).size();
1016            }
1017            return num;
1018        }
1019
1020        public void clear() {
1021            mUidMap.clear();
1022        }
1023
1024        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1025            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1026            if (map == null) {
1027                map = new ArrayMap<String, ArrayList<String>>();
1028                mUidMap.put(userId, map);
1029            }
1030            return map;
1031        }
1032    }
1033    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1034
1035    // Service Connection to remote media container service to copy
1036    // package uri's from external media onto secure containers
1037    // or internal storage.
1038    private IMediaContainerService mContainerService = null;
1039
1040    static final int SEND_PENDING_BROADCAST = 1;
1041    static final int MCS_BOUND = 3;
1042    static final int END_COPY = 4;
1043    static final int INIT_COPY = 5;
1044    static final int MCS_UNBIND = 6;
1045    static final int START_CLEANING_PACKAGE = 7;
1046    static final int FIND_INSTALL_LOC = 8;
1047    static final int POST_INSTALL = 9;
1048    static final int MCS_RECONNECT = 10;
1049    static final int MCS_GIVE_UP = 11;
1050    static final int UPDATED_MEDIA_STATUS = 12;
1051    static final int WRITE_SETTINGS = 13;
1052    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1053    static final int PACKAGE_VERIFIED = 15;
1054    static final int CHECK_PENDING_VERIFICATION = 16;
1055    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1056    static final int INTENT_FILTER_VERIFIED = 18;
1057    static final int WRITE_PACKAGE_LIST = 19;
1058
1059    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1060
1061    // Delay time in millisecs
1062    static final int BROADCAST_DELAY = 10 * 1000;
1063
1064    static UserManagerService sUserManager;
1065
1066    // Stores a list of users whose package restrictions file needs to be updated
1067    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1068
1069    final private DefaultContainerConnection mDefContainerConn =
1070            new DefaultContainerConnection();
1071    class DefaultContainerConnection implements ServiceConnection {
1072        public void onServiceConnected(ComponentName name, IBinder service) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1074            IMediaContainerService imcs =
1075                IMediaContainerService.Stub.asInterface(service);
1076            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1077        }
1078
1079        public void onServiceDisconnected(ComponentName name) {
1080            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1081        }
1082    }
1083
1084    // Recordkeeping of restore-after-install operations that are currently in flight
1085    // between the Package Manager and the Backup Manager
1086    static class PostInstallData {
1087        public InstallArgs args;
1088        public PackageInstalledInfo res;
1089
1090        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1091            args = _a;
1092            res = _r;
1093        }
1094    }
1095
1096    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1097    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1098
1099    // XML tags for backup/restore of various bits of state
1100    private static final String TAG_PREFERRED_BACKUP = "pa";
1101    private static final String TAG_DEFAULT_APPS = "da";
1102    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1103
1104    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1105    private static final String TAG_ALL_GRANTS = "rt-grants";
1106    private static final String TAG_GRANT = "grant";
1107    private static final String ATTR_PACKAGE_NAME = "pkg";
1108
1109    private static final String TAG_PERMISSION = "perm";
1110    private static final String ATTR_PERMISSION_NAME = "name";
1111    private static final String ATTR_IS_GRANTED = "g";
1112    private static final String ATTR_USER_SET = "set";
1113    private static final String ATTR_USER_FIXED = "fixed";
1114    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1115
1116    // System/policy permission grants are not backed up
1117    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1118            FLAG_PERMISSION_POLICY_FIXED
1119            | FLAG_PERMISSION_SYSTEM_FIXED
1120            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1121
1122    // And we back up these user-adjusted states
1123    private static final int USER_RUNTIME_GRANT_MASK =
1124            FLAG_PERMISSION_USER_SET
1125            | FLAG_PERMISSION_USER_FIXED
1126            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1127
1128    final @Nullable String mRequiredVerifierPackage;
1129    final @NonNull String mRequiredInstallerPackage;
1130    final @NonNull String mRequiredUninstallerPackage;
1131    final @Nullable String mSetupWizardPackage;
1132    final @Nullable String mStorageManagerPackage;
1133    final @NonNull String mServicesSystemSharedLibraryPackageName;
1134    final @NonNull String mSharedSystemSharedLibraryPackageName;
1135
1136    final boolean mPermissionReviewRequired;
1137
1138    private final PackageUsage mPackageUsage = new PackageUsage();
1139    private final CompilerStats mCompilerStats = new CompilerStats();
1140
1141    class PackageHandler extends Handler {
1142        private boolean mBound = false;
1143        final ArrayList<HandlerParams> mPendingInstalls =
1144            new ArrayList<HandlerParams>();
1145
1146        private boolean connectToService() {
1147            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1148                    " DefaultContainerService");
1149            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1150            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1151            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1152                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1153                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1154                mBound = true;
1155                return true;
1156            }
1157            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158            return false;
1159        }
1160
1161        private void disconnectService() {
1162            mContainerService = null;
1163            mBound = false;
1164            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1165            mContext.unbindService(mDefContainerConn);
1166            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1167        }
1168
1169        PackageHandler(Looper looper) {
1170            super(looper);
1171        }
1172
1173        public void handleMessage(Message msg) {
1174            try {
1175                doHandleMessage(msg);
1176            } finally {
1177                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1178            }
1179        }
1180
1181        void doHandleMessage(Message msg) {
1182            switch (msg.what) {
1183                case INIT_COPY: {
1184                    HandlerParams params = (HandlerParams) msg.obj;
1185                    int idx = mPendingInstalls.size();
1186                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1187                    // If a bind was already initiated we dont really
1188                    // need to do anything. The pending install
1189                    // will be processed later on.
1190                    if (!mBound) {
1191                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1192                                System.identityHashCode(mHandler));
1193                        // If this is the only one pending we might
1194                        // have to bind to the service again.
1195                        if (!connectToService()) {
1196                            Slog.e(TAG, "Failed to bind to media container service");
1197                            params.serviceError();
1198                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199                                    System.identityHashCode(mHandler));
1200                            if (params.traceMethod != null) {
1201                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1202                                        params.traceCookie);
1203                            }
1204                            return;
1205                        } else {
1206                            // Once we bind to the service, the first
1207                            // pending request will be processed.
1208                            mPendingInstalls.add(idx, params);
1209                        }
1210                    } else {
1211                        mPendingInstalls.add(idx, params);
1212                        // Already bound to the service. Just make
1213                        // sure we trigger off processing the first request.
1214                        if (idx == 0) {
1215                            mHandler.sendEmptyMessage(MCS_BOUND);
1216                        }
1217                    }
1218                    break;
1219                }
1220                case MCS_BOUND: {
1221                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1222                    if (msg.obj != null) {
1223                        mContainerService = (IMediaContainerService) msg.obj;
1224                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1225                                System.identityHashCode(mHandler));
1226                    }
1227                    if (mContainerService == null) {
1228                        if (!mBound) {
1229                            // Something seriously wrong since we are not bound and we are not
1230                            // waiting for connection. Bail out.
1231                            Slog.e(TAG, "Cannot bind to media container service");
1232                            for (HandlerParams params : mPendingInstalls) {
1233                                // Indicate service bind error
1234                                params.serviceError();
1235                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1236                                        System.identityHashCode(params));
1237                                if (params.traceMethod != null) {
1238                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1239                                            params.traceMethod, params.traceCookie);
1240                                }
1241                                return;
1242                            }
1243                            mPendingInstalls.clear();
1244                        } else {
1245                            Slog.w(TAG, "Waiting to connect to media container service");
1246                        }
1247                    } else if (mPendingInstalls.size() > 0) {
1248                        HandlerParams params = mPendingInstalls.get(0);
1249                        if (params != null) {
1250                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1251                                    System.identityHashCode(params));
1252                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1253                            if (params.startCopy()) {
1254                                // We are done...  look for more work or to
1255                                // go idle.
1256                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1257                                        "Checking for more work or unbind...");
1258                                // Delete pending install
1259                                if (mPendingInstalls.size() > 0) {
1260                                    mPendingInstalls.remove(0);
1261                                }
1262                                if (mPendingInstalls.size() == 0) {
1263                                    if (mBound) {
1264                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1265                                                "Posting delayed MCS_UNBIND");
1266                                        removeMessages(MCS_UNBIND);
1267                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1268                                        // Unbind after a little delay, to avoid
1269                                        // continual thrashing.
1270                                        sendMessageDelayed(ubmsg, 10000);
1271                                    }
1272                                } else {
1273                                    // There are more pending requests in queue.
1274                                    // Just post MCS_BOUND message to trigger processing
1275                                    // of next pending install.
1276                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                            "Posting MCS_BOUND for next work");
1278                                    mHandler.sendEmptyMessage(MCS_BOUND);
1279                                }
1280                            }
1281                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1282                        }
1283                    } else {
1284                        // Should never happen ideally.
1285                        Slog.w(TAG, "Empty queue");
1286                    }
1287                    break;
1288                }
1289                case MCS_RECONNECT: {
1290                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1291                    if (mPendingInstalls.size() > 0) {
1292                        if (mBound) {
1293                            disconnectService();
1294                        }
1295                        if (!connectToService()) {
1296                            Slog.e(TAG, "Failed to bind to media container service");
1297                            for (HandlerParams params : mPendingInstalls) {
1298                                // Indicate service bind error
1299                                params.serviceError();
1300                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1301                                        System.identityHashCode(params));
1302                            }
1303                            mPendingInstalls.clear();
1304                        }
1305                    }
1306                    break;
1307                }
1308                case MCS_UNBIND: {
1309                    // If there is no actual work left, then time to unbind.
1310                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1311
1312                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1313                        if (mBound) {
1314                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1315
1316                            disconnectService();
1317                        }
1318                    } else if (mPendingInstalls.size() > 0) {
1319                        // There are more pending requests in queue.
1320                        // Just post MCS_BOUND message to trigger processing
1321                        // of next pending install.
1322                        mHandler.sendEmptyMessage(MCS_BOUND);
1323                    }
1324
1325                    break;
1326                }
1327                case MCS_GIVE_UP: {
1328                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1329                    HandlerParams params = mPendingInstalls.remove(0);
1330                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1331                            System.identityHashCode(params));
1332                    break;
1333                }
1334                case SEND_PENDING_BROADCAST: {
1335                    String packages[];
1336                    ArrayList<String> components[];
1337                    int size = 0;
1338                    int uids[];
1339                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340                    synchronized (mPackages) {
1341                        if (mPendingBroadcasts == null) {
1342                            return;
1343                        }
1344                        size = mPendingBroadcasts.size();
1345                        if (size <= 0) {
1346                            // Nothing to be done. Just return
1347                            return;
1348                        }
1349                        packages = new String[size];
1350                        components = new ArrayList[size];
1351                        uids = new int[size];
1352                        int i = 0;  // filling out the above arrays
1353
1354                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1355                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1356                            Iterator<Map.Entry<String, ArrayList<String>>> it
1357                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1358                                            .entrySet().iterator();
1359                            while (it.hasNext() && i < size) {
1360                                Map.Entry<String, ArrayList<String>> ent = it.next();
1361                                packages[i] = ent.getKey();
1362                                components[i] = ent.getValue();
1363                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1364                                uids[i] = (ps != null)
1365                                        ? UserHandle.getUid(packageUserId, ps.appId)
1366                                        : -1;
1367                                i++;
1368                            }
1369                        }
1370                        size = i;
1371                        mPendingBroadcasts.clear();
1372                    }
1373                    // Send broadcasts
1374                    for (int i = 0; i < size; i++) {
1375                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1376                    }
1377                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1378                    break;
1379                }
1380                case START_CLEANING_PACKAGE: {
1381                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1382                    final String packageName = (String)msg.obj;
1383                    final int userId = msg.arg1;
1384                    final boolean andCode = msg.arg2 != 0;
1385                    synchronized (mPackages) {
1386                        if (userId == UserHandle.USER_ALL) {
1387                            int[] users = sUserManager.getUserIds();
1388                            for (int user : users) {
1389                                mSettings.addPackageToCleanLPw(
1390                                        new PackageCleanItem(user, packageName, andCode));
1391                            }
1392                        } else {
1393                            mSettings.addPackageToCleanLPw(
1394                                    new PackageCleanItem(userId, packageName, andCode));
1395                        }
1396                    }
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1398                    startCleaningPackages();
1399                } break;
1400                case POST_INSTALL: {
1401                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1402
1403                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1404                    final boolean didRestore = (msg.arg2 != 0);
1405                    mRunningInstalls.delete(msg.arg1);
1406
1407                    if (data != null) {
1408                        InstallArgs args = data.args;
1409                        PackageInstalledInfo parentRes = data.res;
1410
1411                        final boolean grantPermissions = (args.installFlags
1412                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1413                        final boolean killApp = (args.installFlags
1414                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1415                        final String[] grantedPermissions = args.installGrantPermissions;
1416
1417                        // Handle the parent package
1418                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1419                                grantedPermissions, didRestore, args.installerPackageName,
1420                                args.observer);
1421
1422                        // Handle the child packages
1423                        final int childCount = (parentRes.addedChildPackages != null)
1424                                ? parentRes.addedChildPackages.size() : 0;
1425                        for (int i = 0; i < childCount; i++) {
1426                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1427                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1428                                    grantedPermissions, false, args.installerPackageName,
1429                                    args.observer);
1430                        }
1431
1432                        // Log tracing if needed
1433                        if (args.traceMethod != null) {
1434                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1435                                    args.traceCookie);
1436                        }
1437                    } else {
1438                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1439                    }
1440
1441                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1442                } break;
1443                case UPDATED_MEDIA_STATUS: {
1444                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1445                    boolean reportStatus = msg.arg1 == 1;
1446                    boolean doGc = msg.arg2 == 1;
1447                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1448                    if (doGc) {
1449                        // Force a gc to clear up stale containers.
1450                        Runtime.getRuntime().gc();
1451                    }
1452                    if (msg.obj != null) {
1453                        @SuppressWarnings("unchecked")
1454                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1455                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1456                        // Unload containers
1457                        unloadAllContainers(args);
1458                    }
1459                    if (reportStatus) {
1460                        try {
1461                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1462                            PackageHelper.getMountService().finishMediaUpdate();
1463                        } catch (RemoteException e) {
1464                            Log.e(TAG, "MountService not running?");
1465                        }
1466                    }
1467                } break;
1468                case WRITE_SETTINGS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_SETTINGS);
1472                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1473                        mSettings.writeLPr();
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case WRITE_PACKAGE_RESTRICTIONS: {
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480                    synchronized (mPackages) {
1481                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1482                        for (int userId : mDirtyUsers) {
1483                            mSettings.writePackageRestrictionsLPr(userId);
1484                        }
1485                        mDirtyUsers.clear();
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                } break;
1489                case WRITE_PACKAGE_LIST: {
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1491                    synchronized (mPackages) {
1492                        removeMessages(WRITE_PACKAGE_LIST);
1493                        mSettings.writePackageListLPr(msg.arg1);
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                } break;
1497                case CHECK_PENDING_VERIFICATION: {
1498                    final int verificationId = msg.arg1;
1499                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1500
1501                    if ((state != null) && !state.timeoutExtended()) {
1502                        final InstallArgs args = state.getInstallArgs();
1503                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1504
1505                        Slog.i(TAG, "Verification timed out for " + originUri);
1506                        mPendingVerification.remove(verificationId);
1507
1508                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1509
1510                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1511                            Slog.i(TAG, "Continuing with installation of " + originUri);
1512                            state.setVerifierResponse(Binder.getCallingUid(),
1513                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1514                            broadcastPackageVerified(verificationId, originUri,
1515                                    PackageManager.VERIFICATION_ALLOW,
1516                                    state.getInstallArgs().getUser());
1517                            try {
1518                                ret = args.copyApk(mContainerService, true);
1519                            } catch (RemoteException e) {
1520                                Slog.e(TAG, "Could not contact the ContainerService");
1521                            }
1522                        } else {
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_REJECT,
1525                                    state.getInstallArgs().getUser());
1526                        }
1527
1528                        Trace.asyncTraceEnd(
1529                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1530
1531                        processPendingInstall(args, ret);
1532                        mHandler.sendEmptyMessage(MCS_UNBIND);
1533                    }
1534                    break;
1535                }
1536                case PACKAGE_VERIFIED: {
1537                    final int verificationId = msg.arg1;
1538
1539                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1540                    if (state == null) {
1541                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1542                        break;
1543                    }
1544
1545                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1546
1547                    state.setVerifierResponse(response.callerUid, response.code);
1548
1549                    if (state.isVerificationComplete()) {
1550                        mPendingVerification.remove(verificationId);
1551
1552                        final InstallArgs args = state.getInstallArgs();
1553                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1554
1555                        int ret;
1556                        if (state.isInstallAllowed()) {
1557                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1558                            broadcastPackageVerified(verificationId, originUri,
1559                                    response.code, state.getInstallArgs().getUser());
1560                            try {
1561                                ret = args.copyApk(mContainerService, true);
1562                            } catch (RemoteException e) {
1563                                Slog.e(TAG, "Could not contact the ContainerService");
1564                            }
1565                        } else {
1566                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1567                        }
1568
1569                        Trace.asyncTraceEnd(
1570                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1571
1572                        processPendingInstall(args, ret);
1573                        mHandler.sendEmptyMessage(MCS_UNBIND);
1574                    }
1575
1576                    break;
1577                }
1578                case START_INTENT_FILTER_VERIFICATIONS: {
1579                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1580                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1581                            params.replacing, params.pkg);
1582                    break;
1583                }
1584                case INTENT_FILTER_VERIFIED: {
1585                    final int verificationId = msg.arg1;
1586
1587                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1588                            verificationId);
1589                    if (state == null) {
1590                        Slog.w(TAG, "Invalid IntentFilter verification token "
1591                                + verificationId + " received");
1592                        break;
1593                    }
1594
1595                    final int userId = state.getUserId();
1596
1597                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                            "Processing IntentFilter verification with token:"
1599                            + verificationId + " and userId:" + userId);
1600
1601                    final IntentFilterVerificationResponse response =
1602                            (IntentFilterVerificationResponse) msg.obj;
1603
1604                    state.setVerifierResponse(response.callerUid, response.code);
1605
1606                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1607                            "IntentFilter verification with token:" + verificationId
1608                            + " and userId:" + userId
1609                            + " is settings verifier response with response code:"
1610                            + response.code);
1611
1612                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1614                                + response.getFailedDomainsString());
1615                    }
1616
1617                    if (state.isVerificationComplete()) {
1618                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1619                    } else {
1620                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1621                                "IntentFilter verification with token:" + verificationId
1622                                + " was not said to be complete");
1623                    }
1624
1625                    break;
1626                }
1627            }
1628        }
1629    }
1630
1631    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1632            boolean killApp, String[] grantedPermissions,
1633            boolean launchedForRestore, String installerPackage,
1634            IPackageInstallObserver2 installObserver) {
1635        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1636            // Send the removed broadcasts
1637            if (res.removedInfo != null) {
1638                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1639            }
1640
1641            // Now that we successfully installed the package, grant runtime
1642            // permissions if requested before broadcasting the install.
1643            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1644                    >= Build.VERSION_CODES.M) {
1645                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1646            }
1647
1648            final boolean update = res.removedInfo != null
1649                    && res.removedInfo.removedPackage != null;
1650
1651            // If this is the first time we have child packages for a disabled privileged
1652            // app that had no children, we grant requested runtime permissions to the new
1653            // children if the parent on the system image had them already granted.
1654            if (res.pkg.parentPackage != null) {
1655                synchronized (mPackages) {
1656                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1657                }
1658            }
1659
1660            synchronized (mPackages) {
1661                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1662            }
1663
1664            final String packageName = res.pkg.applicationInfo.packageName;
1665            Bundle extras = new Bundle(1);
1666            extras.putInt(Intent.EXTRA_UID, res.uid);
1667
1668            // Determine the set of users who are adding this package for
1669            // the first time vs. those who are seeing an update.
1670            int[] firstUsers = EMPTY_INT_ARRAY;
1671            int[] updateUsers = EMPTY_INT_ARRAY;
1672            if (res.origUsers == null || res.origUsers.length == 0) {
1673                firstUsers = res.newUsers;
1674            } else {
1675                for (int newUser : res.newUsers) {
1676                    boolean isNew = true;
1677                    for (int origUser : res.origUsers) {
1678                        if (origUser == newUser) {
1679                            isNew = false;
1680                            break;
1681                        }
1682                    }
1683                    if (isNew) {
1684                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1685                    } else {
1686                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1687                    }
1688                }
1689            }
1690
1691            // Send installed broadcasts if the install/update is not ephemeral
1692            if (!isEphemeral(res.pkg)) {
1693                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1694
1695                // Send added for users that see the package for the first time
1696                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1697                        extras, 0 /*flags*/, null /*targetPackage*/,
1698                        null /*finishedReceiver*/, firstUsers);
1699
1700                // Send added for users that don't see the package for the first time
1701                if (update) {
1702                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1703                }
1704                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                        extras, 0 /*flags*/, null /*targetPackage*/,
1706                        null /*finishedReceiver*/, updateUsers);
1707
1708                // Send replaced for users that don't see the package for the first time
1709                if (update) {
1710                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1711                            packageName, extras, 0 /*flags*/,
1712                            null /*targetPackage*/, null /*finishedReceiver*/,
1713                            updateUsers);
1714                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1715                            null /*package*/, null /*extras*/, 0 /*flags*/,
1716                            packageName /*targetPackage*/,
1717                            null /*finishedReceiver*/, updateUsers);
1718                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1719                    // First-install and we did a restore, so we're responsible for the
1720                    // first-launch broadcast.
1721                    if (DEBUG_BACKUP) {
1722                        Slog.i(TAG, "Post-restore of " + packageName
1723                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1724                    }
1725                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1726                }
1727
1728                // Send broadcast package appeared if forward locked/external for all users
1729                // treat asec-hosted packages like removable media on upgrade
1730                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1731                    if (DEBUG_INSTALL) {
1732                        Slog.i(TAG, "upgrading pkg " + res.pkg
1733                                + " is ASEC-hosted -> AVAILABLE");
1734                    }
1735                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1736                    ArrayList<String> pkgList = new ArrayList<>(1);
1737                    pkgList.add(packageName);
1738                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1739                }
1740            }
1741
1742            // Work that needs to happen on first install within each user
1743            if (firstUsers != null && firstUsers.length > 0) {
1744                synchronized (mPackages) {
1745                    for (int userId : firstUsers) {
1746                        // If this app is a browser and it's newly-installed for some
1747                        // users, clear any default-browser state in those users. The
1748                        // app's nature doesn't depend on the user, so we can just check
1749                        // its browser nature in any user and generalize.
1750                        if (packageIsBrowser(packageName, userId)) {
1751                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1752                        }
1753
1754                        // We may also need to apply pending (restored) runtime
1755                        // permission grants within these users.
1756                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1757                    }
1758                }
1759            }
1760
1761            // Log current value of "unknown sources" setting
1762            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1763                    getUnknownSourcesSettings());
1764
1765            // Force a gc to clear up things
1766            Runtime.getRuntime().gc();
1767
1768            // Remove the replaced package's older resources safely now
1769            // We delete after a gc for applications  on sdcard.
1770            if (res.removedInfo != null && res.removedInfo.args != null) {
1771                synchronized (mInstallLock) {
1772                    res.removedInfo.args.doPostDeleteLI(true);
1773                }
1774            }
1775        }
1776
1777        // If someone is watching installs - notify them
1778        if (installObserver != null) {
1779            try {
1780                Bundle extras = extrasForInstallResult(res);
1781                installObserver.onPackageInstalled(res.name, res.returnCode,
1782                        res.returnMsg, extras);
1783            } catch (RemoteException e) {
1784                Slog.i(TAG, "Observer no longer exists.");
1785            }
1786        }
1787    }
1788
1789    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1790            PackageParser.Package pkg) {
1791        if (pkg.parentPackage == null) {
1792            return;
1793        }
1794        if (pkg.requestedPermissions == null) {
1795            return;
1796        }
1797        final PackageSetting disabledSysParentPs = mSettings
1798                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1799        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1800                || !disabledSysParentPs.isPrivileged()
1801                || (disabledSysParentPs.childPackageNames != null
1802                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1803            return;
1804        }
1805        final int[] allUserIds = sUserManager.getUserIds();
1806        final int permCount = pkg.requestedPermissions.size();
1807        for (int i = 0; i < permCount; i++) {
1808            String permission = pkg.requestedPermissions.get(i);
1809            BasePermission bp = mSettings.mPermissions.get(permission);
1810            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1811                continue;
1812            }
1813            for (int userId : allUserIds) {
1814                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1815                        permission, userId)) {
1816                    grantRuntimePermission(pkg.packageName, permission, userId);
1817                }
1818            }
1819        }
1820    }
1821
1822    private StorageEventListener mStorageListener = new StorageEventListener() {
1823        @Override
1824        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1825            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1826                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1827                    final String volumeUuid = vol.getFsUuid();
1828
1829                    // Clean up any users or apps that were removed or recreated
1830                    // while this volume was missing
1831                    reconcileUsers(volumeUuid);
1832                    reconcileApps(volumeUuid);
1833
1834                    // Clean up any install sessions that expired or were
1835                    // cancelled while this volume was missing
1836                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1837
1838                    loadPrivatePackages(vol);
1839
1840                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1841                    unloadPrivatePackages(vol);
1842                }
1843            }
1844
1845            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1846                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1847                    updateExternalMediaStatus(true, false);
1848                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849                    updateExternalMediaStatus(false, false);
1850                }
1851            }
1852        }
1853
1854        @Override
1855        public void onVolumeForgotten(String fsUuid) {
1856            if (TextUtils.isEmpty(fsUuid)) {
1857                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1858                return;
1859            }
1860
1861            // Remove any apps installed on the forgotten volume
1862            synchronized (mPackages) {
1863                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1864                for (PackageSetting ps : packages) {
1865                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1866                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1867                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1868                }
1869
1870                mSettings.onVolumeForgotten(fsUuid);
1871                mSettings.writeLPr();
1872            }
1873        }
1874    };
1875
1876    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1877            String[] grantedPermissions) {
1878        for (int userId : userIds) {
1879            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1880        }
1881
1882        // We could have touched GID membership, so flush out packages.list
1883        synchronized (mPackages) {
1884            mSettings.writePackageListLPr();
1885        }
1886    }
1887
1888    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1889            String[] grantedPermissions) {
1890        SettingBase sb = (SettingBase) pkg.mExtras;
1891        if (sb == null) {
1892            return;
1893        }
1894
1895        PermissionsState permissionsState = sb.getPermissionsState();
1896
1897        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1898                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1899
1900        for (String permission : pkg.requestedPermissions) {
1901            final BasePermission bp;
1902            synchronized (mPackages) {
1903                bp = mSettings.mPermissions.get(permission);
1904            }
1905            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1906                    && (grantedPermissions == null
1907                           || ArrayUtils.contains(grantedPermissions, permission))) {
1908                final int flags = permissionsState.getPermissionFlags(permission, userId);
1909                // Installer cannot change immutable permissions.
1910                if ((flags & immutableFlags) == 0) {
1911                    grantRuntimePermission(pkg.packageName, permission, userId);
1912                }
1913            }
1914        }
1915    }
1916
1917    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1918        Bundle extras = null;
1919        switch (res.returnCode) {
1920            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1921                extras = new Bundle();
1922                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1923                        res.origPermission);
1924                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1925                        res.origPackage);
1926                break;
1927            }
1928            case PackageManager.INSTALL_SUCCEEDED: {
1929                extras = new Bundle();
1930                extras.putBoolean(Intent.EXTRA_REPLACING,
1931                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1932                break;
1933            }
1934        }
1935        return extras;
1936    }
1937
1938    void scheduleWriteSettingsLocked() {
1939        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1940            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1941        }
1942    }
1943
1944    void scheduleWritePackageListLocked(int userId) {
1945        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1946            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1947            msg.arg1 = userId;
1948            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1949        }
1950    }
1951
1952    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1953        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1954        scheduleWritePackageRestrictionsLocked(userId);
1955    }
1956
1957    void scheduleWritePackageRestrictionsLocked(int userId) {
1958        final int[] userIds = (userId == UserHandle.USER_ALL)
1959                ? sUserManager.getUserIds() : new int[]{userId};
1960        for (int nextUserId : userIds) {
1961            if (!sUserManager.exists(nextUserId)) return;
1962            mDirtyUsers.add(nextUserId);
1963            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1964                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1965            }
1966        }
1967    }
1968
1969    public static PackageManagerService main(Context context, Installer installer,
1970            boolean factoryTest, boolean onlyCore) {
1971        // Self-check for initial settings.
1972        PackageManagerServiceCompilerMapping.checkProperties();
1973
1974        PackageManagerService m = new PackageManagerService(context, installer,
1975                factoryTest, onlyCore);
1976        m.enableSystemUserPackages();
1977        ServiceManager.addService("package", m);
1978        return m;
1979    }
1980
1981    private void enableSystemUserPackages() {
1982        if (!UserManager.isSplitSystemUser()) {
1983            return;
1984        }
1985        // For system user, enable apps based on the following conditions:
1986        // - app is whitelisted or belong to one of these groups:
1987        //   -- system app which has no launcher icons
1988        //   -- system app which has INTERACT_ACROSS_USERS permission
1989        //   -- system IME app
1990        // - app is not in the blacklist
1991        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1992        Set<String> enableApps = new ArraySet<>();
1993        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1994                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1995                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1996        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1997        enableApps.addAll(wlApps);
1998        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1999                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2000        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2001        enableApps.removeAll(blApps);
2002        Log.i(TAG, "Applications installed for system user: " + enableApps);
2003        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2004                UserHandle.SYSTEM);
2005        final int allAppsSize = allAps.size();
2006        synchronized (mPackages) {
2007            for (int i = 0; i < allAppsSize; i++) {
2008                String pName = allAps.get(i);
2009                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2010                // Should not happen, but we shouldn't be failing if it does
2011                if (pkgSetting == null) {
2012                    continue;
2013                }
2014                boolean install = enableApps.contains(pName);
2015                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2016                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2017                            + " for system user");
2018                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2019                }
2020            }
2021        }
2022    }
2023
2024    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2025        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2026                Context.DISPLAY_SERVICE);
2027        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2028    }
2029
2030    /**
2031     * Requests that files preopted on a secondary system partition be copied to the data partition
2032     * if possible.  Note that the actual copying of the files is accomplished by init for security
2033     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2034     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2035     */
2036    private static void requestCopyPreoptedFiles() {
2037        final int WAIT_TIME_MS = 100;
2038        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2039        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2040            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2041            // We will wait for up to 100 seconds.
2042            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2043            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2044                try {
2045                    Thread.sleep(WAIT_TIME_MS);
2046                } catch (InterruptedException e) {
2047                    // Do nothing
2048                }
2049                if (SystemClock.uptimeMillis() > timeEnd) {
2050                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2051                    Slog.wtf(TAG, "cppreopt did not finish!");
2052                    break;
2053                }
2054            }
2055        }
2056    }
2057
2058    public PackageManagerService(Context context, Installer installer,
2059            boolean factoryTest, boolean onlyCore) {
2060        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2061        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2062                SystemClock.uptimeMillis());
2063
2064        if (mSdkVersion <= 0) {
2065            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2066        }
2067
2068        mContext = context;
2069
2070        mPermissionReviewRequired = context.getResources().getBoolean(
2071                R.bool.config_permissionReviewRequired);
2072
2073        mFactoryTest = factoryTest;
2074        mOnlyCore = onlyCore;
2075        mMetrics = new DisplayMetrics();
2076        mSettings = new Settings(mPackages);
2077        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2078                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2079        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2080                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2081        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2082                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2083        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2084                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2085        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2086                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2088                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089
2090        String separateProcesses = SystemProperties.get("debug.separate_processes");
2091        if (separateProcesses != null && separateProcesses.length() > 0) {
2092            if ("*".equals(separateProcesses)) {
2093                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2094                mSeparateProcesses = null;
2095                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2096            } else {
2097                mDefParseFlags = 0;
2098                mSeparateProcesses = separateProcesses.split(",");
2099                Slog.w(TAG, "Running with debug.separate_processes: "
2100                        + separateProcesses);
2101            }
2102        } else {
2103            mDefParseFlags = 0;
2104            mSeparateProcesses = null;
2105        }
2106
2107        mInstaller = installer;
2108        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2109                "*dexopt*");
2110        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2111
2112        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2113                FgThread.get().getLooper());
2114
2115        getDefaultDisplayMetrics(context, mMetrics);
2116
2117        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2118        SystemConfig systemConfig = SystemConfig.getInstance();
2119        mGlobalGids = systemConfig.getGlobalGids();
2120        mSystemPermissions = systemConfig.getSystemPermissions();
2121        mAvailableFeatures = systemConfig.getAvailableFeatures();
2122        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2123
2124        mProtectedPackages = new ProtectedPackages(mContext);
2125
2126        synchronized (mInstallLock) {
2127        // writer
2128        synchronized (mPackages) {
2129            mHandlerThread = new ServiceThread(TAG,
2130                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2131            mHandlerThread.start();
2132            mHandler = new PackageHandler(mHandlerThread.getLooper());
2133            mProcessLoggingHandler = new ProcessLoggingHandler();
2134            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2135
2136            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2137
2138            File dataDir = Environment.getDataDirectory();
2139            mAppInstallDir = new File(dataDir, "app");
2140            mAppLib32InstallDir = new File(dataDir, "app-lib");
2141            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2142            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2143            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2144
2145            sUserManager = new UserManagerService(context, this, mPackages);
2146
2147            // Propagate permission configuration in to package manager.
2148            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2149                    = systemConfig.getPermissions();
2150            for (int i=0; i<permConfig.size(); i++) {
2151                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2152                BasePermission bp = mSettings.mPermissions.get(perm.name);
2153                if (bp == null) {
2154                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2155                    mSettings.mPermissions.put(perm.name, bp);
2156                }
2157                if (perm.gids != null) {
2158                    bp.setGids(perm.gids, perm.perUser);
2159                }
2160            }
2161
2162            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2163            for (int i=0; i<libConfig.size(); i++) {
2164                mSharedLibraries.put(libConfig.keyAt(i),
2165                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2166            }
2167
2168            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2169
2170            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2171            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2172            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2173
2174            if (mFirstBoot) {
2175                requestCopyPreoptedFiles();
2176            }
2177
2178            String customResolverActivity = Resources.getSystem().getString(
2179                    R.string.config_customResolverActivity);
2180            if (TextUtils.isEmpty(customResolverActivity)) {
2181                customResolverActivity = null;
2182            } else {
2183                mCustomResolverComponentName = ComponentName.unflattenFromString(
2184                        customResolverActivity);
2185            }
2186
2187            long startTime = SystemClock.uptimeMillis();
2188
2189            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2190                    startTime);
2191
2192            // Set flag to monitor and not change apk file paths when
2193            // scanning install directories.
2194            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2195
2196            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2197            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2198
2199            if (bootClassPath == null) {
2200                Slog.w(TAG, "No BOOTCLASSPATH found!");
2201            }
2202
2203            if (systemServerClassPath == null) {
2204                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2205            }
2206
2207            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2208            final String[] dexCodeInstructionSets =
2209                    getDexCodeInstructionSets(
2210                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2211
2212            /**
2213             * Ensure all external libraries have had dexopt run on them.
2214             */
2215            if (mSharedLibraries.size() > 0) {
2216                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2217                // NOTE: For now, we're compiling these system "shared libraries"
2218                // (and framework jars) into all available architectures. It's possible
2219                // to compile them only when we come across an app that uses them (there's
2220                // already logic for that in scanPackageLI) but that adds some complexity.
2221                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2222                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2223                        final String lib = libEntry.path;
2224                        if (lib == null) {
2225                            continue;
2226                        }
2227
2228                        try {
2229                            // Shared libraries do not have profiles so we perform a full
2230                            // AOT compilation (if needed).
2231                            int dexoptNeeded = DexFile.getDexOptNeeded(
2232                                    lib, dexCodeInstructionSet,
2233                                    getCompilerFilterForReason(REASON_SHARED_APK),
2234                                    false /* newProfile */);
2235                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2236                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2237                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2238                                        getCompilerFilterForReason(REASON_SHARED_APK),
2239                                        StorageManager.UUID_PRIVATE_INTERNAL,
2240                                        SKIP_SHARED_LIBRARY_CHECK);
2241                            }
2242                        } catch (FileNotFoundException e) {
2243                            Slog.w(TAG, "Library not found: " + lib);
2244                        } catch (IOException | InstallerException e) {
2245                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2246                                    + e.getMessage());
2247                        }
2248                    }
2249                }
2250                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2251            }
2252
2253            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2254
2255            final VersionInfo ver = mSettings.getInternalVersion();
2256            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2257
2258            // when upgrading from pre-M, promote system app permissions from install to runtime
2259            mPromoteSystemApps =
2260                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2261
2262            // When upgrading from pre-N, we need to handle package extraction like first boot,
2263            // as there is no profiling data available.
2264            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2265
2266            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2267
2268            // save off the names of pre-existing system packages prior to scanning; we don't
2269            // want to automatically grant runtime permissions for new system apps
2270            if (mPromoteSystemApps) {
2271                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2272                while (pkgSettingIter.hasNext()) {
2273                    PackageSetting ps = pkgSettingIter.next();
2274                    if (isSystemApp(ps)) {
2275                        mExistingSystemPackages.add(ps.name);
2276                    }
2277                }
2278            }
2279
2280            // Collect vendor overlay packages.
2281            // (Do this before scanning any apps.)
2282            // For security and version matching reason, only consider
2283            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2284            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2285            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2286                    | PackageParser.PARSE_IS_SYSTEM
2287                    | PackageParser.PARSE_IS_SYSTEM_DIR
2288                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2289
2290            // Find base frameworks (resource packages without code).
2291            scanDirTracedLI(frameworkDir, mDefParseFlags
2292                    | PackageParser.PARSE_IS_SYSTEM
2293                    | PackageParser.PARSE_IS_SYSTEM_DIR
2294                    | PackageParser.PARSE_IS_PRIVILEGED,
2295                    scanFlags | SCAN_NO_DEX, 0);
2296
2297            // Collected privileged system packages.
2298            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2299            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2300                    | PackageParser.PARSE_IS_SYSTEM
2301                    | PackageParser.PARSE_IS_SYSTEM_DIR
2302                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2303
2304            // Collect ordinary system packages.
2305            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2306            scanDirTracedLI(systemAppDir, mDefParseFlags
2307                    | PackageParser.PARSE_IS_SYSTEM
2308                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2309
2310            // Collect all vendor packages.
2311            File vendorAppDir = new File("/vendor/app");
2312            try {
2313                vendorAppDir = vendorAppDir.getCanonicalFile();
2314            } catch (IOException e) {
2315                // failed to look up canonical path, continue with original one
2316            }
2317            scanDirTracedLI(vendorAppDir, mDefParseFlags
2318                    | PackageParser.PARSE_IS_SYSTEM
2319                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2320
2321            // Collect all OEM packages.
2322            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2323            scanDirTracedLI(oemAppDir, mDefParseFlags
2324                    | PackageParser.PARSE_IS_SYSTEM
2325                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2326
2327            // Prune any system packages that no longer exist.
2328            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2329            if (!mOnlyCore) {
2330                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2331                while (psit.hasNext()) {
2332                    PackageSetting ps = psit.next();
2333
2334                    /*
2335                     * If this is not a system app, it can't be a
2336                     * disable system app.
2337                     */
2338                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2339                        continue;
2340                    }
2341
2342                    /*
2343                     * If the package is scanned, it's not erased.
2344                     */
2345                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2346                    if (scannedPkg != null) {
2347                        /*
2348                         * If the system app is both scanned and in the
2349                         * disabled packages list, then it must have been
2350                         * added via OTA. Remove it from the currently
2351                         * scanned package so the previously user-installed
2352                         * application can be scanned.
2353                         */
2354                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2355                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2356                                    + ps.name + "; removing system app.  Last known codePath="
2357                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2358                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2359                                    + scannedPkg.mVersionCode);
2360                            removePackageLI(scannedPkg, true);
2361                            mExpectingBetter.put(ps.name, ps.codePath);
2362                        }
2363
2364                        continue;
2365                    }
2366
2367                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2368                        psit.remove();
2369                        logCriticalInfo(Log.WARN, "System package " + ps.name
2370                                + " no longer exists; it's data will be wiped");
2371                        // Actual deletion of code and data will be handled by later
2372                        // reconciliation step
2373                    } else {
2374                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2375                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2376                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2377                        }
2378                    }
2379                }
2380            }
2381
2382            //look for any incomplete package installations
2383            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2384            for (int i = 0; i < deletePkgsList.size(); i++) {
2385                // Actual deletion of code and data will be handled by later
2386                // reconciliation step
2387                final String packageName = deletePkgsList.get(i).name;
2388                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2389                synchronized (mPackages) {
2390                    mSettings.removePackageLPw(packageName);
2391                }
2392            }
2393
2394            //delete tmp files
2395            deleteTempPackageFiles();
2396
2397            // Remove any shared userIDs that have no associated packages
2398            mSettings.pruneSharedUsersLPw();
2399
2400            if (!mOnlyCore) {
2401                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2402                        SystemClock.uptimeMillis());
2403                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2404
2405                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2406                        | PackageParser.PARSE_FORWARD_LOCK,
2407                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2408
2409                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2410                        | PackageParser.PARSE_IS_EPHEMERAL,
2411                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2412
2413                /**
2414                 * Remove disable package settings for any updated system
2415                 * apps that were removed via an OTA. If they're not a
2416                 * previously-updated app, remove them completely.
2417                 * Otherwise, just revoke their system-level permissions.
2418                 */
2419                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2420                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2421                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2422
2423                    String msg;
2424                    if (deletedPkg == null) {
2425                        msg = "Updated system package " + deletedAppName
2426                                + " no longer exists; it's data will be wiped";
2427                        // Actual deletion of code and data will be handled by later
2428                        // reconciliation step
2429                    } else {
2430                        msg = "Updated system app + " + deletedAppName
2431                                + " no longer present; removing system privileges for "
2432                                + deletedAppName;
2433
2434                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2435
2436                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2437                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2438                    }
2439                    logCriticalInfo(Log.WARN, msg);
2440                }
2441
2442                /**
2443                 * Make sure all system apps that we expected to appear on
2444                 * the userdata partition actually showed up. If they never
2445                 * appeared, crawl back and revive the system version.
2446                 */
2447                for (int i = 0; i < mExpectingBetter.size(); i++) {
2448                    final String packageName = mExpectingBetter.keyAt(i);
2449                    if (!mPackages.containsKey(packageName)) {
2450                        final File scanFile = mExpectingBetter.valueAt(i);
2451
2452                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2453                                + " but never showed up; reverting to system");
2454
2455                        int reparseFlags = mDefParseFlags;
2456                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2457                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2458                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2459                                    | PackageParser.PARSE_IS_PRIVILEGED;
2460                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2461                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2462                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2463                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2464                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2465                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2466                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2467                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2468                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2469                        } else {
2470                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2471                            continue;
2472                        }
2473
2474                        mSettings.enableSystemPackageLPw(packageName);
2475
2476                        try {
2477                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2478                        } catch (PackageManagerException e) {
2479                            Slog.e(TAG, "Failed to parse original system package: "
2480                                    + e.getMessage());
2481                        }
2482                    }
2483                }
2484            }
2485            mExpectingBetter.clear();
2486
2487            // Resolve the storage manager.
2488            mStorageManagerPackage = getStorageManagerPackageName();
2489
2490            // Resolve protected action filters. Only the setup wizard is allowed to
2491            // have a high priority filter for these actions.
2492            mSetupWizardPackage = getSetupWizardPackageName();
2493            if (mProtectedFilters.size() > 0) {
2494                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2495                    Slog.i(TAG, "No setup wizard;"
2496                        + " All protected intents capped to priority 0");
2497                }
2498                for (ActivityIntentInfo filter : mProtectedFilters) {
2499                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2500                        if (DEBUG_FILTERS) {
2501                            Slog.i(TAG, "Found setup wizard;"
2502                                + " allow priority " + filter.getPriority() + ";"
2503                                + " package: " + filter.activity.info.packageName
2504                                + " activity: " + filter.activity.className
2505                                + " priority: " + filter.getPriority());
2506                        }
2507                        // skip setup wizard; allow it to keep the high priority filter
2508                        continue;
2509                    }
2510                    Slog.w(TAG, "Protected action; cap priority to 0;"
2511                            + " package: " + filter.activity.info.packageName
2512                            + " activity: " + filter.activity.className
2513                            + " origPrio: " + filter.getPriority());
2514                    filter.setPriority(0);
2515                }
2516            }
2517            mDeferProtectedFilters = false;
2518            mProtectedFilters.clear();
2519
2520            // Now that we know all of the shared libraries, update all clients to have
2521            // the correct library paths.
2522            updateAllSharedLibrariesLPw();
2523
2524            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2525                // NOTE: We ignore potential failures here during a system scan (like
2526                // the rest of the commands above) because there's precious little we
2527                // can do about it. A settings error is reported, though.
2528                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2529                        false /* boot complete */);
2530            }
2531
2532            // Now that we know all the packages we are keeping,
2533            // read and update their last usage times.
2534            mPackageUsage.read(mPackages);
2535            mCompilerStats.read();
2536
2537            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2538                    SystemClock.uptimeMillis());
2539            Slog.i(TAG, "Time to scan packages: "
2540                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2541                    + " seconds");
2542
2543            // If the platform SDK has changed since the last time we booted,
2544            // we need to re-grant app permission to catch any new ones that
2545            // appear.  This is really a hack, and means that apps can in some
2546            // cases get permissions that the user didn't initially explicitly
2547            // allow...  it would be nice to have some better way to handle
2548            // this situation.
2549            int updateFlags = UPDATE_PERMISSIONS_ALL;
2550            if (ver.sdkVersion != mSdkVersion) {
2551                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2552                        + mSdkVersion + "; regranting permissions for internal storage");
2553                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2554            }
2555            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2556            ver.sdkVersion = mSdkVersion;
2557
2558            // If this is the first boot or an update from pre-M, and it is a normal
2559            // boot, then we need to initialize the default preferred apps across
2560            // all defined users.
2561            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2562                for (UserInfo user : sUserManager.getUsers(true)) {
2563                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2564                    applyFactoryDefaultBrowserLPw(user.id);
2565                    primeDomainVerificationsLPw(user.id);
2566                }
2567            }
2568
2569            // Prepare storage for system user really early during boot,
2570            // since core system apps like SettingsProvider and SystemUI
2571            // can't wait for user to start
2572            final int storageFlags;
2573            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2574                storageFlags = StorageManager.FLAG_STORAGE_DE;
2575            } else {
2576                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2577            }
2578            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2579                    storageFlags, true /* migrateAppData */);
2580
2581            // If this is first boot after an OTA, and a normal boot, then
2582            // we need to clear code cache directories.
2583            // Note that we do *not* clear the application profiles. These remain valid
2584            // across OTAs and are used to drive profile verification (post OTA) and
2585            // profile compilation (without waiting to collect a fresh set of profiles).
2586            if (mIsUpgrade && !onlyCore) {
2587                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2588                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2589                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2590                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2591                        // No apps are running this early, so no need to freeze
2592                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2593                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2594                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2595                    }
2596                }
2597                ver.fingerprint = Build.FINGERPRINT;
2598            }
2599
2600            checkDefaultBrowser();
2601
2602            // clear only after permissions and other defaults have been updated
2603            mExistingSystemPackages.clear();
2604            mPromoteSystemApps = false;
2605
2606            // All the changes are done during package scanning.
2607            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2608
2609            // can downgrade to reader
2610            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2611            mSettings.writeLPr();
2612            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2613
2614            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2615            // early on (before the package manager declares itself as early) because other
2616            // components in the system server might ask for package contexts for these apps.
2617            //
2618            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2619            // (i.e, that the data partition is unavailable).
2620            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2621                long start = System.nanoTime();
2622                List<PackageParser.Package> coreApps = new ArrayList<>();
2623                for (PackageParser.Package pkg : mPackages.values()) {
2624                    if (pkg.coreApp) {
2625                        coreApps.add(pkg);
2626                    }
2627                }
2628
2629                int[] stats = performDexOptUpgrade(coreApps, false,
2630                        getCompilerFilterForReason(REASON_CORE_APP));
2631
2632                final int elapsedTimeSeconds =
2633                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2634                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2635
2636                if (DEBUG_DEXOPT) {
2637                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2638                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2639                }
2640
2641
2642                // TODO: Should we log these stats to tron too ?
2643                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2644                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2645                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2646                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2647            }
2648
2649            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2650                    SystemClock.uptimeMillis());
2651
2652            if (!mOnlyCore) {
2653                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2654                mRequiredInstallerPackage = getRequiredInstallerLPr();
2655                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2656                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2657                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2658                        mIntentFilterVerifierComponent);
2659                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2660                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2661                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2662                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2663            } else {
2664                mRequiredVerifierPackage = null;
2665                mRequiredInstallerPackage = null;
2666                mRequiredUninstallerPackage = null;
2667                mIntentFilterVerifierComponent = null;
2668                mIntentFilterVerifier = null;
2669                mServicesSystemSharedLibraryPackageName = null;
2670                mSharedSystemSharedLibraryPackageName = null;
2671            }
2672
2673            mInstallerService = new PackageInstallerService(context, this);
2674
2675            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2676            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2677            // both the installer and resolver must be present to enable ephemeral
2678            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2679                if (DEBUG_EPHEMERAL) {
2680                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2681                            + " installer:" + ephemeralInstallerComponent);
2682                }
2683                mEphemeralResolverComponent = ephemeralResolverComponent;
2684                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2685                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2686                mEphemeralResolverConnection =
2687                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2688            } else {
2689                if (DEBUG_EPHEMERAL) {
2690                    final String missingComponent =
2691                            (ephemeralResolverComponent == null)
2692                            ? (ephemeralInstallerComponent == null)
2693                                    ? "resolver and installer"
2694                                    : "resolver"
2695                            : "installer";
2696                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2697                }
2698                mEphemeralResolverComponent = null;
2699                mEphemeralInstallerComponent = null;
2700                mEphemeralResolverConnection = null;
2701            }
2702
2703            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2704        } // synchronized (mPackages)
2705        } // synchronized (mInstallLock)
2706
2707        // Now after opening every single application zip, make sure they
2708        // are all flushed.  Not really needed, but keeps things nice and
2709        // tidy.
2710        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2711        Runtime.getRuntime().gc();
2712        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2713
2714        // The initial scanning above does many calls into installd while
2715        // holding the mPackages lock, but we're mostly interested in yelling
2716        // once we have a booted system.
2717        mInstaller.setWarnIfHeld(mPackages);
2718
2719        // Expose private service for system components to use.
2720        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2721        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2722    }
2723
2724    @Override
2725    public boolean isFirstBoot() {
2726        return mFirstBoot;
2727    }
2728
2729    @Override
2730    public boolean isOnlyCoreApps() {
2731        return mOnlyCore;
2732    }
2733
2734    @Override
2735    public boolean isUpgrade() {
2736        return mIsUpgrade;
2737    }
2738
2739    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2740        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2741
2742        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2743                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2744                UserHandle.USER_SYSTEM);
2745        if (matches.size() == 1) {
2746            return matches.get(0).getComponentInfo().packageName;
2747        } else if (matches.size() == 0) {
2748            Log.e(TAG, "There should probably be a verifier, but, none were found");
2749            return null;
2750        }
2751        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2752    }
2753
2754    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2755        synchronized (mPackages) {
2756            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2757            if (libraryEntry == null) {
2758                throw new IllegalStateException("Missing required shared library:" + libraryName);
2759            }
2760            return libraryEntry.apk;
2761        }
2762    }
2763
2764    private @NonNull String getRequiredInstallerLPr() {
2765        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2766        intent.addCategory(Intent.CATEGORY_DEFAULT);
2767        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2768
2769        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2770                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2771                UserHandle.USER_SYSTEM);
2772        if (matches.size() == 1) {
2773            ResolveInfo resolveInfo = matches.get(0);
2774            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2775                throw new RuntimeException("The installer must be a privileged app");
2776            }
2777            return matches.get(0).getComponentInfo().packageName;
2778        } else {
2779            throw new RuntimeException("There must be exactly one installer; found " + matches);
2780        }
2781    }
2782
2783    private @NonNull String getRequiredUninstallerLPr() {
2784        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2785        intent.addCategory(Intent.CATEGORY_DEFAULT);
2786        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2787
2788        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2789                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2790                UserHandle.USER_SYSTEM);
2791        if (resolveInfo == null ||
2792                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2793            throw new RuntimeException("There must be exactly one uninstaller; found "
2794                    + resolveInfo);
2795        }
2796        return resolveInfo.getComponentInfo().packageName;
2797    }
2798
2799    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2800        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2801
2802        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2803                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2804                UserHandle.USER_SYSTEM);
2805        ResolveInfo best = null;
2806        final int N = matches.size();
2807        for (int i = 0; i < N; i++) {
2808            final ResolveInfo cur = matches.get(i);
2809            final String packageName = cur.getComponentInfo().packageName;
2810            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2811                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2812                continue;
2813            }
2814
2815            if (best == null || cur.priority > best.priority) {
2816                best = cur;
2817            }
2818        }
2819
2820        if (best != null) {
2821            return best.getComponentInfo().getComponentName();
2822        } else {
2823            throw new RuntimeException("There must be at least one intent filter verifier");
2824        }
2825    }
2826
2827    private @Nullable ComponentName getEphemeralResolverLPr() {
2828        final String[] packageArray =
2829                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2830        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2831            if (DEBUG_EPHEMERAL) {
2832                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2833            }
2834            return null;
2835        }
2836
2837        final int resolveFlags =
2838                MATCH_DIRECT_BOOT_AWARE
2839                | MATCH_DIRECT_BOOT_UNAWARE
2840                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2841        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2842        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2843                resolveFlags, UserHandle.USER_SYSTEM);
2844
2845        final int N = resolvers.size();
2846        if (N == 0) {
2847            if (DEBUG_EPHEMERAL) {
2848                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2849            }
2850            return null;
2851        }
2852
2853        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2854        for (int i = 0; i < N; i++) {
2855            final ResolveInfo info = resolvers.get(i);
2856
2857            if (info.serviceInfo == null) {
2858                continue;
2859            }
2860
2861            final String packageName = info.serviceInfo.packageName;
2862            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2863                if (DEBUG_EPHEMERAL) {
2864                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2865                            + " pkg: " + packageName + ", info:" + info);
2866                }
2867                continue;
2868            }
2869
2870            if (DEBUG_EPHEMERAL) {
2871                Slog.v(TAG, "Ephemeral resolver found;"
2872                        + " pkg: " + packageName + ", info:" + info);
2873            }
2874            return new ComponentName(packageName, info.serviceInfo.name);
2875        }
2876        if (DEBUG_EPHEMERAL) {
2877            Slog.v(TAG, "Ephemeral resolver NOT found");
2878        }
2879        return null;
2880    }
2881
2882    private @Nullable ComponentName getEphemeralInstallerLPr() {
2883        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2884        intent.addCategory(Intent.CATEGORY_DEFAULT);
2885        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2886
2887        final int resolveFlags =
2888                MATCH_DIRECT_BOOT_AWARE
2889                | MATCH_DIRECT_BOOT_UNAWARE
2890                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2891        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2892                resolveFlags, UserHandle.USER_SYSTEM);
2893        if (matches.size() == 0) {
2894            return null;
2895        } else if (matches.size() == 1) {
2896            return matches.get(0).getComponentInfo().getComponentName();
2897        } else {
2898            throw new RuntimeException(
2899                    "There must be at most one ephemeral installer; found " + matches);
2900        }
2901    }
2902
2903    private void primeDomainVerificationsLPw(int userId) {
2904        if (DEBUG_DOMAIN_VERIFICATION) {
2905            Slog.d(TAG, "Priming domain verifications in user " + userId);
2906        }
2907
2908        SystemConfig systemConfig = SystemConfig.getInstance();
2909        ArraySet<String> packages = systemConfig.getLinkedApps();
2910
2911        for (String packageName : packages) {
2912            PackageParser.Package pkg = mPackages.get(packageName);
2913            if (pkg != null) {
2914                if (!pkg.isSystemApp()) {
2915                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2916                    continue;
2917                }
2918
2919                ArraySet<String> domains = null;
2920                for (PackageParser.Activity a : pkg.activities) {
2921                    for (ActivityIntentInfo filter : a.intents) {
2922                        if (hasValidDomains(filter)) {
2923                            if (domains == null) {
2924                                domains = new ArraySet<String>();
2925                            }
2926                            domains.addAll(filter.getHostsList());
2927                        }
2928                    }
2929                }
2930
2931                if (domains != null && domains.size() > 0) {
2932                    if (DEBUG_DOMAIN_VERIFICATION) {
2933                        Slog.v(TAG, "      + " + packageName);
2934                    }
2935                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2936                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2937                    // and then 'always' in the per-user state actually used for intent resolution.
2938                    final IntentFilterVerificationInfo ivi;
2939                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2940                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2941                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2942                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2943                } else {
2944                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2945                            + "' does not handle web links");
2946                }
2947            } else {
2948                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2949            }
2950        }
2951
2952        scheduleWritePackageRestrictionsLocked(userId);
2953        scheduleWriteSettingsLocked();
2954    }
2955
2956    private void applyFactoryDefaultBrowserLPw(int userId) {
2957        // The default browser app's package name is stored in a string resource,
2958        // with a product-specific overlay used for vendor customization.
2959        String browserPkg = mContext.getResources().getString(
2960                com.android.internal.R.string.default_browser);
2961        if (!TextUtils.isEmpty(browserPkg)) {
2962            // non-empty string => required to be a known package
2963            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2964            if (ps == null) {
2965                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2966                browserPkg = null;
2967            } else {
2968                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2969            }
2970        }
2971
2972        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2973        // default.  If there's more than one, just leave everything alone.
2974        if (browserPkg == null) {
2975            calculateDefaultBrowserLPw(userId);
2976        }
2977    }
2978
2979    private void calculateDefaultBrowserLPw(int userId) {
2980        List<String> allBrowsers = resolveAllBrowserApps(userId);
2981        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2982        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2983    }
2984
2985    private List<String> resolveAllBrowserApps(int userId) {
2986        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2987        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2988                PackageManager.MATCH_ALL, userId);
2989
2990        final int count = list.size();
2991        List<String> result = new ArrayList<String>(count);
2992        for (int i=0; i<count; i++) {
2993            ResolveInfo info = list.get(i);
2994            if (info.activityInfo == null
2995                    || !info.handleAllWebDataURI
2996                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2997                    || result.contains(info.activityInfo.packageName)) {
2998                continue;
2999            }
3000            result.add(info.activityInfo.packageName);
3001        }
3002
3003        return result;
3004    }
3005
3006    private boolean packageIsBrowser(String packageName, int userId) {
3007        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3008                PackageManager.MATCH_ALL, userId);
3009        final int N = list.size();
3010        for (int i = 0; i < N; i++) {
3011            ResolveInfo info = list.get(i);
3012            if (packageName.equals(info.activityInfo.packageName)) {
3013                return true;
3014            }
3015        }
3016        return false;
3017    }
3018
3019    private void checkDefaultBrowser() {
3020        final int myUserId = UserHandle.myUserId();
3021        final String packageName = getDefaultBrowserPackageName(myUserId);
3022        if (packageName != null) {
3023            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3024            if (info == null) {
3025                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3026                synchronized (mPackages) {
3027                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3028                }
3029            }
3030        }
3031    }
3032
3033    @Override
3034    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3035            throws RemoteException {
3036        try {
3037            return super.onTransact(code, data, reply, flags);
3038        } catch (RuntimeException e) {
3039            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3040                Slog.wtf(TAG, "Package Manager Crash", e);
3041            }
3042            throw e;
3043        }
3044    }
3045
3046    static int[] appendInts(int[] cur, int[] add) {
3047        if (add == null) return cur;
3048        if (cur == null) return add;
3049        final int N = add.length;
3050        for (int i=0; i<N; i++) {
3051            cur = appendInt(cur, add[i]);
3052        }
3053        return cur;
3054    }
3055
3056    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3057        if (!sUserManager.exists(userId)) return null;
3058        if (ps == null) {
3059            return null;
3060        }
3061        final PackageParser.Package p = ps.pkg;
3062        if (p == null) {
3063            return null;
3064        }
3065
3066        final PermissionsState permissionsState = ps.getPermissionsState();
3067
3068        // Compute GIDs only if requested
3069        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3070                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3071        // Compute granted permissions only if package has requested permissions
3072        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3073                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3074        final PackageUserState state = ps.readUserState(userId);
3075
3076        return PackageParser.generatePackageInfo(p, gids, flags,
3077                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3078    }
3079
3080    @Override
3081    public void checkPackageStartable(String packageName, int userId) {
3082        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3083
3084        synchronized (mPackages) {
3085            final PackageSetting ps = mSettings.mPackages.get(packageName);
3086            if (ps == null) {
3087                throw new SecurityException("Package " + packageName + " was not found!");
3088            }
3089
3090            if (!ps.getInstalled(userId)) {
3091                throw new SecurityException(
3092                        "Package " + packageName + " was not installed for user " + userId + "!");
3093            }
3094
3095            if (mSafeMode && !ps.isSystem()) {
3096                throw new SecurityException("Package " + packageName + " not a system app!");
3097            }
3098
3099            if (mFrozenPackages.contains(packageName)) {
3100                throw new SecurityException("Package " + packageName + " is currently frozen!");
3101            }
3102
3103            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3104                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3105                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3106            }
3107        }
3108    }
3109
3110    @Override
3111    public boolean isPackageAvailable(String packageName, int userId) {
3112        if (!sUserManager.exists(userId)) return false;
3113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3114                false /* requireFullPermission */, false /* checkShell */, "is package available");
3115        synchronized (mPackages) {
3116            PackageParser.Package p = mPackages.get(packageName);
3117            if (p != null) {
3118                final PackageSetting ps = (PackageSetting) p.mExtras;
3119                if (ps != null) {
3120                    final PackageUserState state = ps.readUserState(userId);
3121                    if (state != null) {
3122                        return PackageParser.isAvailable(state);
3123                    }
3124                }
3125            }
3126        }
3127        return false;
3128    }
3129
3130    @Override
3131    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3132        if (!sUserManager.exists(userId)) return null;
3133        flags = updateFlagsForPackage(flags, userId, packageName);
3134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3135                false /* requireFullPermission */, false /* checkShell */, "get package info");
3136        // reader
3137        synchronized (mPackages) {
3138            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3139            PackageParser.Package p = null;
3140            if (matchFactoryOnly) {
3141                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3142                if (ps != null) {
3143                    return generatePackageInfo(ps, flags, userId);
3144                }
3145            }
3146            if (p == null) {
3147                p = mPackages.get(packageName);
3148                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3149                    return null;
3150                }
3151            }
3152            if (DEBUG_PACKAGE_INFO)
3153                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3154            if (p != null) {
3155                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3156            }
3157            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3158                final PackageSetting ps = mSettings.mPackages.get(packageName);
3159                return generatePackageInfo(ps, flags, userId);
3160            }
3161        }
3162        return null;
3163    }
3164
3165    @Override
3166    public String[] currentToCanonicalPackageNames(String[] names) {
3167        String[] out = new String[names.length];
3168        // reader
3169        synchronized (mPackages) {
3170            for (int i=names.length-1; i>=0; i--) {
3171                PackageSetting ps = mSettings.mPackages.get(names[i]);
3172                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3173            }
3174        }
3175        return out;
3176    }
3177
3178    @Override
3179    public String[] canonicalToCurrentPackageNames(String[] names) {
3180        String[] out = new String[names.length];
3181        // reader
3182        synchronized (mPackages) {
3183            for (int i=names.length-1; i>=0; i--) {
3184                String cur = mSettings.getRenamedPackageLPr(names[i]);
3185                out[i] = cur != null ? cur : names[i];
3186            }
3187        }
3188        return out;
3189    }
3190
3191    @Override
3192    public int getPackageUid(String packageName, int flags, int userId) {
3193        if (!sUserManager.exists(userId)) return -1;
3194        flags = updateFlagsForPackage(flags, userId, packageName);
3195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3196                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3197
3198        // reader
3199        synchronized (mPackages) {
3200            final PackageParser.Package p = mPackages.get(packageName);
3201            if (p != null && p.isMatch(flags)) {
3202                return UserHandle.getUid(userId, p.applicationInfo.uid);
3203            }
3204            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3205                final PackageSetting ps = mSettings.mPackages.get(packageName);
3206                if (ps != null && ps.isMatch(flags)) {
3207                    return UserHandle.getUid(userId, ps.appId);
3208                }
3209            }
3210        }
3211
3212        return -1;
3213    }
3214
3215    @Override
3216    public int[] getPackageGids(String packageName, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return null;
3218        flags = updateFlagsForPackage(flags, userId, packageName);
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3220                false /* requireFullPermission */, false /* checkShell */,
3221                "getPackageGids");
3222
3223        // reader
3224        synchronized (mPackages) {
3225            final PackageParser.Package p = mPackages.get(packageName);
3226            if (p != null && p.isMatch(flags)) {
3227                PackageSetting ps = (PackageSetting) p.mExtras;
3228                return ps.getPermissionsState().computeGids(userId);
3229            }
3230            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3231                final PackageSetting ps = mSettings.mPackages.get(packageName);
3232                if (ps != null && ps.isMatch(flags)) {
3233                    return ps.getPermissionsState().computeGids(userId);
3234                }
3235            }
3236        }
3237
3238        return null;
3239    }
3240
3241    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3242        if (bp.perm != null) {
3243            return PackageParser.generatePermissionInfo(bp.perm, flags);
3244        }
3245        PermissionInfo pi = new PermissionInfo();
3246        pi.name = bp.name;
3247        pi.packageName = bp.sourcePackage;
3248        pi.nonLocalizedLabel = bp.name;
3249        pi.protectionLevel = bp.protectionLevel;
3250        return pi;
3251    }
3252
3253    @Override
3254    public PermissionInfo getPermissionInfo(String name, int flags) {
3255        // reader
3256        synchronized (mPackages) {
3257            final BasePermission p = mSettings.mPermissions.get(name);
3258            if (p != null) {
3259                return generatePermissionInfo(p, flags);
3260            }
3261            return null;
3262        }
3263    }
3264
3265    @Override
3266    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3267            int flags) {
3268        // reader
3269        synchronized (mPackages) {
3270            if (group != null && !mPermissionGroups.containsKey(group)) {
3271                // This is thrown as NameNotFoundException
3272                return null;
3273            }
3274
3275            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3276            for (BasePermission p : mSettings.mPermissions.values()) {
3277                if (group == null) {
3278                    if (p.perm == null || p.perm.info.group == null) {
3279                        out.add(generatePermissionInfo(p, flags));
3280                    }
3281                } else {
3282                    if (p.perm != null && group.equals(p.perm.info.group)) {
3283                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3284                    }
3285                }
3286            }
3287            return new ParceledListSlice<>(out);
3288        }
3289    }
3290
3291    @Override
3292    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3293        // reader
3294        synchronized (mPackages) {
3295            return PackageParser.generatePermissionGroupInfo(
3296                    mPermissionGroups.get(name), flags);
3297        }
3298    }
3299
3300    @Override
3301    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3302        // reader
3303        synchronized (mPackages) {
3304            final int N = mPermissionGroups.size();
3305            ArrayList<PermissionGroupInfo> out
3306                    = new ArrayList<PermissionGroupInfo>(N);
3307            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3308                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3309            }
3310            return new ParceledListSlice<>(out);
3311        }
3312    }
3313
3314    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3315            int userId) {
3316        if (!sUserManager.exists(userId)) return null;
3317        PackageSetting ps = mSettings.mPackages.get(packageName);
3318        if (ps != null) {
3319            if (ps.pkg == null) {
3320                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3321                if (pInfo != null) {
3322                    return pInfo.applicationInfo;
3323                }
3324                return null;
3325            }
3326            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3327                    ps.readUserState(userId), userId);
3328        }
3329        return null;
3330    }
3331
3332    @Override
3333    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3334        if (!sUserManager.exists(userId)) return null;
3335        flags = updateFlagsForApplication(flags, userId, packageName);
3336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3337                false /* requireFullPermission */, false /* checkShell */, "get application info");
3338        // writer
3339        synchronized (mPackages) {
3340            PackageParser.Package p = mPackages.get(packageName);
3341            if (DEBUG_PACKAGE_INFO) Log.v(
3342                    TAG, "getApplicationInfo " + packageName
3343                    + ": " + p);
3344            if (p != null) {
3345                PackageSetting ps = mSettings.mPackages.get(packageName);
3346                if (ps == null) return null;
3347                // Note: isEnabledLP() does not apply here - always return info
3348                return PackageParser.generateApplicationInfo(
3349                        p, flags, ps.readUserState(userId), userId);
3350            }
3351            if ("android".equals(packageName)||"system".equals(packageName)) {
3352                return mAndroidApplication;
3353            }
3354            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3355                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3356            }
3357        }
3358        return null;
3359    }
3360
3361    @Override
3362    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3363            final IPackageDataObserver observer) {
3364        mContext.enforceCallingOrSelfPermission(
3365                android.Manifest.permission.CLEAR_APP_CACHE, null);
3366        // Queue up an async operation since clearing cache may take a little while.
3367        mHandler.post(new Runnable() {
3368            public void run() {
3369                mHandler.removeCallbacks(this);
3370                boolean success = true;
3371                synchronized (mInstallLock) {
3372                    try {
3373                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3374                    } catch (InstallerException e) {
3375                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3376                        success = false;
3377                    }
3378                }
3379                if (observer != null) {
3380                    try {
3381                        observer.onRemoveCompleted(null, success);
3382                    } catch (RemoteException e) {
3383                        Slog.w(TAG, "RemoveException when invoking call back");
3384                    }
3385                }
3386            }
3387        });
3388    }
3389
3390    @Override
3391    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3392            final IntentSender pi) {
3393        mContext.enforceCallingOrSelfPermission(
3394                android.Manifest.permission.CLEAR_APP_CACHE, null);
3395        // Queue up an async operation since clearing cache may take a little while.
3396        mHandler.post(new Runnable() {
3397            public void run() {
3398                mHandler.removeCallbacks(this);
3399                boolean success = true;
3400                synchronized (mInstallLock) {
3401                    try {
3402                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3403                    } catch (InstallerException e) {
3404                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3405                        success = false;
3406                    }
3407                }
3408                if(pi != null) {
3409                    try {
3410                        // Callback via pending intent
3411                        int code = success ? 1 : 0;
3412                        pi.sendIntent(null, code, null,
3413                                null, null);
3414                    } catch (SendIntentException e1) {
3415                        Slog.i(TAG, "Failed to send pending intent");
3416                    }
3417                }
3418            }
3419        });
3420    }
3421
3422    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3423        synchronized (mInstallLock) {
3424            try {
3425                mInstaller.freeCache(volumeUuid, freeStorageSize);
3426            } catch (InstallerException e) {
3427                throw new IOException("Failed to free enough space", e);
3428            }
3429        }
3430    }
3431
3432    /**
3433     * Update given flags based on encryption status of current user.
3434     */
3435    private int updateFlags(int flags, int userId) {
3436        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3437                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3438            // Caller expressed an explicit opinion about what encryption
3439            // aware/unaware components they want to see, so fall through and
3440            // give them what they want
3441        } else {
3442            // Caller expressed no opinion, so match based on user state
3443            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3444                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3445            } else {
3446                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3447            }
3448        }
3449        return flags;
3450    }
3451
3452    private UserManagerInternal getUserManagerInternal() {
3453        if (mUserManagerInternal == null) {
3454            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3455        }
3456        return mUserManagerInternal;
3457    }
3458
3459    /**
3460     * Update given flags when being used to request {@link PackageInfo}.
3461     */
3462    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3463        boolean triaged = true;
3464        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3465                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3466            // Caller is asking for component details, so they'd better be
3467            // asking for specific encryption matching behavior, or be triaged
3468            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3469                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3470                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3471                triaged = false;
3472            }
3473        }
3474        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3475                | PackageManager.MATCH_SYSTEM_ONLY
3476                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3477            triaged = false;
3478        }
3479        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3480            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3481                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3482        }
3483        return updateFlags(flags, userId);
3484    }
3485
3486    /**
3487     * Update given flags when being used to request {@link ApplicationInfo}.
3488     */
3489    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3490        return updateFlagsForPackage(flags, userId, cookie);
3491    }
3492
3493    /**
3494     * Update given flags when being used to request {@link ComponentInfo}.
3495     */
3496    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3497        if (cookie instanceof Intent) {
3498            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3499                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3500            }
3501        }
3502
3503        boolean triaged = true;
3504        // Caller is asking for component details, so they'd better be
3505        // asking for specific encryption matching behavior, or be triaged
3506        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3507                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3508                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3509            triaged = false;
3510        }
3511        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3512            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3513                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3514        }
3515
3516        return updateFlags(flags, userId);
3517    }
3518
3519    /**
3520     * Update given flags when being used to request {@link ResolveInfo}.
3521     */
3522    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3523        // Safe mode means we shouldn't match any third-party components
3524        if (mSafeMode) {
3525            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3526        }
3527
3528        return updateFlagsForComponent(flags, userId, cookie);
3529    }
3530
3531    @Override
3532    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3533        if (!sUserManager.exists(userId)) return null;
3534        flags = updateFlagsForComponent(flags, userId, component);
3535        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3536                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3537        synchronized (mPackages) {
3538            PackageParser.Activity a = mActivities.mActivities.get(component);
3539
3540            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3541            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3542                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3543                if (ps == null) return null;
3544                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3545                        userId);
3546            }
3547            if (mResolveComponentName.equals(component)) {
3548                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3549                        new PackageUserState(), userId);
3550            }
3551        }
3552        return null;
3553    }
3554
3555    @Override
3556    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3557            String resolvedType) {
3558        synchronized (mPackages) {
3559            if (component.equals(mResolveComponentName)) {
3560                // The resolver supports EVERYTHING!
3561                return true;
3562            }
3563            PackageParser.Activity a = mActivities.mActivities.get(component);
3564            if (a == null) {
3565                return false;
3566            }
3567            for (int i=0; i<a.intents.size(); i++) {
3568                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3569                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3570                    return true;
3571                }
3572            }
3573            return false;
3574        }
3575    }
3576
3577    @Override
3578    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3579        if (!sUserManager.exists(userId)) return null;
3580        flags = updateFlagsForComponent(flags, userId, component);
3581        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3582                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3583        synchronized (mPackages) {
3584            PackageParser.Activity a = mReceivers.mActivities.get(component);
3585            if (DEBUG_PACKAGE_INFO) Log.v(
3586                TAG, "getReceiverInfo " + component + ": " + a);
3587            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3588                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3589                if (ps == null) return null;
3590                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3591                        userId);
3592            }
3593        }
3594        return null;
3595    }
3596
3597    @Override
3598    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3599        if (!sUserManager.exists(userId)) return null;
3600        flags = updateFlagsForComponent(flags, userId, component);
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3602                false /* requireFullPermission */, false /* checkShell */, "get service info");
3603        synchronized (mPackages) {
3604            PackageParser.Service s = mServices.mServices.get(component);
3605            if (DEBUG_PACKAGE_INFO) Log.v(
3606                TAG, "getServiceInfo " + component + ": " + s);
3607            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3608                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3609                if (ps == null) return null;
3610                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3611                        userId);
3612            }
3613        }
3614        return null;
3615    }
3616
3617    @Override
3618    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3619        if (!sUserManager.exists(userId)) return null;
3620        flags = updateFlagsForComponent(flags, userId, component);
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3622                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3623        synchronized (mPackages) {
3624            PackageParser.Provider p = mProviders.mProviders.get(component);
3625            if (DEBUG_PACKAGE_INFO) Log.v(
3626                TAG, "getProviderInfo " + component + ": " + p);
3627            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3628                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3629                if (ps == null) return null;
3630                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3631                        userId);
3632            }
3633        }
3634        return null;
3635    }
3636
3637    @Override
3638    public String[] getSystemSharedLibraryNames() {
3639        Set<String> libSet;
3640        synchronized (mPackages) {
3641            libSet = mSharedLibraries.keySet();
3642            int size = libSet.size();
3643            if (size > 0) {
3644                String[] libs = new String[size];
3645                libSet.toArray(libs);
3646                return libs;
3647            }
3648        }
3649        return null;
3650    }
3651
3652    @Override
3653    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3654        synchronized (mPackages) {
3655            return mServicesSystemSharedLibraryPackageName;
3656        }
3657    }
3658
3659    @Override
3660    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3661        synchronized (mPackages) {
3662            return mSharedSystemSharedLibraryPackageName;
3663        }
3664    }
3665
3666    @Override
3667    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3668        synchronized (mPackages) {
3669            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3670
3671            final FeatureInfo fi = new FeatureInfo();
3672            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3673                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3674            res.add(fi);
3675
3676            return new ParceledListSlice<>(res);
3677        }
3678    }
3679
3680    @Override
3681    public boolean hasSystemFeature(String name, int version) {
3682        synchronized (mPackages) {
3683            final FeatureInfo feat = mAvailableFeatures.get(name);
3684            if (feat == null) {
3685                return false;
3686            } else {
3687                return feat.version >= version;
3688            }
3689        }
3690    }
3691
3692    @Override
3693    public int checkPermission(String permName, String pkgName, int userId) {
3694        if (!sUserManager.exists(userId)) {
3695            return PackageManager.PERMISSION_DENIED;
3696        }
3697
3698        synchronized (mPackages) {
3699            final PackageParser.Package p = mPackages.get(pkgName);
3700            if (p != null && p.mExtras != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                final PermissionsState permissionsState = ps.getPermissionsState();
3703                if (permissionsState.hasPermission(permName, userId)) {
3704                    return PackageManager.PERMISSION_GRANTED;
3705                }
3706                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3707                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3708                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3709                    return PackageManager.PERMISSION_GRANTED;
3710                }
3711            }
3712        }
3713
3714        return PackageManager.PERMISSION_DENIED;
3715    }
3716
3717    @Override
3718    public int checkUidPermission(String permName, int uid) {
3719        final int userId = UserHandle.getUserId(uid);
3720
3721        if (!sUserManager.exists(userId)) {
3722            return PackageManager.PERMISSION_DENIED;
3723        }
3724
3725        synchronized (mPackages) {
3726            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3727            if (obj != null) {
3728                final SettingBase ps = (SettingBase) obj;
3729                final PermissionsState permissionsState = ps.getPermissionsState();
3730                if (permissionsState.hasPermission(permName, userId)) {
3731                    return PackageManager.PERMISSION_GRANTED;
3732                }
3733                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3734                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3735                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3736                    return PackageManager.PERMISSION_GRANTED;
3737                }
3738            } else {
3739                ArraySet<String> perms = mSystemPermissions.get(uid);
3740                if (perms != null) {
3741                    if (perms.contains(permName)) {
3742                        return PackageManager.PERMISSION_GRANTED;
3743                    }
3744                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3745                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3746                        return PackageManager.PERMISSION_GRANTED;
3747                    }
3748                }
3749            }
3750        }
3751
3752        return PackageManager.PERMISSION_DENIED;
3753    }
3754
3755    @Override
3756    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3757        if (UserHandle.getCallingUserId() != userId) {
3758            mContext.enforceCallingPermission(
3759                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3760                    "isPermissionRevokedByPolicy for user " + userId);
3761        }
3762
3763        if (checkPermission(permission, packageName, userId)
3764                == PackageManager.PERMISSION_GRANTED) {
3765            return false;
3766        }
3767
3768        final long identity = Binder.clearCallingIdentity();
3769        try {
3770            final int flags = getPermissionFlags(permission, packageName, userId);
3771            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3772        } finally {
3773            Binder.restoreCallingIdentity(identity);
3774        }
3775    }
3776
3777    @Override
3778    public String getPermissionControllerPackageName() {
3779        synchronized (mPackages) {
3780            return mRequiredInstallerPackage;
3781        }
3782    }
3783
3784    /**
3785     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3786     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3787     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3788     * @param message the message to log on security exception
3789     */
3790    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3791            boolean checkShell, String message) {
3792        if (userId < 0) {
3793            throw new IllegalArgumentException("Invalid userId " + userId);
3794        }
3795        if (checkShell) {
3796            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3797        }
3798        if (userId == UserHandle.getUserId(callingUid)) return;
3799        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3800            if (requireFullPermission) {
3801                mContext.enforceCallingOrSelfPermission(
3802                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3803            } else {
3804                try {
3805                    mContext.enforceCallingOrSelfPermission(
3806                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3807                } catch (SecurityException se) {
3808                    mContext.enforceCallingOrSelfPermission(
3809                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3810                }
3811            }
3812        }
3813    }
3814
3815    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3816        if (callingUid == Process.SHELL_UID) {
3817            if (userHandle >= 0
3818                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3819                throw new SecurityException("Shell does not have permission to access user "
3820                        + userHandle);
3821            } else if (userHandle < 0) {
3822                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3823                        + Debug.getCallers(3));
3824            }
3825        }
3826    }
3827
3828    private BasePermission findPermissionTreeLP(String permName) {
3829        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3830            if (permName.startsWith(bp.name) &&
3831                    permName.length() > bp.name.length() &&
3832                    permName.charAt(bp.name.length()) == '.') {
3833                return bp;
3834            }
3835        }
3836        return null;
3837    }
3838
3839    private BasePermission checkPermissionTreeLP(String permName) {
3840        if (permName != null) {
3841            BasePermission bp = findPermissionTreeLP(permName);
3842            if (bp != null) {
3843                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3844                    return bp;
3845                }
3846                throw new SecurityException("Calling uid "
3847                        + Binder.getCallingUid()
3848                        + " is not allowed to add to permission tree "
3849                        + bp.name + " owned by uid " + bp.uid);
3850            }
3851        }
3852        throw new SecurityException("No permission tree found for " + permName);
3853    }
3854
3855    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3856        if (s1 == null) {
3857            return s2 == null;
3858        }
3859        if (s2 == null) {
3860            return false;
3861        }
3862        if (s1.getClass() != s2.getClass()) {
3863            return false;
3864        }
3865        return s1.equals(s2);
3866    }
3867
3868    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3869        if (pi1.icon != pi2.icon) return false;
3870        if (pi1.logo != pi2.logo) return false;
3871        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3872        if (!compareStrings(pi1.name, pi2.name)) return false;
3873        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3874        // We'll take care of setting this one.
3875        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3876        // These are not currently stored in settings.
3877        //if (!compareStrings(pi1.group, pi2.group)) return false;
3878        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3879        //if (pi1.labelRes != pi2.labelRes) return false;
3880        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3881        return true;
3882    }
3883
3884    int permissionInfoFootprint(PermissionInfo info) {
3885        int size = info.name.length();
3886        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3887        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3888        return size;
3889    }
3890
3891    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3892        int size = 0;
3893        for (BasePermission perm : mSettings.mPermissions.values()) {
3894            if (perm.uid == tree.uid) {
3895                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3896            }
3897        }
3898        return size;
3899    }
3900
3901    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3902        // We calculate the max size of permissions defined by this uid and throw
3903        // if that plus the size of 'info' would exceed our stated maximum.
3904        if (tree.uid != Process.SYSTEM_UID) {
3905            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3906            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3907                throw new SecurityException("Permission tree size cap exceeded");
3908            }
3909        }
3910    }
3911
3912    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3913        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3914            throw new SecurityException("Label must be specified in permission");
3915        }
3916        BasePermission tree = checkPermissionTreeLP(info.name);
3917        BasePermission bp = mSettings.mPermissions.get(info.name);
3918        boolean added = bp == null;
3919        boolean changed = true;
3920        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3921        if (added) {
3922            enforcePermissionCapLocked(info, tree);
3923            bp = new BasePermission(info.name, tree.sourcePackage,
3924                    BasePermission.TYPE_DYNAMIC);
3925        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3926            throw new SecurityException(
3927                    "Not allowed to modify non-dynamic permission "
3928                    + info.name);
3929        } else {
3930            if (bp.protectionLevel == fixedLevel
3931                    && bp.perm.owner.equals(tree.perm.owner)
3932                    && bp.uid == tree.uid
3933                    && comparePermissionInfos(bp.perm.info, info)) {
3934                changed = false;
3935            }
3936        }
3937        bp.protectionLevel = fixedLevel;
3938        info = new PermissionInfo(info);
3939        info.protectionLevel = fixedLevel;
3940        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3941        bp.perm.info.packageName = tree.perm.info.packageName;
3942        bp.uid = tree.uid;
3943        if (added) {
3944            mSettings.mPermissions.put(info.name, bp);
3945        }
3946        if (changed) {
3947            if (!async) {
3948                mSettings.writeLPr();
3949            } else {
3950                scheduleWriteSettingsLocked();
3951            }
3952        }
3953        return added;
3954    }
3955
3956    @Override
3957    public boolean addPermission(PermissionInfo info) {
3958        synchronized (mPackages) {
3959            return addPermissionLocked(info, false);
3960        }
3961    }
3962
3963    @Override
3964    public boolean addPermissionAsync(PermissionInfo info) {
3965        synchronized (mPackages) {
3966            return addPermissionLocked(info, true);
3967        }
3968    }
3969
3970    @Override
3971    public void removePermission(String name) {
3972        synchronized (mPackages) {
3973            checkPermissionTreeLP(name);
3974            BasePermission bp = mSettings.mPermissions.get(name);
3975            if (bp != null) {
3976                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3977                    throw new SecurityException(
3978                            "Not allowed to modify non-dynamic permission "
3979                            + name);
3980                }
3981                mSettings.mPermissions.remove(name);
3982                mSettings.writeLPr();
3983            }
3984        }
3985    }
3986
3987    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3988            BasePermission bp) {
3989        int index = pkg.requestedPermissions.indexOf(bp.name);
3990        if (index == -1) {
3991            throw new SecurityException("Package " + pkg.packageName
3992                    + " has not requested permission " + bp.name);
3993        }
3994        if (!bp.isRuntime() && !bp.isDevelopment()) {
3995            throw new SecurityException("Permission " + bp.name
3996                    + " is not a changeable permission type");
3997        }
3998    }
3999
4000    @Override
4001    public void grantRuntimePermission(String packageName, String name, final int userId) {
4002        if (!sUserManager.exists(userId)) {
4003            Log.e(TAG, "No such user:" + userId);
4004            return;
4005        }
4006
4007        mContext.enforceCallingOrSelfPermission(
4008                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4009                "grantRuntimePermission");
4010
4011        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4012                true /* requireFullPermission */, true /* checkShell */,
4013                "grantRuntimePermission");
4014
4015        final int uid;
4016        final SettingBase sb;
4017
4018        synchronized (mPackages) {
4019            final PackageParser.Package pkg = mPackages.get(packageName);
4020            if (pkg == null) {
4021                throw new IllegalArgumentException("Unknown package: " + packageName);
4022            }
4023
4024            final BasePermission bp = mSettings.mPermissions.get(name);
4025            if (bp == null) {
4026                throw new IllegalArgumentException("Unknown permission: " + name);
4027            }
4028
4029            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4030
4031            // If a permission review is required for legacy apps we represent
4032            // their permissions as always granted runtime ones since we need
4033            // to keep the review required permission flag per user while an
4034            // install permission's state is shared across all users.
4035            if (mPermissionReviewRequired
4036                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4037                    && bp.isRuntime()) {
4038                return;
4039            }
4040
4041            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4042            sb = (SettingBase) pkg.mExtras;
4043            if (sb == null) {
4044                throw new IllegalArgumentException("Unknown package: " + packageName);
4045            }
4046
4047            final PermissionsState permissionsState = sb.getPermissionsState();
4048
4049            final int flags = permissionsState.getPermissionFlags(name, userId);
4050            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4051                throw new SecurityException("Cannot grant system fixed permission "
4052                        + name + " for package " + packageName);
4053            }
4054
4055            if (bp.isDevelopment()) {
4056                // Development permissions must be handled specially, since they are not
4057                // normal runtime permissions.  For now they apply to all users.
4058                if (permissionsState.grantInstallPermission(bp) !=
4059                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4060                    scheduleWriteSettingsLocked();
4061                }
4062                return;
4063            }
4064
4065            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4066                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4067                return;
4068            }
4069
4070            final int result = permissionsState.grantRuntimePermission(bp, userId);
4071            switch (result) {
4072                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4073                    return;
4074                }
4075
4076                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4077                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4078                    mHandler.post(new Runnable() {
4079                        @Override
4080                        public void run() {
4081                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4082                        }
4083                    });
4084                }
4085                break;
4086            }
4087
4088            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4089
4090            // Not critical if that is lost - app has to request again.
4091            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4092        }
4093
4094        // Only need to do this if user is initialized. Otherwise it's a new user
4095        // and there are no processes running as the user yet and there's no need
4096        // to make an expensive call to remount processes for the changed permissions.
4097        if (READ_EXTERNAL_STORAGE.equals(name)
4098                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4099            final long token = Binder.clearCallingIdentity();
4100            try {
4101                if (sUserManager.isInitialized(userId)) {
4102                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4103                            MountServiceInternal.class);
4104                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4105                }
4106            } finally {
4107                Binder.restoreCallingIdentity(token);
4108            }
4109        }
4110    }
4111
4112    @Override
4113    public void revokeRuntimePermission(String packageName, String name, int userId) {
4114        if (!sUserManager.exists(userId)) {
4115            Log.e(TAG, "No such user:" + userId);
4116            return;
4117        }
4118
4119        mContext.enforceCallingOrSelfPermission(
4120                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4121                "revokeRuntimePermission");
4122
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4124                true /* requireFullPermission */, true /* checkShell */,
4125                "revokeRuntimePermission");
4126
4127        final int appId;
4128
4129        synchronized (mPackages) {
4130            final PackageParser.Package pkg = mPackages.get(packageName);
4131            if (pkg == null) {
4132                throw new IllegalArgumentException("Unknown package: " + packageName);
4133            }
4134
4135            final BasePermission bp = mSettings.mPermissions.get(name);
4136            if (bp == null) {
4137                throw new IllegalArgumentException("Unknown permission: " + name);
4138            }
4139
4140            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4141
4142            // If a permission review is required for legacy apps we represent
4143            // their permissions as always granted runtime ones since we need
4144            // to keep the review required permission flag per user while an
4145            // install permission's state is shared across all users.
4146            if (mPermissionReviewRequired
4147                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4148                    && bp.isRuntime()) {
4149                return;
4150            }
4151
4152            SettingBase sb = (SettingBase) pkg.mExtras;
4153            if (sb == null) {
4154                throw new IllegalArgumentException("Unknown package: " + packageName);
4155            }
4156
4157            final PermissionsState permissionsState = sb.getPermissionsState();
4158
4159            final int flags = permissionsState.getPermissionFlags(name, userId);
4160            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4161                throw new SecurityException("Cannot revoke system fixed permission "
4162                        + name + " for package " + packageName);
4163            }
4164
4165            if (bp.isDevelopment()) {
4166                // Development permissions must be handled specially, since they are not
4167                // normal runtime permissions.  For now they apply to all users.
4168                if (permissionsState.revokeInstallPermission(bp) !=
4169                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4170                    scheduleWriteSettingsLocked();
4171                }
4172                return;
4173            }
4174
4175            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4176                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4177                return;
4178            }
4179
4180            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4181
4182            // Critical, after this call app should never have the permission.
4183            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4184
4185            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4186        }
4187
4188        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4189    }
4190
4191    @Override
4192    public void resetRuntimePermissions() {
4193        mContext.enforceCallingOrSelfPermission(
4194                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4195                "revokeRuntimePermission");
4196
4197        int callingUid = Binder.getCallingUid();
4198        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4199            mContext.enforceCallingOrSelfPermission(
4200                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4201                    "resetRuntimePermissions");
4202        }
4203
4204        synchronized (mPackages) {
4205            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4206            for (int userId : UserManagerService.getInstance().getUserIds()) {
4207                final int packageCount = mPackages.size();
4208                for (int i = 0; i < packageCount; i++) {
4209                    PackageParser.Package pkg = mPackages.valueAt(i);
4210                    if (!(pkg.mExtras instanceof PackageSetting)) {
4211                        continue;
4212                    }
4213                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4214                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4215                }
4216            }
4217        }
4218    }
4219
4220    @Override
4221    public int getPermissionFlags(String name, String packageName, int userId) {
4222        if (!sUserManager.exists(userId)) {
4223            return 0;
4224        }
4225
4226        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4227
4228        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4229                true /* requireFullPermission */, false /* checkShell */,
4230                "getPermissionFlags");
4231
4232        synchronized (mPackages) {
4233            final PackageParser.Package pkg = mPackages.get(packageName);
4234            if (pkg == null) {
4235                return 0;
4236            }
4237
4238            final BasePermission bp = mSettings.mPermissions.get(name);
4239            if (bp == null) {
4240                return 0;
4241            }
4242
4243            SettingBase sb = (SettingBase) pkg.mExtras;
4244            if (sb == null) {
4245                return 0;
4246            }
4247
4248            PermissionsState permissionsState = sb.getPermissionsState();
4249            return permissionsState.getPermissionFlags(name, userId);
4250        }
4251    }
4252
4253    @Override
4254    public void updatePermissionFlags(String name, String packageName, int flagMask,
4255            int flagValues, int userId) {
4256        if (!sUserManager.exists(userId)) {
4257            return;
4258        }
4259
4260        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4261
4262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4263                true /* requireFullPermission */, true /* checkShell */,
4264                "updatePermissionFlags");
4265
4266        // Only the system can change these flags and nothing else.
4267        if (getCallingUid() != Process.SYSTEM_UID) {
4268            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4269            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4270            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4271            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4272            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4273        }
4274
4275        synchronized (mPackages) {
4276            final PackageParser.Package pkg = mPackages.get(packageName);
4277            if (pkg == null) {
4278                throw new IllegalArgumentException("Unknown package: " + packageName);
4279            }
4280
4281            final BasePermission bp = mSettings.mPermissions.get(name);
4282            if (bp == null) {
4283                throw new IllegalArgumentException("Unknown permission: " + name);
4284            }
4285
4286            SettingBase sb = (SettingBase) pkg.mExtras;
4287            if (sb == null) {
4288                throw new IllegalArgumentException("Unknown package: " + packageName);
4289            }
4290
4291            PermissionsState permissionsState = sb.getPermissionsState();
4292
4293            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4294
4295            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4296                // Install and runtime permissions are stored in different places,
4297                // so figure out what permission changed and persist the change.
4298                if (permissionsState.getInstallPermissionState(name) != null) {
4299                    scheduleWriteSettingsLocked();
4300                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4301                        || hadState) {
4302                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4303                }
4304            }
4305        }
4306    }
4307
4308    /**
4309     * Update the permission flags for all packages and runtime permissions of a user in order
4310     * to allow device or profile owner to remove POLICY_FIXED.
4311     */
4312    @Override
4313    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4314        if (!sUserManager.exists(userId)) {
4315            return;
4316        }
4317
4318        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4319
4320        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4321                true /* requireFullPermission */, true /* checkShell */,
4322                "updatePermissionFlagsForAllApps");
4323
4324        // Only the system can change system fixed flags.
4325        if (getCallingUid() != Process.SYSTEM_UID) {
4326            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4327            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4328        }
4329
4330        synchronized (mPackages) {
4331            boolean changed = false;
4332            final int packageCount = mPackages.size();
4333            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4334                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4335                SettingBase sb = (SettingBase) pkg.mExtras;
4336                if (sb == null) {
4337                    continue;
4338                }
4339                PermissionsState permissionsState = sb.getPermissionsState();
4340                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4341                        userId, flagMask, flagValues);
4342            }
4343            if (changed) {
4344                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4345            }
4346        }
4347    }
4348
4349    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4350        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4351                != PackageManager.PERMISSION_GRANTED
4352            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4353                != PackageManager.PERMISSION_GRANTED) {
4354            throw new SecurityException(message + " requires "
4355                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4356                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4357        }
4358    }
4359
4360    @Override
4361    public boolean shouldShowRequestPermissionRationale(String permissionName,
4362            String packageName, int userId) {
4363        if (UserHandle.getCallingUserId() != userId) {
4364            mContext.enforceCallingPermission(
4365                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4366                    "canShowRequestPermissionRationale for user " + userId);
4367        }
4368
4369        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4370        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4371            return false;
4372        }
4373
4374        if (checkPermission(permissionName, packageName, userId)
4375                == PackageManager.PERMISSION_GRANTED) {
4376            return false;
4377        }
4378
4379        final int flags;
4380
4381        final long identity = Binder.clearCallingIdentity();
4382        try {
4383            flags = getPermissionFlags(permissionName,
4384                    packageName, userId);
4385        } finally {
4386            Binder.restoreCallingIdentity(identity);
4387        }
4388
4389        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4390                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4391                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4392
4393        if ((flags & fixedFlags) != 0) {
4394            return false;
4395        }
4396
4397        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4398    }
4399
4400    @Override
4401    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4402        mContext.enforceCallingOrSelfPermission(
4403                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4404                "addOnPermissionsChangeListener");
4405
4406        synchronized (mPackages) {
4407            mOnPermissionChangeListeners.addListenerLocked(listener);
4408        }
4409    }
4410
4411    @Override
4412    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4413        synchronized (mPackages) {
4414            mOnPermissionChangeListeners.removeListenerLocked(listener);
4415        }
4416    }
4417
4418    @Override
4419    public boolean isProtectedBroadcast(String actionName) {
4420        synchronized (mPackages) {
4421            if (mProtectedBroadcasts.contains(actionName)) {
4422                return true;
4423            } else if (actionName != null) {
4424                // TODO: remove these terrible hacks
4425                if (actionName.startsWith("android.net.netmon.lingerExpired")
4426                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4427                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4428                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4429                    return true;
4430                }
4431            }
4432        }
4433        return false;
4434    }
4435
4436    @Override
4437    public int checkSignatures(String pkg1, String pkg2) {
4438        synchronized (mPackages) {
4439            final PackageParser.Package p1 = mPackages.get(pkg1);
4440            final PackageParser.Package p2 = mPackages.get(pkg2);
4441            if (p1 == null || p1.mExtras == null
4442                    || p2 == null || p2.mExtras == null) {
4443                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4444            }
4445            return compareSignatures(p1.mSignatures, p2.mSignatures);
4446        }
4447    }
4448
4449    @Override
4450    public int checkUidSignatures(int uid1, int uid2) {
4451        // Map to base uids.
4452        uid1 = UserHandle.getAppId(uid1);
4453        uid2 = UserHandle.getAppId(uid2);
4454        // reader
4455        synchronized (mPackages) {
4456            Signature[] s1;
4457            Signature[] s2;
4458            Object obj = mSettings.getUserIdLPr(uid1);
4459            if (obj != null) {
4460                if (obj instanceof SharedUserSetting) {
4461                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4462                } else if (obj instanceof PackageSetting) {
4463                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4464                } else {
4465                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4466                }
4467            } else {
4468                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4469            }
4470            obj = mSettings.getUserIdLPr(uid2);
4471            if (obj != null) {
4472                if (obj instanceof SharedUserSetting) {
4473                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4474                } else if (obj instanceof PackageSetting) {
4475                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4476                } else {
4477                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4478                }
4479            } else {
4480                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4481            }
4482            return compareSignatures(s1, s2);
4483        }
4484    }
4485
4486    /**
4487     * This method should typically only be used when granting or revoking
4488     * permissions, since the app may immediately restart after this call.
4489     * <p>
4490     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4491     * guard your work against the app being relaunched.
4492     */
4493    private void killUid(int appId, int userId, String reason) {
4494        final long identity = Binder.clearCallingIdentity();
4495        try {
4496            IActivityManager am = ActivityManagerNative.getDefault();
4497            if (am != null) {
4498                try {
4499                    am.killUid(appId, userId, reason);
4500                } catch (RemoteException e) {
4501                    /* ignore - same process */
4502                }
4503            }
4504        } finally {
4505            Binder.restoreCallingIdentity(identity);
4506        }
4507    }
4508
4509    /**
4510     * Compares two sets of signatures. Returns:
4511     * <br />
4512     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4513     * <br />
4514     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4515     * <br />
4516     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4517     * <br />
4518     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4519     * <br />
4520     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4521     */
4522    static int compareSignatures(Signature[] s1, Signature[] s2) {
4523        if (s1 == null) {
4524            return s2 == null
4525                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4526                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4527        }
4528
4529        if (s2 == null) {
4530            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4531        }
4532
4533        if (s1.length != s2.length) {
4534            return PackageManager.SIGNATURE_NO_MATCH;
4535        }
4536
4537        // Since both signature sets are of size 1, we can compare without HashSets.
4538        if (s1.length == 1) {
4539            return s1[0].equals(s2[0]) ?
4540                    PackageManager.SIGNATURE_MATCH :
4541                    PackageManager.SIGNATURE_NO_MATCH;
4542        }
4543
4544        ArraySet<Signature> set1 = new ArraySet<Signature>();
4545        for (Signature sig : s1) {
4546            set1.add(sig);
4547        }
4548        ArraySet<Signature> set2 = new ArraySet<Signature>();
4549        for (Signature sig : s2) {
4550            set2.add(sig);
4551        }
4552        // Make sure s2 contains all signatures in s1.
4553        if (set1.equals(set2)) {
4554            return PackageManager.SIGNATURE_MATCH;
4555        }
4556        return PackageManager.SIGNATURE_NO_MATCH;
4557    }
4558
4559    /**
4560     * If the database version for this type of package (internal storage or
4561     * external storage) is less than the version where package signatures
4562     * were updated, return true.
4563     */
4564    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4565        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4566        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4567    }
4568
4569    /**
4570     * Used for backward compatibility to make sure any packages with
4571     * certificate chains get upgraded to the new style. {@code existingSigs}
4572     * will be in the old format (since they were stored on disk from before the
4573     * system upgrade) and {@code scannedSigs} will be in the newer format.
4574     */
4575    private int compareSignaturesCompat(PackageSignatures existingSigs,
4576            PackageParser.Package scannedPkg) {
4577        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4578            return PackageManager.SIGNATURE_NO_MATCH;
4579        }
4580
4581        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4582        for (Signature sig : existingSigs.mSignatures) {
4583            existingSet.add(sig);
4584        }
4585        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4586        for (Signature sig : scannedPkg.mSignatures) {
4587            try {
4588                Signature[] chainSignatures = sig.getChainSignatures();
4589                for (Signature chainSig : chainSignatures) {
4590                    scannedCompatSet.add(chainSig);
4591                }
4592            } catch (CertificateEncodingException e) {
4593                scannedCompatSet.add(sig);
4594            }
4595        }
4596        /*
4597         * Make sure the expanded scanned set contains all signatures in the
4598         * existing one.
4599         */
4600        if (scannedCompatSet.equals(existingSet)) {
4601            // Migrate the old signatures to the new scheme.
4602            existingSigs.assignSignatures(scannedPkg.mSignatures);
4603            // The new KeySets will be re-added later in the scanning process.
4604            synchronized (mPackages) {
4605                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4606            }
4607            return PackageManager.SIGNATURE_MATCH;
4608        }
4609        return PackageManager.SIGNATURE_NO_MATCH;
4610    }
4611
4612    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4613        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4614        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4615    }
4616
4617    private int compareSignaturesRecover(PackageSignatures existingSigs,
4618            PackageParser.Package scannedPkg) {
4619        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4620            return PackageManager.SIGNATURE_NO_MATCH;
4621        }
4622
4623        String msg = null;
4624        try {
4625            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4626                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4627                        + scannedPkg.packageName);
4628                return PackageManager.SIGNATURE_MATCH;
4629            }
4630        } catch (CertificateException e) {
4631            msg = e.getMessage();
4632        }
4633
4634        logCriticalInfo(Log.INFO,
4635                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4636        return PackageManager.SIGNATURE_NO_MATCH;
4637    }
4638
4639    @Override
4640    public List<String> getAllPackages() {
4641        synchronized (mPackages) {
4642            return new ArrayList<String>(mPackages.keySet());
4643        }
4644    }
4645
4646    @Override
4647    public String[] getPackagesForUid(int uid) {
4648        uid = UserHandle.getAppId(uid);
4649        // reader
4650        synchronized (mPackages) {
4651            Object obj = mSettings.getUserIdLPr(uid);
4652            if (obj instanceof SharedUserSetting) {
4653                final SharedUserSetting sus = (SharedUserSetting) obj;
4654                final int N = sus.packages.size();
4655                final String[] res = new String[N];
4656                for (int i = 0; i < N; i++) {
4657                    res[i] = sus.packages.valueAt(i).name;
4658                }
4659                return res;
4660            } else if (obj instanceof PackageSetting) {
4661                final PackageSetting ps = (PackageSetting) obj;
4662                return new String[] { ps.name };
4663            }
4664        }
4665        return null;
4666    }
4667
4668    @Override
4669    public String getNameForUid(int uid) {
4670        // reader
4671        synchronized (mPackages) {
4672            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4673            if (obj instanceof SharedUserSetting) {
4674                final SharedUserSetting sus = (SharedUserSetting) obj;
4675                return sus.name + ":" + sus.userId;
4676            } else if (obj instanceof PackageSetting) {
4677                final PackageSetting ps = (PackageSetting) obj;
4678                return ps.name;
4679            }
4680        }
4681        return null;
4682    }
4683
4684    @Override
4685    public int getUidForSharedUser(String sharedUserName) {
4686        if(sharedUserName == null) {
4687            return -1;
4688        }
4689        // reader
4690        synchronized (mPackages) {
4691            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4692            if (suid == null) {
4693                return -1;
4694            }
4695            return suid.userId;
4696        }
4697    }
4698
4699    @Override
4700    public int getFlagsForUid(int uid) {
4701        synchronized (mPackages) {
4702            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4703            if (obj instanceof SharedUserSetting) {
4704                final SharedUserSetting sus = (SharedUserSetting) obj;
4705                return sus.pkgFlags;
4706            } else if (obj instanceof PackageSetting) {
4707                final PackageSetting ps = (PackageSetting) obj;
4708                return ps.pkgFlags;
4709            }
4710        }
4711        return 0;
4712    }
4713
4714    @Override
4715    public int getPrivateFlagsForUid(int uid) {
4716        synchronized (mPackages) {
4717            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4718            if (obj instanceof SharedUserSetting) {
4719                final SharedUserSetting sus = (SharedUserSetting) obj;
4720                return sus.pkgPrivateFlags;
4721            } else if (obj instanceof PackageSetting) {
4722                final PackageSetting ps = (PackageSetting) obj;
4723                return ps.pkgPrivateFlags;
4724            }
4725        }
4726        return 0;
4727    }
4728
4729    @Override
4730    public boolean isUidPrivileged(int uid) {
4731        uid = UserHandle.getAppId(uid);
4732        // reader
4733        synchronized (mPackages) {
4734            Object obj = mSettings.getUserIdLPr(uid);
4735            if (obj instanceof SharedUserSetting) {
4736                final SharedUserSetting sus = (SharedUserSetting) obj;
4737                final Iterator<PackageSetting> it = sus.packages.iterator();
4738                while (it.hasNext()) {
4739                    if (it.next().isPrivileged()) {
4740                        return true;
4741                    }
4742                }
4743            } else if (obj instanceof PackageSetting) {
4744                final PackageSetting ps = (PackageSetting) obj;
4745                return ps.isPrivileged();
4746            }
4747        }
4748        return false;
4749    }
4750
4751    @Override
4752    public String[] getAppOpPermissionPackages(String permissionName) {
4753        synchronized (mPackages) {
4754            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4755            if (pkgs == null) {
4756                return null;
4757            }
4758            return pkgs.toArray(new String[pkgs.size()]);
4759        }
4760    }
4761
4762    @Override
4763    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4764            int flags, int userId) {
4765        try {
4766            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4767
4768            if (!sUserManager.exists(userId)) return null;
4769            flags = updateFlagsForResolve(flags, userId, intent);
4770            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4771                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4772
4773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4774            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4775                    flags, userId);
4776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4777
4778            final ResolveInfo bestChoice =
4779                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4780            return bestChoice;
4781        } finally {
4782            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4783        }
4784    }
4785
4786    @Override
4787    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4788            IntentFilter filter, int match, ComponentName activity) {
4789        final int userId = UserHandle.getCallingUserId();
4790        if (DEBUG_PREFERRED) {
4791            Log.v(TAG, "setLastChosenActivity intent=" + intent
4792                + " resolvedType=" + resolvedType
4793                + " flags=" + flags
4794                + " filter=" + filter
4795                + " match=" + match
4796                + " activity=" + activity);
4797            filter.dump(new PrintStreamPrinter(System.out), "    ");
4798        }
4799        intent.setComponent(null);
4800        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4801                userId);
4802        // Find any earlier preferred or last chosen entries and nuke them
4803        findPreferredActivity(intent, resolvedType,
4804                flags, query, 0, false, true, false, userId);
4805        // Add the new activity as the last chosen for this filter
4806        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4807                "Setting last chosen");
4808    }
4809
4810    @Override
4811    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4812        final int userId = UserHandle.getCallingUserId();
4813        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4814        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4815                userId);
4816        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4817                false, false, false, userId);
4818    }
4819
4820    private boolean isEphemeralDisabled() {
4821        // ephemeral apps have been disabled across the board
4822        if (DISABLE_EPHEMERAL_APPS) {
4823            return true;
4824        }
4825        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4826        if (!mSystemReady) {
4827            return true;
4828        }
4829        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4830    }
4831
4832    private boolean isEphemeralAllowed(
4833            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4834            boolean skipPackageCheck) {
4835        // Short circuit and return early if possible.
4836        if (isEphemeralDisabled()) {
4837            return false;
4838        }
4839        final int callingUser = UserHandle.getCallingUserId();
4840        if (callingUser != UserHandle.USER_SYSTEM) {
4841            return false;
4842        }
4843        if (mEphemeralResolverConnection == null) {
4844            return false;
4845        }
4846        if (intent.getComponent() != null) {
4847            return false;
4848        }
4849        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4850            return false;
4851        }
4852        if (!skipPackageCheck && intent.getPackage() != null) {
4853            return false;
4854        }
4855        final boolean isWebUri = hasWebURI(intent);
4856        if (!isWebUri || intent.getData().getHost() == null) {
4857            return false;
4858        }
4859        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4860        synchronized (mPackages) {
4861            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4862            for (int n = 0; n < count; n++) {
4863                ResolveInfo info = resolvedActivities.get(n);
4864                String packageName = info.activityInfo.packageName;
4865                PackageSetting ps = mSettings.mPackages.get(packageName);
4866                if (ps != null) {
4867                    // Try to get the status from User settings first
4868                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4869                    int status = (int) (packedStatus >> 32);
4870                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4871                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4872                        if (DEBUG_EPHEMERAL) {
4873                            Slog.v(TAG, "DENY ephemeral apps;"
4874                                + " pkg: " + packageName + ", status: " + status);
4875                        }
4876                        return false;
4877                    }
4878                }
4879            }
4880        }
4881        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4882        return true;
4883    }
4884
4885    private static EphemeralResolveInfo getEphemeralResolveInfo(
4886            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4887            String resolvedType, int userId, String packageName) {
4888        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4889                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4890        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4891                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4892        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4893                ephemeralPrefixCount);
4894        final int[] shaPrefix = digest.getDigestPrefix();
4895        final byte[][] digestBytes = digest.getDigestBytes();
4896        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4897                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4898        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4899            // No hash prefix match; there are no ephemeral apps for this domain.
4900            return null;
4901        }
4902
4903        // Go in reverse order so we match the narrowest scope first.
4904        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4905            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4906                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4907                    continue;
4908                }
4909                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4910                // No filters; this should never happen.
4911                if (filters.isEmpty()) {
4912                    continue;
4913                }
4914                if (packageName != null
4915                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4916                    continue;
4917                }
4918                // We have a domain match; resolve the filters to see if anything matches.
4919                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4920                for (int j = filters.size() - 1; j >= 0; --j) {
4921                    final EphemeralResolveIntentInfo intentInfo =
4922                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4923                    ephemeralResolver.addFilter(intentInfo);
4924                }
4925                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4926                        intent, resolvedType, false /*defaultOnly*/, userId);
4927                if (!matchedResolveInfoList.isEmpty()) {
4928                    return matchedResolveInfoList.get(0);
4929                }
4930            }
4931        }
4932        // Hash or filter mis-match; no ephemeral apps for this domain.
4933        return null;
4934    }
4935
4936    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4937            int flags, List<ResolveInfo> query, int userId) {
4938        if (query != null) {
4939            final int N = query.size();
4940            if (N == 1) {
4941                return query.get(0);
4942            } else if (N > 1) {
4943                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4944                // If there is more than one activity with the same priority,
4945                // then let the user decide between them.
4946                ResolveInfo r0 = query.get(0);
4947                ResolveInfo r1 = query.get(1);
4948                if (DEBUG_INTENT_MATCHING || debug) {
4949                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4950                            + r1.activityInfo.name + "=" + r1.priority);
4951                }
4952                // If the first activity has a higher priority, or a different
4953                // default, then it is always desirable to pick it.
4954                if (r0.priority != r1.priority
4955                        || r0.preferredOrder != r1.preferredOrder
4956                        || r0.isDefault != r1.isDefault) {
4957                    return query.get(0);
4958                }
4959                // If we have saved a preference for a preferred activity for
4960                // this Intent, use that.
4961                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4962                        flags, query, r0.priority, true, false, debug, userId);
4963                if (ri != null) {
4964                    return ri;
4965                }
4966                ri = new ResolveInfo(mResolveInfo);
4967                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4968                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4969                // If all of the options come from the same package, show the application's
4970                // label and icon instead of the generic resolver's.
4971                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4972                // and then throw away the ResolveInfo itself, meaning that the caller loses
4973                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4974                // a fallback for this case; we only set the target package's resources on
4975                // the ResolveInfo, not the ActivityInfo.
4976                final String intentPackage = intent.getPackage();
4977                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4978                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4979                    ri.resolvePackageName = intentPackage;
4980                    if (userNeedsBadging(userId)) {
4981                        ri.noResourceId = true;
4982                    } else {
4983                        ri.icon = appi.icon;
4984                    }
4985                    ri.iconResourceId = appi.icon;
4986                    ri.labelRes = appi.labelRes;
4987                }
4988                ri.activityInfo.applicationInfo = new ApplicationInfo(
4989                        ri.activityInfo.applicationInfo);
4990                if (userId != 0) {
4991                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4992                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4993                }
4994                // Make sure that the resolver is displayable in car mode
4995                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4996                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4997                return ri;
4998            }
4999        }
5000        return null;
5001    }
5002
5003    /**
5004     * Return true if the given list is not empty and all of its contents have
5005     * an activityInfo with the given package name.
5006     */
5007    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5008        if (ArrayUtils.isEmpty(list)) {
5009            return false;
5010        }
5011        for (int i = 0, N = list.size(); i < N; i++) {
5012            final ResolveInfo ri = list.get(i);
5013            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5014            if (ai == null || !packageName.equals(ai.packageName)) {
5015                return false;
5016            }
5017        }
5018        return true;
5019    }
5020
5021    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5022            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5023        final int N = query.size();
5024        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5025                .get(userId);
5026        // Get the list of persistent preferred activities that handle the intent
5027        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5028        List<PersistentPreferredActivity> pprefs = ppir != null
5029                ? ppir.queryIntent(intent, resolvedType,
5030                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5031                : null;
5032        if (pprefs != null && pprefs.size() > 0) {
5033            final int M = pprefs.size();
5034            for (int i=0; i<M; i++) {
5035                final PersistentPreferredActivity ppa = pprefs.get(i);
5036                if (DEBUG_PREFERRED || debug) {
5037                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5038                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5039                            + "\n  component=" + ppa.mComponent);
5040                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5041                }
5042                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5043                        flags | MATCH_DISABLED_COMPONENTS, userId);
5044                if (DEBUG_PREFERRED || debug) {
5045                    Slog.v(TAG, "Found persistent preferred activity:");
5046                    if (ai != null) {
5047                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5048                    } else {
5049                        Slog.v(TAG, "  null");
5050                    }
5051                }
5052                if (ai == null) {
5053                    // This previously registered persistent preferred activity
5054                    // component is no longer known. Ignore it and do NOT remove it.
5055                    continue;
5056                }
5057                for (int j=0; j<N; j++) {
5058                    final ResolveInfo ri = query.get(j);
5059                    if (!ri.activityInfo.applicationInfo.packageName
5060                            .equals(ai.applicationInfo.packageName)) {
5061                        continue;
5062                    }
5063                    if (!ri.activityInfo.name.equals(ai.name)) {
5064                        continue;
5065                    }
5066                    //  Found a persistent preference that can handle the intent.
5067                    if (DEBUG_PREFERRED || debug) {
5068                        Slog.v(TAG, "Returning persistent preferred activity: " +
5069                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5070                    }
5071                    return ri;
5072                }
5073            }
5074        }
5075        return null;
5076    }
5077
5078    // TODO: handle preferred activities missing while user has amnesia
5079    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5080            List<ResolveInfo> query, int priority, boolean always,
5081            boolean removeMatches, boolean debug, int userId) {
5082        if (!sUserManager.exists(userId)) return null;
5083        flags = updateFlagsForResolve(flags, userId, intent);
5084        // writer
5085        synchronized (mPackages) {
5086            if (intent.getSelector() != null) {
5087                intent = intent.getSelector();
5088            }
5089            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5090
5091            // Try to find a matching persistent preferred activity.
5092            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5093                    debug, userId);
5094
5095            // If a persistent preferred activity matched, use it.
5096            if (pri != null) {
5097                return pri;
5098            }
5099
5100            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5101            // Get the list of preferred activities that handle the intent
5102            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5103            List<PreferredActivity> prefs = pir != null
5104                    ? pir.queryIntent(intent, resolvedType,
5105                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5106                    : null;
5107            if (prefs != null && prefs.size() > 0) {
5108                boolean changed = false;
5109                try {
5110                    // First figure out how good the original match set is.
5111                    // We will only allow preferred activities that came
5112                    // from the same match quality.
5113                    int match = 0;
5114
5115                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5116
5117                    final int N = query.size();
5118                    for (int j=0; j<N; j++) {
5119                        final ResolveInfo ri = query.get(j);
5120                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5121                                + ": 0x" + Integer.toHexString(match));
5122                        if (ri.match > match) {
5123                            match = ri.match;
5124                        }
5125                    }
5126
5127                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5128                            + Integer.toHexString(match));
5129
5130                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5131                    final int M = prefs.size();
5132                    for (int i=0; i<M; i++) {
5133                        final PreferredActivity pa = prefs.get(i);
5134                        if (DEBUG_PREFERRED || debug) {
5135                            Slog.v(TAG, "Checking PreferredActivity ds="
5136                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5137                                    + "\n  component=" + pa.mPref.mComponent);
5138                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5139                        }
5140                        if (pa.mPref.mMatch != match) {
5141                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5142                                    + Integer.toHexString(pa.mPref.mMatch));
5143                            continue;
5144                        }
5145                        // If it's not an "always" type preferred activity and that's what we're
5146                        // looking for, skip it.
5147                        if (always && !pa.mPref.mAlways) {
5148                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5149                            continue;
5150                        }
5151                        final ActivityInfo ai = getActivityInfo(
5152                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5153                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5154                                userId);
5155                        if (DEBUG_PREFERRED || debug) {
5156                            Slog.v(TAG, "Found preferred activity:");
5157                            if (ai != null) {
5158                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5159                            } else {
5160                                Slog.v(TAG, "  null");
5161                            }
5162                        }
5163                        if (ai == null) {
5164                            // This previously registered preferred activity
5165                            // component is no longer known.  Most likely an update
5166                            // to the app was installed and in the new version this
5167                            // component no longer exists.  Clean it up by removing
5168                            // it from the preferred activities list, and skip it.
5169                            Slog.w(TAG, "Removing dangling preferred activity: "
5170                                    + pa.mPref.mComponent);
5171                            pir.removeFilter(pa);
5172                            changed = true;
5173                            continue;
5174                        }
5175                        for (int j=0; j<N; j++) {
5176                            final ResolveInfo ri = query.get(j);
5177                            if (!ri.activityInfo.applicationInfo.packageName
5178                                    .equals(ai.applicationInfo.packageName)) {
5179                                continue;
5180                            }
5181                            if (!ri.activityInfo.name.equals(ai.name)) {
5182                                continue;
5183                            }
5184
5185                            if (removeMatches) {
5186                                pir.removeFilter(pa);
5187                                changed = true;
5188                                if (DEBUG_PREFERRED) {
5189                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5190                                }
5191                                break;
5192                            }
5193
5194                            // Okay we found a previously set preferred or last chosen app.
5195                            // If the result set is different from when this
5196                            // was created, we need to clear it and re-ask the
5197                            // user their preference, if we're looking for an "always" type entry.
5198                            if (always && !pa.mPref.sameSet(query)) {
5199                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5200                                        + intent + " type " + resolvedType);
5201                                if (DEBUG_PREFERRED) {
5202                                    Slog.v(TAG, "Removing preferred activity since set changed "
5203                                            + pa.mPref.mComponent);
5204                                }
5205                                pir.removeFilter(pa);
5206                                // Re-add the filter as a "last chosen" entry (!always)
5207                                PreferredActivity lastChosen = new PreferredActivity(
5208                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5209                                pir.addFilter(lastChosen);
5210                                changed = true;
5211                                return null;
5212                            }
5213
5214                            // Yay! Either the set matched or we're looking for the last chosen
5215                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5216                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5217                            return ri;
5218                        }
5219                    }
5220                } finally {
5221                    if (changed) {
5222                        if (DEBUG_PREFERRED) {
5223                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5224                        }
5225                        scheduleWritePackageRestrictionsLocked(userId);
5226                    }
5227                }
5228            }
5229        }
5230        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5231        return null;
5232    }
5233
5234    /*
5235     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5236     */
5237    @Override
5238    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5239            int targetUserId) {
5240        mContext.enforceCallingOrSelfPermission(
5241                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5242        List<CrossProfileIntentFilter> matches =
5243                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5244        if (matches != null) {
5245            int size = matches.size();
5246            for (int i = 0; i < size; i++) {
5247                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5248            }
5249        }
5250        if (hasWebURI(intent)) {
5251            // cross-profile app linking works only towards the parent.
5252            final UserInfo parent = getProfileParent(sourceUserId);
5253            synchronized(mPackages) {
5254                int flags = updateFlagsForResolve(0, parent.id, intent);
5255                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5256                        intent, resolvedType, flags, sourceUserId, parent.id);
5257                return xpDomainInfo != null;
5258            }
5259        }
5260        return false;
5261    }
5262
5263    private UserInfo getProfileParent(int userId) {
5264        final long identity = Binder.clearCallingIdentity();
5265        try {
5266            return sUserManager.getProfileParent(userId);
5267        } finally {
5268            Binder.restoreCallingIdentity(identity);
5269        }
5270    }
5271
5272    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5273            String resolvedType, int userId) {
5274        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5275        if (resolver != null) {
5276            return resolver.queryIntent(intent, resolvedType, false, userId);
5277        }
5278        return null;
5279    }
5280
5281    @Override
5282    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5283            String resolvedType, int flags, int userId) {
5284        try {
5285            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5286
5287            return new ParceledListSlice<>(
5288                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5289        } finally {
5290            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5291        }
5292    }
5293
5294    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5295            String resolvedType, int flags, int userId) {
5296        if (!sUserManager.exists(userId)) return Collections.emptyList();
5297        flags = updateFlagsForResolve(flags, userId, intent);
5298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5299                false /* requireFullPermission */, false /* checkShell */,
5300                "query intent activities");
5301        ComponentName comp = intent.getComponent();
5302        if (comp == null) {
5303            if (intent.getSelector() != null) {
5304                intent = intent.getSelector();
5305                comp = intent.getComponent();
5306            }
5307        }
5308
5309        if (comp != null) {
5310            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5311            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5312            if (ai != null) {
5313                final ResolveInfo ri = new ResolveInfo();
5314                ri.activityInfo = ai;
5315                list.add(ri);
5316            }
5317            return list;
5318        }
5319
5320        // reader
5321        boolean sortResult = false;
5322        boolean addEphemeral = false;
5323        boolean matchEphemeralPackage = false;
5324        List<ResolveInfo> result;
5325        final String pkgName = intent.getPackage();
5326        synchronized (mPackages) {
5327            if (pkgName == null) {
5328                List<CrossProfileIntentFilter> matchingFilters =
5329                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5330                // Check for results that need to skip the current profile.
5331                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5332                        resolvedType, flags, userId);
5333                if (xpResolveInfo != null) {
5334                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5335                    xpResult.add(xpResolveInfo);
5336                    return filterIfNotSystemUser(xpResult, userId);
5337                }
5338
5339                // Check for results in the current profile.
5340                result = filterIfNotSystemUser(mActivities.queryIntent(
5341                        intent, resolvedType, flags, userId), userId);
5342                addEphemeral =
5343                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5344
5345                // Check for cross profile results.
5346                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5347                xpResolveInfo = queryCrossProfileIntents(
5348                        matchingFilters, intent, resolvedType, flags, userId,
5349                        hasNonNegativePriorityResult);
5350                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5351                    boolean isVisibleToUser = filterIfNotSystemUser(
5352                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5353                    if (isVisibleToUser) {
5354                        result.add(xpResolveInfo);
5355                        sortResult = true;
5356                    }
5357                }
5358                if (hasWebURI(intent)) {
5359                    CrossProfileDomainInfo xpDomainInfo = null;
5360                    final UserInfo parent = getProfileParent(userId);
5361                    if (parent != null) {
5362                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5363                                flags, userId, parent.id);
5364                    }
5365                    if (xpDomainInfo != null) {
5366                        if (xpResolveInfo != null) {
5367                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5368                            // in the result.
5369                            result.remove(xpResolveInfo);
5370                        }
5371                        if (result.size() == 0 && !addEphemeral) {
5372                            result.add(xpDomainInfo.resolveInfo);
5373                            return result;
5374                        }
5375                    }
5376                    if (result.size() > 1 || addEphemeral) {
5377                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5378                                intent, flags, result, xpDomainInfo, userId);
5379                        sortResult = true;
5380                    }
5381                }
5382            } else {
5383                final PackageParser.Package pkg = mPackages.get(pkgName);
5384                if (pkg != null) {
5385                    result = filterIfNotSystemUser(
5386                            mActivities.queryIntentForPackage(
5387                                    intent, resolvedType, flags, pkg.activities, userId),
5388                            userId);
5389                } else {
5390                    // the caller wants to resolve for a particular package; however, there
5391                    // were no installed results, so, try to find an ephemeral result
5392                    addEphemeral = isEphemeralAllowed(
5393                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5394                    matchEphemeralPackage = true;
5395                    result = new ArrayList<ResolveInfo>();
5396                }
5397            }
5398        }
5399        if (addEphemeral) {
5400            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5401            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5402                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5403                    matchEphemeralPackage ? pkgName : null);
5404            if (ai != null) {
5405                if (DEBUG_EPHEMERAL) {
5406                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5407                }
5408                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5409                ephemeralInstaller.ephemeralResolveInfo = ai;
5410                // make sure this resolver is the default
5411                ephemeralInstaller.isDefault = true;
5412                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5413                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5414                // add a non-generic filter
5415                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5416                ephemeralInstaller.filter.addDataPath(
5417                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5418                result.add(ephemeralInstaller);
5419            }
5420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5421        }
5422        if (sortResult) {
5423            Collections.sort(result, mResolvePrioritySorter);
5424        }
5425        return result;
5426    }
5427
5428    private static class CrossProfileDomainInfo {
5429        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5430        ResolveInfo resolveInfo;
5431        /* Best domain verification status of the activities found in the other profile */
5432        int bestDomainVerificationStatus;
5433    }
5434
5435    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5436            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5437        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5438                sourceUserId)) {
5439            return null;
5440        }
5441        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5442                resolvedType, flags, parentUserId);
5443
5444        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5445            return null;
5446        }
5447        CrossProfileDomainInfo result = null;
5448        int size = resultTargetUser.size();
5449        for (int i = 0; i < size; i++) {
5450            ResolveInfo riTargetUser = resultTargetUser.get(i);
5451            // Intent filter verification is only for filters that specify a host. So don't return
5452            // those that handle all web uris.
5453            if (riTargetUser.handleAllWebDataURI) {
5454                continue;
5455            }
5456            String packageName = riTargetUser.activityInfo.packageName;
5457            PackageSetting ps = mSettings.mPackages.get(packageName);
5458            if (ps == null) {
5459                continue;
5460            }
5461            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5462            int status = (int)(verificationState >> 32);
5463            if (result == null) {
5464                result = new CrossProfileDomainInfo();
5465                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5466                        sourceUserId, parentUserId);
5467                result.bestDomainVerificationStatus = status;
5468            } else {
5469                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5470                        result.bestDomainVerificationStatus);
5471            }
5472        }
5473        // Don't consider matches with status NEVER across profiles.
5474        if (result != null && result.bestDomainVerificationStatus
5475                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5476            return null;
5477        }
5478        return result;
5479    }
5480
5481    /**
5482     * Verification statuses are ordered from the worse to the best, except for
5483     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5484     */
5485    private int bestDomainVerificationStatus(int status1, int status2) {
5486        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5487            return status2;
5488        }
5489        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5490            return status1;
5491        }
5492        return (int) MathUtils.max(status1, status2);
5493    }
5494
5495    private boolean isUserEnabled(int userId) {
5496        long callingId = Binder.clearCallingIdentity();
5497        try {
5498            UserInfo userInfo = sUserManager.getUserInfo(userId);
5499            return userInfo != null && userInfo.isEnabled();
5500        } finally {
5501            Binder.restoreCallingIdentity(callingId);
5502        }
5503    }
5504
5505    /**
5506     * Filter out activities with systemUserOnly flag set, when current user is not System.
5507     *
5508     * @return filtered list
5509     */
5510    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5511        if (userId == UserHandle.USER_SYSTEM) {
5512            return resolveInfos;
5513        }
5514        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5515            ResolveInfo info = resolveInfos.get(i);
5516            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5517                resolveInfos.remove(i);
5518            }
5519        }
5520        return resolveInfos;
5521    }
5522
5523    /**
5524     * @param resolveInfos list of resolve infos in descending priority order
5525     * @return if the list contains a resolve info with non-negative priority
5526     */
5527    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5528        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5529    }
5530
5531    private static boolean hasWebURI(Intent intent) {
5532        if (intent.getData() == null) {
5533            return false;
5534        }
5535        final String scheme = intent.getScheme();
5536        if (TextUtils.isEmpty(scheme)) {
5537            return false;
5538        }
5539        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5540    }
5541
5542    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5543            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5544            int userId) {
5545        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5546
5547        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5548            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5549                    candidates.size());
5550        }
5551
5552        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5553        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5554        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5555        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5556        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5557        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5558
5559        synchronized (mPackages) {
5560            final int count = candidates.size();
5561            // First, try to use linked apps. Partition the candidates into four lists:
5562            // one for the final results, one for the "do not use ever", one for "undefined status"
5563            // and finally one for "browser app type".
5564            for (int n=0; n<count; n++) {
5565                ResolveInfo info = candidates.get(n);
5566                String packageName = info.activityInfo.packageName;
5567                PackageSetting ps = mSettings.mPackages.get(packageName);
5568                if (ps != null) {
5569                    // Add to the special match all list (Browser use case)
5570                    if (info.handleAllWebDataURI) {
5571                        matchAllList.add(info);
5572                        continue;
5573                    }
5574                    // Try to get the status from User settings first
5575                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5576                    int status = (int)(packedStatus >> 32);
5577                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5578                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5579                        if (DEBUG_DOMAIN_VERIFICATION) {
5580                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5581                                    + " : linkgen=" + linkGeneration);
5582                        }
5583                        // Use link-enabled generation as preferredOrder, i.e.
5584                        // prefer newly-enabled over earlier-enabled.
5585                        info.preferredOrder = linkGeneration;
5586                        alwaysList.add(info);
5587                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5588                        if (DEBUG_DOMAIN_VERIFICATION) {
5589                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5590                        }
5591                        neverList.add(info);
5592                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5593                        if (DEBUG_DOMAIN_VERIFICATION) {
5594                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5595                        }
5596                        alwaysAskList.add(info);
5597                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5598                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5599                        if (DEBUG_DOMAIN_VERIFICATION) {
5600                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5601                        }
5602                        undefinedList.add(info);
5603                    }
5604                }
5605            }
5606
5607            // We'll want to include browser possibilities in a few cases
5608            boolean includeBrowser = false;
5609
5610            // First try to add the "always" resolution(s) for the current user, if any
5611            if (alwaysList.size() > 0) {
5612                result.addAll(alwaysList);
5613            } else {
5614                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5615                result.addAll(undefinedList);
5616                // Maybe add one for the other profile.
5617                if (xpDomainInfo != null && (
5618                        xpDomainInfo.bestDomainVerificationStatus
5619                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5620                    result.add(xpDomainInfo.resolveInfo);
5621                }
5622                includeBrowser = true;
5623            }
5624
5625            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5626            // If there were 'always' entries their preferred order has been set, so we also
5627            // back that off to make the alternatives equivalent
5628            if (alwaysAskList.size() > 0) {
5629                for (ResolveInfo i : result) {
5630                    i.preferredOrder = 0;
5631                }
5632                result.addAll(alwaysAskList);
5633                includeBrowser = true;
5634            }
5635
5636            if (includeBrowser) {
5637                // Also add browsers (all of them or only the default one)
5638                if (DEBUG_DOMAIN_VERIFICATION) {
5639                    Slog.v(TAG, "   ...including browsers in candidate set");
5640                }
5641                if ((matchFlags & MATCH_ALL) != 0) {
5642                    result.addAll(matchAllList);
5643                } else {
5644                    // Browser/generic handling case.  If there's a default browser, go straight
5645                    // to that (but only if there is no other higher-priority match).
5646                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5647                    int maxMatchPrio = 0;
5648                    ResolveInfo defaultBrowserMatch = null;
5649                    final int numCandidates = matchAllList.size();
5650                    for (int n = 0; n < numCandidates; n++) {
5651                        ResolveInfo info = matchAllList.get(n);
5652                        // track the highest overall match priority...
5653                        if (info.priority > maxMatchPrio) {
5654                            maxMatchPrio = info.priority;
5655                        }
5656                        // ...and the highest-priority default browser match
5657                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5658                            if (defaultBrowserMatch == null
5659                                    || (defaultBrowserMatch.priority < info.priority)) {
5660                                if (debug) {
5661                                    Slog.v(TAG, "Considering default browser match " + info);
5662                                }
5663                                defaultBrowserMatch = info;
5664                            }
5665                        }
5666                    }
5667                    if (defaultBrowserMatch != null
5668                            && defaultBrowserMatch.priority >= maxMatchPrio
5669                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5670                    {
5671                        if (debug) {
5672                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5673                        }
5674                        result.add(defaultBrowserMatch);
5675                    } else {
5676                        result.addAll(matchAllList);
5677                    }
5678                }
5679
5680                // If there is nothing selected, add all candidates and remove the ones that the user
5681                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5682                if (result.size() == 0) {
5683                    result.addAll(candidates);
5684                    result.removeAll(neverList);
5685                }
5686            }
5687        }
5688        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5689            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5690                    result.size());
5691            for (ResolveInfo info : result) {
5692                Slog.v(TAG, "  + " + info.activityInfo);
5693            }
5694        }
5695        return result;
5696    }
5697
5698    // Returns a packed value as a long:
5699    //
5700    // high 'int'-sized word: link status: undefined/ask/never/always.
5701    // low 'int'-sized word: relative priority among 'always' results.
5702    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5703        long result = ps.getDomainVerificationStatusForUser(userId);
5704        // if none available, get the master status
5705        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5706            if (ps.getIntentFilterVerificationInfo() != null) {
5707                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5708            }
5709        }
5710        return result;
5711    }
5712
5713    private ResolveInfo querySkipCurrentProfileIntents(
5714            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5715            int flags, int sourceUserId) {
5716        if (matchingFilters != null) {
5717            int size = matchingFilters.size();
5718            for (int i = 0; i < size; i ++) {
5719                CrossProfileIntentFilter filter = matchingFilters.get(i);
5720                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5721                    // Checking if there are activities in the target user that can handle the
5722                    // intent.
5723                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5724                            resolvedType, flags, sourceUserId);
5725                    if (resolveInfo != null) {
5726                        return resolveInfo;
5727                    }
5728                }
5729            }
5730        }
5731        return null;
5732    }
5733
5734    // Return matching ResolveInfo in target user if any.
5735    private ResolveInfo queryCrossProfileIntents(
5736            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5737            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5738        if (matchingFilters != null) {
5739            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5740            // match the same intent. For performance reasons, it is better not to
5741            // run queryIntent twice for the same userId
5742            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5743            int size = matchingFilters.size();
5744            for (int i = 0; i < size; i++) {
5745                CrossProfileIntentFilter filter = matchingFilters.get(i);
5746                int targetUserId = filter.getTargetUserId();
5747                boolean skipCurrentProfile =
5748                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5749                boolean skipCurrentProfileIfNoMatchFound =
5750                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5751                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5752                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5753                    // Checking if there are activities in the target user that can handle the
5754                    // intent.
5755                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5756                            resolvedType, flags, sourceUserId);
5757                    if (resolveInfo != null) return resolveInfo;
5758                    alreadyTriedUserIds.put(targetUserId, true);
5759                }
5760            }
5761        }
5762        return null;
5763    }
5764
5765    /**
5766     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5767     * will forward the intent to the filter's target user.
5768     * Otherwise, returns null.
5769     */
5770    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5771            String resolvedType, int flags, int sourceUserId) {
5772        int targetUserId = filter.getTargetUserId();
5773        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5774                resolvedType, flags, targetUserId);
5775        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5776            // If all the matches in the target profile are suspended, return null.
5777            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5778                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5779                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5780                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5781                            targetUserId);
5782                }
5783            }
5784        }
5785        return null;
5786    }
5787
5788    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5789            int sourceUserId, int targetUserId) {
5790        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5791        long ident = Binder.clearCallingIdentity();
5792        boolean targetIsProfile;
5793        try {
5794            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5795        } finally {
5796            Binder.restoreCallingIdentity(ident);
5797        }
5798        String className;
5799        if (targetIsProfile) {
5800            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5801        } else {
5802            className = FORWARD_INTENT_TO_PARENT;
5803        }
5804        ComponentName forwardingActivityComponentName = new ComponentName(
5805                mAndroidApplication.packageName, className);
5806        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5807                sourceUserId);
5808        if (!targetIsProfile) {
5809            forwardingActivityInfo.showUserIcon = targetUserId;
5810            forwardingResolveInfo.noResourceId = true;
5811        }
5812        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5813        forwardingResolveInfo.priority = 0;
5814        forwardingResolveInfo.preferredOrder = 0;
5815        forwardingResolveInfo.match = 0;
5816        forwardingResolveInfo.isDefault = true;
5817        forwardingResolveInfo.filter = filter;
5818        forwardingResolveInfo.targetUserId = targetUserId;
5819        return forwardingResolveInfo;
5820    }
5821
5822    @Override
5823    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5824            Intent[] specifics, String[] specificTypes, Intent intent,
5825            String resolvedType, int flags, int userId) {
5826        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5827                specificTypes, intent, resolvedType, flags, userId));
5828    }
5829
5830    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5831            Intent[] specifics, String[] specificTypes, Intent intent,
5832            String resolvedType, int flags, int userId) {
5833        if (!sUserManager.exists(userId)) return Collections.emptyList();
5834        flags = updateFlagsForResolve(flags, userId, intent);
5835        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5836                false /* requireFullPermission */, false /* checkShell */,
5837                "query intent activity options");
5838        final String resultsAction = intent.getAction();
5839
5840        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5841                | PackageManager.GET_RESOLVED_FILTER, userId);
5842
5843        if (DEBUG_INTENT_MATCHING) {
5844            Log.v(TAG, "Query " + intent + ": " + results);
5845        }
5846
5847        int specificsPos = 0;
5848        int N;
5849
5850        // todo: note that the algorithm used here is O(N^2).  This
5851        // isn't a problem in our current environment, but if we start running
5852        // into situations where we have more than 5 or 10 matches then this
5853        // should probably be changed to something smarter...
5854
5855        // First we go through and resolve each of the specific items
5856        // that were supplied, taking care of removing any corresponding
5857        // duplicate items in the generic resolve list.
5858        if (specifics != null) {
5859            for (int i=0; i<specifics.length; i++) {
5860                final Intent sintent = specifics[i];
5861                if (sintent == null) {
5862                    continue;
5863                }
5864
5865                if (DEBUG_INTENT_MATCHING) {
5866                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5867                }
5868
5869                String action = sintent.getAction();
5870                if (resultsAction != null && resultsAction.equals(action)) {
5871                    // If this action was explicitly requested, then don't
5872                    // remove things that have it.
5873                    action = null;
5874                }
5875
5876                ResolveInfo ri = null;
5877                ActivityInfo ai = null;
5878
5879                ComponentName comp = sintent.getComponent();
5880                if (comp == null) {
5881                    ri = resolveIntent(
5882                        sintent,
5883                        specificTypes != null ? specificTypes[i] : null,
5884                            flags, userId);
5885                    if (ri == null) {
5886                        continue;
5887                    }
5888                    if (ri == mResolveInfo) {
5889                        // ACK!  Must do something better with this.
5890                    }
5891                    ai = ri.activityInfo;
5892                    comp = new ComponentName(ai.applicationInfo.packageName,
5893                            ai.name);
5894                } else {
5895                    ai = getActivityInfo(comp, flags, userId);
5896                    if (ai == null) {
5897                        continue;
5898                    }
5899                }
5900
5901                // Look for any generic query activities that are duplicates
5902                // of this specific one, and remove them from the results.
5903                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5904                N = results.size();
5905                int j;
5906                for (j=specificsPos; j<N; j++) {
5907                    ResolveInfo sri = results.get(j);
5908                    if ((sri.activityInfo.name.equals(comp.getClassName())
5909                            && sri.activityInfo.applicationInfo.packageName.equals(
5910                                    comp.getPackageName()))
5911                        || (action != null && sri.filter.matchAction(action))) {
5912                        results.remove(j);
5913                        if (DEBUG_INTENT_MATCHING) Log.v(
5914                            TAG, "Removing duplicate item from " + j
5915                            + " due to specific " + specificsPos);
5916                        if (ri == null) {
5917                            ri = sri;
5918                        }
5919                        j--;
5920                        N--;
5921                    }
5922                }
5923
5924                // Add this specific item to its proper place.
5925                if (ri == null) {
5926                    ri = new ResolveInfo();
5927                    ri.activityInfo = ai;
5928                }
5929                results.add(specificsPos, ri);
5930                ri.specificIndex = i;
5931                specificsPos++;
5932            }
5933        }
5934
5935        // Now we go through the remaining generic results and remove any
5936        // duplicate actions that are found here.
5937        N = results.size();
5938        for (int i=specificsPos; i<N-1; i++) {
5939            final ResolveInfo rii = results.get(i);
5940            if (rii.filter == null) {
5941                continue;
5942            }
5943
5944            // Iterate over all of the actions of this result's intent
5945            // filter...  typically this should be just one.
5946            final Iterator<String> it = rii.filter.actionsIterator();
5947            if (it == null) {
5948                continue;
5949            }
5950            while (it.hasNext()) {
5951                final String action = it.next();
5952                if (resultsAction != null && resultsAction.equals(action)) {
5953                    // If this action was explicitly requested, then don't
5954                    // remove things that have it.
5955                    continue;
5956                }
5957                for (int j=i+1; j<N; j++) {
5958                    final ResolveInfo rij = results.get(j);
5959                    if (rij.filter != null && rij.filter.hasAction(action)) {
5960                        results.remove(j);
5961                        if (DEBUG_INTENT_MATCHING) Log.v(
5962                            TAG, "Removing duplicate item from " + j
5963                            + " due to action " + action + " at " + i);
5964                        j--;
5965                        N--;
5966                    }
5967                }
5968            }
5969
5970            // If the caller didn't request filter information, drop it now
5971            // so we don't have to marshall/unmarshall it.
5972            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5973                rii.filter = null;
5974            }
5975        }
5976
5977        // Filter out the caller activity if so requested.
5978        if (caller != null) {
5979            N = results.size();
5980            for (int i=0; i<N; i++) {
5981                ActivityInfo ainfo = results.get(i).activityInfo;
5982                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5983                        && caller.getClassName().equals(ainfo.name)) {
5984                    results.remove(i);
5985                    break;
5986                }
5987            }
5988        }
5989
5990        // If the caller didn't request filter information,
5991        // drop them now so we don't have to
5992        // marshall/unmarshall it.
5993        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5994            N = results.size();
5995            for (int i=0; i<N; i++) {
5996                results.get(i).filter = null;
5997            }
5998        }
5999
6000        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6001        return results;
6002    }
6003
6004    @Override
6005    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6006            String resolvedType, int flags, int userId) {
6007        return new ParceledListSlice<>(
6008                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6009    }
6010
6011    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6012            String resolvedType, int flags, int userId) {
6013        if (!sUserManager.exists(userId)) return Collections.emptyList();
6014        flags = updateFlagsForResolve(flags, userId, intent);
6015        ComponentName comp = intent.getComponent();
6016        if (comp == null) {
6017            if (intent.getSelector() != null) {
6018                intent = intent.getSelector();
6019                comp = intent.getComponent();
6020            }
6021        }
6022        if (comp != null) {
6023            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6024            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6025            if (ai != null) {
6026                ResolveInfo ri = new ResolveInfo();
6027                ri.activityInfo = ai;
6028                list.add(ri);
6029            }
6030            return list;
6031        }
6032
6033        // reader
6034        synchronized (mPackages) {
6035            String pkgName = intent.getPackage();
6036            if (pkgName == null) {
6037                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6038            }
6039            final PackageParser.Package pkg = mPackages.get(pkgName);
6040            if (pkg != null) {
6041                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6042                        userId);
6043            }
6044            return Collections.emptyList();
6045        }
6046    }
6047
6048    @Override
6049    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6050        if (!sUserManager.exists(userId)) return null;
6051        flags = updateFlagsForResolve(flags, userId, intent);
6052        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6053        if (query != null) {
6054            if (query.size() >= 1) {
6055                // If there is more than one service with the same priority,
6056                // just arbitrarily pick the first one.
6057                return query.get(0);
6058            }
6059        }
6060        return null;
6061    }
6062
6063    @Override
6064    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6065            String resolvedType, int flags, int userId) {
6066        return new ParceledListSlice<>(
6067                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6068    }
6069
6070    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6071            String resolvedType, int flags, int userId) {
6072        if (!sUserManager.exists(userId)) return Collections.emptyList();
6073        flags = updateFlagsForResolve(flags, userId, intent);
6074        ComponentName comp = intent.getComponent();
6075        if (comp == null) {
6076            if (intent.getSelector() != null) {
6077                intent = intent.getSelector();
6078                comp = intent.getComponent();
6079            }
6080        }
6081        if (comp != null) {
6082            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6083            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6084            if (si != null) {
6085                final ResolveInfo ri = new ResolveInfo();
6086                ri.serviceInfo = si;
6087                list.add(ri);
6088            }
6089            return list;
6090        }
6091
6092        // reader
6093        synchronized (mPackages) {
6094            String pkgName = intent.getPackage();
6095            if (pkgName == null) {
6096                return mServices.queryIntent(intent, resolvedType, flags, userId);
6097            }
6098            final PackageParser.Package pkg = mPackages.get(pkgName);
6099            if (pkg != null) {
6100                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6101                        userId);
6102            }
6103            return Collections.emptyList();
6104        }
6105    }
6106
6107    @Override
6108    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6109            String resolvedType, int flags, int userId) {
6110        return new ParceledListSlice<>(
6111                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6112    }
6113
6114    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6115            Intent intent, String resolvedType, int flags, int userId) {
6116        if (!sUserManager.exists(userId)) return Collections.emptyList();
6117        flags = updateFlagsForResolve(flags, userId, intent);
6118        ComponentName comp = intent.getComponent();
6119        if (comp == null) {
6120            if (intent.getSelector() != null) {
6121                intent = intent.getSelector();
6122                comp = intent.getComponent();
6123            }
6124        }
6125        if (comp != null) {
6126            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6127            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6128            if (pi != null) {
6129                final ResolveInfo ri = new ResolveInfo();
6130                ri.providerInfo = pi;
6131                list.add(ri);
6132            }
6133            return list;
6134        }
6135
6136        // reader
6137        synchronized (mPackages) {
6138            String pkgName = intent.getPackage();
6139            if (pkgName == null) {
6140                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6141            }
6142            final PackageParser.Package pkg = mPackages.get(pkgName);
6143            if (pkg != null) {
6144                return mProviders.queryIntentForPackage(
6145                        intent, resolvedType, flags, pkg.providers, userId);
6146            }
6147            return Collections.emptyList();
6148        }
6149    }
6150
6151    @Override
6152    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6153        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6154        flags = updateFlagsForPackage(flags, userId, null);
6155        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6157                true /* requireFullPermission */, false /* checkShell */,
6158                "get installed packages");
6159
6160        // writer
6161        synchronized (mPackages) {
6162            ArrayList<PackageInfo> list;
6163            if (listUninstalled) {
6164                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6165                for (PackageSetting ps : mSettings.mPackages.values()) {
6166                    final PackageInfo pi;
6167                    if (ps.pkg != null) {
6168                        pi = generatePackageInfo(ps, flags, userId);
6169                    } else {
6170                        pi = generatePackageInfo(ps, flags, userId);
6171                    }
6172                    if (pi != null) {
6173                        list.add(pi);
6174                    }
6175                }
6176            } else {
6177                list = new ArrayList<PackageInfo>(mPackages.size());
6178                for (PackageParser.Package p : mPackages.values()) {
6179                    final PackageInfo pi =
6180                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6181                    if (pi != null) {
6182                        list.add(pi);
6183                    }
6184                }
6185            }
6186
6187            return new ParceledListSlice<PackageInfo>(list);
6188        }
6189    }
6190
6191    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6192            String[] permissions, boolean[] tmp, int flags, int userId) {
6193        int numMatch = 0;
6194        final PermissionsState permissionsState = ps.getPermissionsState();
6195        for (int i=0; i<permissions.length; i++) {
6196            final String permission = permissions[i];
6197            if (permissionsState.hasPermission(permission, userId)) {
6198                tmp[i] = true;
6199                numMatch++;
6200            } else {
6201                tmp[i] = false;
6202            }
6203        }
6204        if (numMatch == 0) {
6205            return;
6206        }
6207        final PackageInfo pi;
6208        if (ps.pkg != null) {
6209            pi = generatePackageInfo(ps, flags, userId);
6210        } else {
6211            pi = generatePackageInfo(ps, flags, userId);
6212        }
6213        // The above might return null in cases of uninstalled apps or install-state
6214        // skew across users/profiles.
6215        if (pi != null) {
6216            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6217                if (numMatch == permissions.length) {
6218                    pi.requestedPermissions = permissions;
6219                } else {
6220                    pi.requestedPermissions = new String[numMatch];
6221                    numMatch = 0;
6222                    for (int i=0; i<permissions.length; i++) {
6223                        if (tmp[i]) {
6224                            pi.requestedPermissions[numMatch] = permissions[i];
6225                            numMatch++;
6226                        }
6227                    }
6228                }
6229            }
6230            list.add(pi);
6231        }
6232    }
6233
6234    @Override
6235    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6236            String[] permissions, int flags, int userId) {
6237        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6238        flags = updateFlagsForPackage(flags, userId, permissions);
6239        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6240
6241        // writer
6242        synchronized (mPackages) {
6243            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6244            boolean[] tmpBools = new boolean[permissions.length];
6245            if (listUninstalled) {
6246                for (PackageSetting ps : mSettings.mPackages.values()) {
6247                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6248                }
6249            } else {
6250                for (PackageParser.Package pkg : mPackages.values()) {
6251                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6252                    if (ps != null) {
6253                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6254                                userId);
6255                    }
6256                }
6257            }
6258
6259            return new ParceledListSlice<PackageInfo>(list);
6260        }
6261    }
6262
6263    @Override
6264    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6265        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6266        flags = updateFlagsForApplication(flags, userId, null);
6267        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6268
6269        // writer
6270        synchronized (mPackages) {
6271            ArrayList<ApplicationInfo> list;
6272            if (listUninstalled) {
6273                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6274                for (PackageSetting ps : mSettings.mPackages.values()) {
6275                    ApplicationInfo ai;
6276                    if (ps.pkg != null) {
6277                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6278                                ps.readUserState(userId), userId);
6279                    } else {
6280                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6281                    }
6282                    if (ai != null) {
6283                        list.add(ai);
6284                    }
6285                }
6286            } else {
6287                list = new ArrayList<ApplicationInfo>(mPackages.size());
6288                for (PackageParser.Package p : mPackages.values()) {
6289                    if (p.mExtras != null) {
6290                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6291                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6292                        if (ai != null) {
6293                            list.add(ai);
6294                        }
6295                    }
6296                }
6297            }
6298
6299            return new ParceledListSlice<ApplicationInfo>(list);
6300        }
6301    }
6302
6303    @Override
6304    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6306            return null;
6307        }
6308
6309        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6310                "getEphemeralApplications");
6311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6312                true /* requireFullPermission */, false /* checkShell */,
6313                "getEphemeralApplications");
6314        synchronized (mPackages) {
6315            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6316                    .getEphemeralApplicationsLPw(userId);
6317            if (ephemeralApps != null) {
6318                return new ParceledListSlice<>(ephemeralApps);
6319            }
6320        }
6321        return null;
6322    }
6323
6324    @Override
6325    public boolean isEphemeralApplication(String packageName, int userId) {
6326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6327                true /* requireFullPermission */, false /* checkShell */,
6328                "isEphemeral");
6329        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6330            return false;
6331        }
6332
6333        if (!isCallerSameApp(packageName)) {
6334            return false;
6335        }
6336        synchronized (mPackages) {
6337            PackageParser.Package pkg = mPackages.get(packageName);
6338            if (pkg != null) {
6339                return pkg.applicationInfo.isEphemeralApp();
6340            }
6341        }
6342        return false;
6343    }
6344
6345    @Override
6346    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6347        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6348            return null;
6349        }
6350
6351        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6352                true /* requireFullPermission */, false /* checkShell */,
6353                "getCookie");
6354        if (!isCallerSameApp(packageName)) {
6355            return null;
6356        }
6357        synchronized (mPackages) {
6358            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6359                    packageName, userId);
6360        }
6361    }
6362
6363    @Override
6364    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6365        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6366            return true;
6367        }
6368
6369        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6370                true /* requireFullPermission */, true /* checkShell */,
6371                "setCookie");
6372        if (!isCallerSameApp(packageName)) {
6373            return false;
6374        }
6375        synchronized (mPackages) {
6376            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6377                    packageName, cookie, userId);
6378        }
6379    }
6380
6381    @Override
6382    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6383        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6384            return null;
6385        }
6386
6387        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6388                "getEphemeralApplicationIcon");
6389        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6390                true /* requireFullPermission */, false /* checkShell */,
6391                "getEphemeralApplicationIcon");
6392        synchronized (mPackages) {
6393            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6394                    packageName, userId);
6395        }
6396    }
6397
6398    private boolean isCallerSameApp(String packageName) {
6399        PackageParser.Package pkg = mPackages.get(packageName);
6400        return pkg != null
6401                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6402    }
6403
6404    @Override
6405    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6406        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6407    }
6408
6409    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6410        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6411
6412        // reader
6413        synchronized (mPackages) {
6414            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6415            final int userId = UserHandle.getCallingUserId();
6416            while (i.hasNext()) {
6417                final PackageParser.Package p = i.next();
6418                if (p.applicationInfo == null) continue;
6419
6420                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6421                        && !p.applicationInfo.isDirectBootAware();
6422                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6423                        && p.applicationInfo.isDirectBootAware();
6424
6425                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6426                        && (!mSafeMode || isSystemApp(p))
6427                        && (matchesUnaware || matchesAware)) {
6428                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6429                    if (ps != null) {
6430                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6431                                ps.readUserState(userId), userId);
6432                        if (ai != null) {
6433                            finalList.add(ai);
6434                        }
6435                    }
6436                }
6437            }
6438        }
6439
6440        return finalList;
6441    }
6442
6443    @Override
6444    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6445        if (!sUserManager.exists(userId)) return null;
6446        flags = updateFlagsForComponent(flags, userId, name);
6447        // reader
6448        synchronized (mPackages) {
6449            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6450            PackageSetting ps = provider != null
6451                    ? mSettings.mPackages.get(provider.owner.packageName)
6452                    : null;
6453            return ps != null
6454                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6455                    ? PackageParser.generateProviderInfo(provider, flags,
6456                            ps.readUserState(userId), userId)
6457                    : null;
6458        }
6459    }
6460
6461    /**
6462     * @deprecated
6463     */
6464    @Deprecated
6465    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6466        // reader
6467        synchronized (mPackages) {
6468            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6469                    .entrySet().iterator();
6470            final int userId = UserHandle.getCallingUserId();
6471            while (i.hasNext()) {
6472                Map.Entry<String, PackageParser.Provider> entry = i.next();
6473                PackageParser.Provider p = entry.getValue();
6474                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6475
6476                if (ps != null && p.syncable
6477                        && (!mSafeMode || (p.info.applicationInfo.flags
6478                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6479                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6480                            ps.readUserState(userId), userId);
6481                    if (info != null) {
6482                        outNames.add(entry.getKey());
6483                        outInfo.add(info);
6484                    }
6485                }
6486            }
6487        }
6488    }
6489
6490    @Override
6491    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6492            int uid, int flags) {
6493        final int userId = processName != null ? UserHandle.getUserId(uid)
6494                : UserHandle.getCallingUserId();
6495        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6496        flags = updateFlagsForComponent(flags, userId, processName);
6497
6498        ArrayList<ProviderInfo> finalList = null;
6499        // reader
6500        synchronized (mPackages) {
6501            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6502            while (i.hasNext()) {
6503                final PackageParser.Provider p = i.next();
6504                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6505                if (ps != null && p.info.authority != null
6506                        && (processName == null
6507                                || (p.info.processName.equals(processName)
6508                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6509                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6510                    if (finalList == null) {
6511                        finalList = new ArrayList<ProviderInfo>(3);
6512                    }
6513                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6514                            ps.readUserState(userId), userId);
6515                    if (info != null) {
6516                        finalList.add(info);
6517                    }
6518                }
6519            }
6520        }
6521
6522        if (finalList != null) {
6523            Collections.sort(finalList, mProviderInitOrderSorter);
6524            return new ParceledListSlice<ProviderInfo>(finalList);
6525        }
6526
6527        return ParceledListSlice.emptyList();
6528    }
6529
6530    @Override
6531    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6532        // reader
6533        synchronized (mPackages) {
6534            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6535            return PackageParser.generateInstrumentationInfo(i, flags);
6536        }
6537    }
6538
6539    @Override
6540    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6541            String targetPackage, int flags) {
6542        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6543    }
6544
6545    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6546            int flags) {
6547        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6548
6549        // reader
6550        synchronized (mPackages) {
6551            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6552            while (i.hasNext()) {
6553                final PackageParser.Instrumentation p = i.next();
6554                if (targetPackage == null
6555                        || targetPackage.equals(p.info.targetPackage)) {
6556                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6557                            flags);
6558                    if (ii != null) {
6559                        finalList.add(ii);
6560                    }
6561                }
6562            }
6563        }
6564
6565        return finalList;
6566    }
6567
6568    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6569        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6570        if (overlays == null) {
6571            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6572            return;
6573        }
6574        for (PackageParser.Package opkg : overlays.values()) {
6575            // Not much to do if idmap fails: we already logged the error
6576            // and we certainly don't want to abort installation of pkg simply
6577            // because an overlay didn't fit properly. For these reasons,
6578            // ignore the return value of createIdmapForPackagePairLI.
6579            createIdmapForPackagePairLI(pkg, opkg);
6580        }
6581    }
6582
6583    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6584            PackageParser.Package opkg) {
6585        if (!opkg.mTrustedOverlay) {
6586            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6587                    opkg.baseCodePath + ": overlay not trusted");
6588            return false;
6589        }
6590        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6591        if (overlaySet == null) {
6592            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6593                    opkg.baseCodePath + " but target package has no known overlays");
6594            return false;
6595        }
6596        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6597        // TODO: generate idmap for split APKs
6598        try {
6599            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6600        } catch (InstallerException e) {
6601            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6602                    + opkg.baseCodePath);
6603            return false;
6604        }
6605        PackageParser.Package[] overlayArray =
6606            overlaySet.values().toArray(new PackageParser.Package[0]);
6607        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6608            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6609                return p1.mOverlayPriority - p2.mOverlayPriority;
6610            }
6611        };
6612        Arrays.sort(overlayArray, cmp);
6613
6614        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6615        int i = 0;
6616        for (PackageParser.Package p : overlayArray) {
6617            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6618        }
6619        return true;
6620    }
6621
6622    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6623        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6624        try {
6625            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6626        } finally {
6627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6628        }
6629    }
6630
6631    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6632        final File[] files = dir.listFiles();
6633        if (ArrayUtils.isEmpty(files)) {
6634            Log.d(TAG, "No files in app dir " + dir);
6635            return;
6636        }
6637
6638        if (DEBUG_PACKAGE_SCANNING) {
6639            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6640                    + " flags=0x" + Integer.toHexString(parseFlags));
6641        }
6642
6643        for (File file : files) {
6644            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6645                    && !PackageInstallerService.isStageName(file.getName());
6646            if (!isPackage) {
6647                // Ignore entries which are not packages
6648                continue;
6649            }
6650            try {
6651                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6652                        scanFlags, currentTime, null);
6653            } catch (PackageManagerException e) {
6654                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6655
6656                // Delete invalid userdata apps
6657                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6658                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6659                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6660                    removeCodePathLI(file);
6661                }
6662            }
6663        }
6664    }
6665
6666    private static File getSettingsProblemFile() {
6667        File dataDir = Environment.getDataDirectory();
6668        File systemDir = new File(dataDir, "system");
6669        File fname = new File(systemDir, "uiderrors.txt");
6670        return fname;
6671    }
6672
6673    static void reportSettingsProblem(int priority, String msg) {
6674        logCriticalInfo(priority, msg);
6675    }
6676
6677    static void logCriticalInfo(int priority, String msg) {
6678        Slog.println(priority, TAG, msg);
6679        EventLogTags.writePmCriticalInfo(msg);
6680        try {
6681            File fname = getSettingsProblemFile();
6682            FileOutputStream out = new FileOutputStream(fname, true);
6683            PrintWriter pw = new FastPrintWriter(out);
6684            SimpleDateFormat formatter = new SimpleDateFormat();
6685            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6686            pw.println(dateString + ": " + msg);
6687            pw.close();
6688            FileUtils.setPermissions(
6689                    fname.toString(),
6690                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6691                    -1, -1);
6692        } catch (java.io.IOException e) {
6693        }
6694    }
6695
6696    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6697        if (srcFile.isDirectory()) {
6698            final File baseFile = new File(pkg.baseCodePath);
6699            long maxModifiedTime = baseFile.lastModified();
6700            if (pkg.splitCodePaths != null) {
6701                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6702                    final File splitFile = new File(pkg.splitCodePaths[i]);
6703                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6704                }
6705            }
6706            return maxModifiedTime;
6707        }
6708        return srcFile.lastModified();
6709    }
6710
6711    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6712            final int policyFlags) throws PackageManagerException {
6713        // When upgrading from pre-N MR1, verify the package time stamp using the package
6714        // directory and not the APK file.
6715        final long lastModifiedTime = mIsPreNMR1Upgrade
6716                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6717        if (ps != null
6718                && ps.codePath.equals(srcFile)
6719                && ps.timeStamp == lastModifiedTime
6720                && !isCompatSignatureUpdateNeeded(pkg)
6721                && !isRecoverSignatureUpdateNeeded(pkg)) {
6722            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6723            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6724            ArraySet<PublicKey> signingKs;
6725            synchronized (mPackages) {
6726                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6727            }
6728            if (ps.signatures.mSignatures != null
6729                    && ps.signatures.mSignatures.length != 0
6730                    && signingKs != null) {
6731                // Optimization: reuse the existing cached certificates
6732                // if the package appears to be unchanged.
6733                pkg.mSignatures = ps.signatures.mSignatures;
6734                pkg.mSigningKeys = signingKs;
6735                return;
6736            }
6737
6738            Slog.w(TAG, "PackageSetting for " + ps.name
6739                    + " is missing signatures.  Collecting certs again to recover them.");
6740        } else {
6741            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6742        }
6743
6744        try {
6745            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6746            PackageParser.collectCertificates(pkg, policyFlags);
6747        } catch (PackageParserException e) {
6748            throw PackageManagerException.from(e);
6749        } finally {
6750            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6751        }
6752    }
6753
6754    /**
6755     *  Traces a package scan.
6756     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6757     */
6758    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6759            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6760        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6761        try {
6762            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6763        } finally {
6764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6765        }
6766    }
6767
6768    /**
6769     *  Scans a package and returns the newly parsed package.
6770     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6771     */
6772    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6773            long currentTime, UserHandle user) throws PackageManagerException {
6774        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6775        PackageParser pp = new PackageParser();
6776        pp.setSeparateProcesses(mSeparateProcesses);
6777        pp.setOnlyCoreApps(mOnlyCore);
6778        pp.setDisplayMetrics(mMetrics);
6779
6780        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6781            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6782        }
6783
6784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6785        final PackageParser.Package pkg;
6786        try {
6787            pkg = pp.parsePackage(scanFile, parseFlags);
6788        } catch (PackageParserException e) {
6789            throw PackageManagerException.from(e);
6790        } finally {
6791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6792        }
6793
6794        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6795    }
6796
6797    /**
6798     *  Scans a package and returns the newly parsed package.
6799     *  @throws PackageManagerException on a parse error.
6800     */
6801    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6802            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6803            throws PackageManagerException {
6804        // If the package has children and this is the first dive in the function
6805        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6806        // packages (parent and children) would be successfully scanned before the
6807        // actual scan since scanning mutates internal state and we want to atomically
6808        // install the package and its children.
6809        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6810            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6811                scanFlags |= SCAN_CHECK_ONLY;
6812            }
6813        } else {
6814            scanFlags &= ~SCAN_CHECK_ONLY;
6815        }
6816
6817        // Scan the parent
6818        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6819                scanFlags, currentTime, user);
6820
6821        // Scan the children
6822        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6823        for (int i = 0; i < childCount; i++) {
6824            PackageParser.Package childPackage = pkg.childPackages.get(i);
6825            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6826                    currentTime, user);
6827        }
6828
6829
6830        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6831            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6832        }
6833
6834        return scannedPkg;
6835    }
6836
6837    /**
6838     *  Scans a package and returns the newly parsed package.
6839     *  @throws PackageManagerException on a parse error.
6840     */
6841    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6842            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6843            throws PackageManagerException {
6844        PackageSetting ps = null;
6845        PackageSetting updatedPkg;
6846        // reader
6847        synchronized (mPackages) {
6848            // Look to see if we already know about this package.
6849            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6850            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6851                // This package has been renamed to its original name.  Let's
6852                // use that.
6853                ps = mSettings.peekPackageLPr(oldName);
6854            }
6855            // If there was no original package, see one for the real package name.
6856            if (ps == null) {
6857                ps = mSettings.peekPackageLPr(pkg.packageName);
6858            }
6859            // Check to see if this package could be hiding/updating a system
6860            // package.  Must look for it either under the original or real
6861            // package name depending on our state.
6862            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6863            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6864
6865            // If this is a package we don't know about on the system partition, we
6866            // may need to remove disabled child packages on the system partition
6867            // or may need to not add child packages if the parent apk is updated
6868            // on the data partition and no longer defines this child package.
6869            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6870                // If this is a parent package for an updated system app and this system
6871                // app got an OTA update which no longer defines some of the child packages
6872                // we have to prune them from the disabled system packages.
6873                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6874                if (disabledPs != null) {
6875                    final int scannedChildCount = (pkg.childPackages != null)
6876                            ? pkg.childPackages.size() : 0;
6877                    final int disabledChildCount = disabledPs.childPackageNames != null
6878                            ? disabledPs.childPackageNames.size() : 0;
6879                    for (int i = 0; i < disabledChildCount; i++) {
6880                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6881                        boolean disabledPackageAvailable = false;
6882                        for (int j = 0; j < scannedChildCount; j++) {
6883                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6884                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6885                                disabledPackageAvailable = true;
6886                                break;
6887                            }
6888                         }
6889                         if (!disabledPackageAvailable) {
6890                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6891                         }
6892                    }
6893                }
6894            }
6895        }
6896
6897        boolean updatedPkgBetter = false;
6898        // First check if this is a system package that may involve an update
6899        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6900            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6901            // it needs to drop FLAG_PRIVILEGED.
6902            if (locationIsPrivileged(scanFile)) {
6903                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6904            } else {
6905                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6906            }
6907
6908            if (ps != null && !ps.codePath.equals(scanFile)) {
6909                // The path has changed from what was last scanned...  check the
6910                // version of the new path against what we have stored to determine
6911                // what to do.
6912                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6913                if (pkg.mVersionCode <= ps.versionCode) {
6914                    // The system package has been updated and the code path does not match
6915                    // Ignore entry. Skip it.
6916                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6917                            + " ignored: updated version " + ps.versionCode
6918                            + " better than this " + pkg.mVersionCode);
6919                    if (!updatedPkg.codePath.equals(scanFile)) {
6920                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6921                                + ps.name + " changing from " + updatedPkg.codePathString
6922                                + " to " + scanFile);
6923                        updatedPkg.codePath = scanFile;
6924                        updatedPkg.codePathString = scanFile.toString();
6925                        updatedPkg.resourcePath = scanFile;
6926                        updatedPkg.resourcePathString = scanFile.toString();
6927                    }
6928                    updatedPkg.pkg = pkg;
6929                    updatedPkg.versionCode = pkg.mVersionCode;
6930
6931                    // Update the disabled system child packages to point to the package too.
6932                    final int childCount = updatedPkg.childPackageNames != null
6933                            ? updatedPkg.childPackageNames.size() : 0;
6934                    for (int i = 0; i < childCount; i++) {
6935                        String childPackageName = updatedPkg.childPackageNames.get(i);
6936                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6937                                childPackageName);
6938                        if (updatedChildPkg != null) {
6939                            updatedChildPkg.pkg = pkg;
6940                            updatedChildPkg.versionCode = pkg.mVersionCode;
6941                        }
6942                    }
6943
6944                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6945                            + scanFile + " ignored: updated version " + ps.versionCode
6946                            + " better than this " + pkg.mVersionCode);
6947                } else {
6948                    // The current app on the system partition is better than
6949                    // what we have updated to on the data partition; switch
6950                    // back to the system partition version.
6951                    // At this point, its safely assumed that package installation for
6952                    // apps in system partition will go through. If not there won't be a working
6953                    // version of the app
6954                    // writer
6955                    synchronized (mPackages) {
6956                        // Just remove the loaded entries from package lists.
6957                        mPackages.remove(ps.name);
6958                    }
6959
6960                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6961                            + " reverting from " + ps.codePathString
6962                            + ": new version " + pkg.mVersionCode
6963                            + " better than installed " + ps.versionCode);
6964
6965                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6966                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6967                    synchronized (mInstallLock) {
6968                        args.cleanUpResourcesLI();
6969                    }
6970                    synchronized (mPackages) {
6971                        mSettings.enableSystemPackageLPw(ps.name);
6972                    }
6973                    updatedPkgBetter = true;
6974                }
6975            }
6976        }
6977
6978        if (updatedPkg != null) {
6979            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6980            // initially
6981            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6982
6983            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6984            // flag set initially
6985            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6986                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6987            }
6988        }
6989
6990        // Verify certificates against what was last scanned
6991        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6992
6993        /*
6994         * A new system app appeared, but we already had a non-system one of the
6995         * same name installed earlier.
6996         */
6997        boolean shouldHideSystemApp = false;
6998        if (updatedPkg == null && ps != null
6999                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7000            /*
7001             * Check to make sure the signatures match first. If they don't,
7002             * wipe the installed application and its data.
7003             */
7004            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7005                    != PackageManager.SIGNATURE_MATCH) {
7006                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7007                        + " signatures don't match existing userdata copy; removing");
7008                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7009                        "scanPackageInternalLI")) {
7010                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7011                }
7012                ps = null;
7013            } else {
7014                /*
7015                 * If the newly-added system app is an older version than the
7016                 * already installed version, hide it. It will be scanned later
7017                 * and re-added like an update.
7018                 */
7019                if (pkg.mVersionCode <= ps.versionCode) {
7020                    shouldHideSystemApp = true;
7021                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7022                            + " but new version " + pkg.mVersionCode + " better than installed "
7023                            + ps.versionCode + "; hiding system");
7024                } else {
7025                    /*
7026                     * The newly found system app is a newer version that the
7027                     * one previously installed. Simply remove the
7028                     * already-installed application and replace it with our own
7029                     * while keeping the application data.
7030                     */
7031                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7032                            + " reverting from " + ps.codePathString + ": new version "
7033                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7034                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7035                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7036                    synchronized (mInstallLock) {
7037                        args.cleanUpResourcesLI();
7038                    }
7039                }
7040            }
7041        }
7042
7043        // The apk is forward locked (not public) if its code and resources
7044        // are kept in different files. (except for app in either system or
7045        // vendor path).
7046        // TODO grab this value from PackageSettings
7047        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7048            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7049                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7050            }
7051        }
7052
7053        // TODO: extend to support forward-locked splits
7054        String resourcePath = null;
7055        String baseResourcePath = null;
7056        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7057            if (ps != null && ps.resourcePathString != null) {
7058                resourcePath = ps.resourcePathString;
7059                baseResourcePath = ps.resourcePathString;
7060            } else {
7061                // Should not happen at all. Just log an error.
7062                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7063            }
7064        } else {
7065            resourcePath = pkg.codePath;
7066            baseResourcePath = pkg.baseCodePath;
7067        }
7068
7069        // Set application objects path explicitly.
7070        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7071        pkg.setApplicationInfoCodePath(pkg.codePath);
7072        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7073        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7074        pkg.setApplicationInfoResourcePath(resourcePath);
7075        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7076        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7077
7078        // Note that we invoke the following method only if we are about to unpack an application
7079        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7080                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7081
7082        /*
7083         * If the system app should be overridden by a previously installed
7084         * data, hide the system app now and let the /data/app scan pick it up
7085         * again.
7086         */
7087        if (shouldHideSystemApp) {
7088            synchronized (mPackages) {
7089                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7090            }
7091        }
7092
7093        return scannedPkg;
7094    }
7095
7096    private static String fixProcessName(String defProcessName,
7097            String processName, int uid) {
7098        if (processName == null) {
7099            return defProcessName;
7100        }
7101        return processName;
7102    }
7103
7104    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7105            throws PackageManagerException {
7106        if (pkgSetting.signatures.mSignatures != null) {
7107            // Already existing package. Make sure signatures match
7108            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7109                    == PackageManager.SIGNATURE_MATCH;
7110            if (!match) {
7111                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7112                        == PackageManager.SIGNATURE_MATCH;
7113            }
7114            if (!match) {
7115                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7116                        == PackageManager.SIGNATURE_MATCH;
7117            }
7118            if (!match) {
7119                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7120                        + pkg.packageName + " signatures do not match the "
7121                        + "previously installed version; ignoring!");
7122            }
7123        }
7124
7125        // Check for shared user signatures
7126        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7127            // Already existing package. Make sure signatures match
7128            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7129                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7130            if (!match) {
7131                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7132                        == PackageManager.SIGNATURE_MATCH;
7133            }
7134            if (!match) {
7135                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7136                        == PackageManager.SIGNATURE_MATCH;
7137            }
7138            if (!match) {
7139                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7140                        "Package " + pkg.packageName
7141                        + " has no signatures that match those in shared user "
7142                        + pkgSetting.sharedUser.name + "; ignoring!");
7143            }
7144        }
7145    }
7146
7147    /**
7148     * Enforces that only the system UID or root's UID can call a method exposed
7149     * via Binder.
7150     *
7151     * @param message used as message if SecurityException is thrown
7152     * @throws SecurityException if the caller is not system or root
7153     */
7154    private static final void enforceSystemOrRoot(String message) {
7155        final int uid = Binder.getCallingUid();
7156        if (uid != Process.SYSTEM_UID && uid != 0) {
7157            throw new SecurityException(message);
7158        }
7159    }
7160
7161    @Override
7162    public void performFstrimIfNeeded() {
7163        enforceSystemOrRoot("Only the system can request fstrim");
7164
7165        // Before everything else, see whether we need to fstrim.
7166        try {
7167            IMountService ms = PackageHelper.getMountService();
7168            if (ms != null) {
7169                boolean doTrim = false;
7170                final long interval = android.provider.Settings.Global.getLong(
7171                        mContext.getContentResolver(),
7172                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7173                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7174                if (interval > 0) {
7175                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7176                    if (timeSinceLast > interval) {
7177                        doTrim = true;
7178                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7179                                + "; running immediately");
7180                    }
7181                }
7182                if (doTrim) {
7183                    final boolean dexOptDialogShown;
7184                    synchronized (mPackages) {
7185                        dexOptDialogShown = mDexOptDialogShown;
7186                    }
7187                    if (!isFirstBoot() && dexOptDialogShown) {
7188                        try {
7189                            ActivityManagerNative.getDefault().showBootMessage(
7190                                    mContext.getResources().getString(
7191                                            R.string.android_upgrading_fstrim), true);
7192                        } catch (RemoteException e) {
7193                        }
7194                    }
7195                    ms.runMaintenance();
7196                }
7197            } else {
7198                Slog.e(TAG, "Mount service unavailable!");
7199            }
7200        } catch (RemoteException e) {
7201            // Can't happen; MountService is local
7202        }
7203    }
7204
7205    @Override
7206    public void updatePackagesIfNeeded() {
7207        enforceSystemOrRoot("Only the system can request package update");
7208
7209        // We need to re-extract after an OTA.
7210        boolean causeUpgrade = isUpgrade();
7211
7212        // First boot or factory reset.
7213        // Note: we also handle devices that are upgrading to N right now as if it is their
7214        //       first boot, as they do not have profile data.
7215        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7216
7217        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7218        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7219
7220        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7221            return;
7222        }
7223
7224        List<PackageParser.Package> pkgs;
7225        synchronized (mPackages) {
7226            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7227        }
7228
7229        final long startTime = System.nanoTime();
7230        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7231                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7232
7233        final int elapsedTimeSeconds =
7234                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7235
7236        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7237        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7238        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7239        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7240        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7241    }
7242
7243    /**
7244     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7245     * containing statistics about the invocation. The array consists of three elements,
7246     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7247     * and {@code numberOfPackagesFailed}.
7248     */
7249    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7250            String compilerFilter) {
7251
7252        int numberOfPackagesVisited = 0;
7253        int numberOfPackagesOptimized = 0;
7254        int numberOfPackagesSkipped = 0;
7255        int numberOfPackagesFailed = 0;
7256        final int numberOfPackagesToDexopt = pkgs.size();
7257
7258        for (PackageParser.Package pkg : pkgs) {
7259            numberOfPackagesVisited++;
7260
7261            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7262                if (DEBUG_DEXOPT) {
7263                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7264                }
7265                numberOfPackagesSkipped++;
7266                continue;
7267            }
7268
7269            if (DEBUG_DEXOPT) {
7270                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7271                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7272            }
7273
7274            if (showDialog) {
7275                try {
7276                    ActivityManagerNative.getDefault().showBootMessage(
7277                            mContext.getResources().getString(R.string.android_upgrading_apk,
7278                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7279                } catch (RemoteException e) {
7280                }
7281                synchronized (mPackages) {
7282                    mDexOptDialogShown = true;
7283                }
7284            }
7285
7286            // If the OTA updates a system app which was previously preopted to a non-preopted state
7287            // the app might end up being verified at runtime. That's because by default the apps
7288            // are verify-profile but for preopted apps there's no profile.
7289            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7290            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7291            // filter (by default interpret-only).
7292            // Note that at this stage unused apps are already filtered.
7293            if (isSystemApp(pkg) &&
7294                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7295                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7296                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7297            }
7298
7299            // If the OTA updates a system app which was previously preopted to a non-preopted state
7300            // the app might end up being verified at runtime. That's because by default the apps
7301            // are verify-profile but for preopted apps there's no profile.
7302            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7303            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7304            // filter (by default interpret-only).
7305            // Note that at this stage unused apps are already filtered.
7306            if (isSystemApp(pkg) &&
7307                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7308                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7309                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7310            }
7311
7312            // checkProfiles is false to avoid merging profiles during boot which
7313            // might interfere with background compilation (b/28612421).
7314            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7315            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7316            // trade-off worth doing to save boot time work.
7317            int dexOptStatus = performDexOptTraced(pkg.packageName,
7318                    false /* checkProfiles */,
7319                    compilerFilter,
7320                    false /* force */);
7321            switch (dexOptStatus) {
7322                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7323                    numberOfPackagesOptimized++;
7324                    break;
7325                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7326                    numberOfPackagesSkipped++;
7327                    break;
7328                case PackageDexOptimizer.DEX_OPT_FAILED:
7329                    numberOfPackagesFailed++;
7330                    break;
7331                default:
7332                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7333                    break;
7334            }
7335        }
7336
7337        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7338                numberOfPackagesFailed };
7339    }
7340
7341    @Override
7342    public void notifyPackageUse(String packageName, int reason) {
7343        synchronized (mPackages) {
7344            PackageParser.Package p = mPackages.get(packageName);
7345            if (p == null) {
7346                return;
7347            }
7348            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7349        }
7350    }
7351
7352    // TODO: this is not used nor needed. Delete it.
7353    @Override
7354    public boolean performDexOptIfNeeded(String packageName) {
7355        int dexOptStatus = performDexOptTraced(packageName,
7356                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7357        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7358    }
7359
7360    @Override
7361    public boolean performDexOpt(String packageName,
7362            boolean checkProfiles, int compileReason, boolean force) {
7363        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7364                getCompilerFilterForReason(compileReason), force);
7365        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7366    }
7367
7368    @Override
7369    public boolean performDexOptMode(String packageName,
7370            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7371        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7372                targetCompilerFilter, force);
7373        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7374    }
7375
7376    private int performDexOptTraced(String packageName,
7377                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7378        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7379        try {
7380            return performDexOptInternal(packageName, checkProfiles,
7381                    targetCompilerFilter, force);
7382        } finally {
7383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7384        }
7385    }
7386
7387    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7388    // if the package can now be considered up to date for the given filter.
7389    private int performDexOptInternal(String packageName,
7390                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7391        PackageParser.Package p;
7392        synchronized (mPackages) {
7393            p = mPackages.get(packageName);
7394            if (p == null) {
7395                // Package could not be found. Report failure.
7396                return PackageDexOptimizer.DEX_OPT_FAILED;
7397            }
7398            mPackageUsage.maybeWriteAsync(mPackages);
7399            mCompilerStats.maybeWriteAsync();
7400        }
7401        long callingId = Binder.clearCallingIdentity();
7402        try {
7403            synchronized (mInstallLock) {
7404                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7405                        targetCompilerFilter, force);
7406            }
7407        } finally {
7408            Binder.restoreCallingIdentity(callingId);
7409        }
7410    }
7411
7412    public ArraySet<String> getOptimizablePackages() {
7413        ArraySet<String> pkgs = new ArraySet<String>();
7414        synchronized (mPackages) {
7415            for (PackageParser.Package p : mPackages.values()) {
7416                if (PackageDexOptimizer.canOptimizePackage(p)) {
7417                    pkgs.add(p.packageName);
7418                }
7419            }
7420        }
7421        return pkgs;
7422    }
7423
7424    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7425            boolean checkProfiles, String targetCompilerFilter,
7426            boolean force) {
7427        // Select the dex optimizer based on the force parameter.
7428        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7429        //       allocate an object here.
7430        PackageDexOptimizer pdo = force
7431                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7432                : mPackageDexOptimizer;
7433
7434        // Optimize all dependencies first. Note: we ignore the return value and march on
7435        // on errors.
7436        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7437        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7438        if (!deps.isEmpty()) {
7439            for (PackageParser.Package depPackage : deps) {
7440                // TODO: Analyze and investigate if we (should) profile libraries.
7441                // Currently this will do a full compilation of the library by default.
7442                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7443                        false /* checkProfiles */,
7444                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7445                        getOrCreateCompilerPackageStats(depPackage));
7446            }
7447        }
7448        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7449                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7450    }
7451
7452    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7453        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7454            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7455            Set<String> collectedNames = new HashSet<>();
7456            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7457
7458            retValue.remove(p);
7459
7460            return retValue;
7461        } else {
7462            return Collections.emptyList();
7463        }
7464    }
7465
7466    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7467            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7468        if (!collectedNames.contains(p.packageName)) {
7469            collectedNames.add(p.packageName);
7470            collected.add(p);
7471
7472            if (p.usesLibraries != null) {
7473                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7474            }
7475            if (p.usesOptionalLibraries != null) {
7476                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7477                        collectedNames);
7478            }
7479        }
7480    }
7481
7482    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7483            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7484        for (String libName : libs) {
7485            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7486            if (libPkg != null) {
7487                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7488            }
7489        }
7490    }
7491
7492    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7493        synchronized (mPackages) {
7494            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7495            if (lib != null && lib.apk != null) {
7496                return mPackages.get(lib.apk);
7497            }
7498        }
7499        return null;
7500    }
7501
7502    public void shutdown() {
7503        mPackageUsage.writeNow(mPackages);
7504        mCompilerStats.writeNow();
7505    }
7506
7507    @Override
7508    public void dumpProfiles(String packageName) {
7509        PackageParser.Package pkg;
7510        synchronized (mPackages) {
7511            pkg = mPackages.get(packageName);
7512            if (pkg == null) {
7513                throw new IllegalArgumentException("Unknown package: " + packageName);
7514            }
7515        }
7516        /* Only the shell, root, or the app user should be able to dump profiles. */
7517        int callingUid = Binder.getCallingUid();
7518        if (callingUid != Process.SHELL_UID &&
7519            callingUid != Process.ROOT_UID &&
7520            callingUid != pkg.applicationInfo.uid) {
7521            throw new SecurityException("dumpProfiles");
7522        }
7523
7524        synchronized (mInstallLock) {
7525            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7526            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7527            try {
7528                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7529                String gid = Integer.toString(sharedGid);
7530                String codePaths = TextUtils.join(";", allCodePaths);
7531                mInstaller.dumpProfiles(gid, packageName, codePaths);
7532            } catch (InstallerException e) {
7533                Slog.w(TAG, "Failed to dump profiles", e);
7534            }
7535            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7536        }
7537    }
7538
7539    @Override
7540    public void forceDexOpt(String packageName) {
7541        enforceSystemOrRoot("forceDexOpt");
7542
7543        PackageParser.Package pkg;
7544        synchronized (mPackages) {
7545            pkg = mPackages.get(packageName);
7546            if (pkg == null) {
7547                throw new IllegalArgumentException("Unknown package: " + packageName);
7548            }
7549        }
7550
7551        synchronized (mInstallLock) {
7552            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7553
7554            // Whoever is calling forceDexOpt wants a fully compiled package.
7555            // Don't use profiles since that may cause compilation to be skipped.
7556            final int res = performDexOptInternalWithDependenciesLI(pkg,
7557                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7558                    true /* force */);
7559
7560            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7561            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7562                throw new IllegalStateException("Failed to dexopt: " + res);
7563            }
7564        }
7565    }
7566
7567    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7568        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7569            Slog.w(TAG, "Unable to update from " + oldPkg.name
7570                    + " to " + newPkg.packageName
7571                    + ": old package not in system partition");
7572            return false;
7573        } else if (mPackages.get(oldPkg.name) != null) {
7574            Slog.w(TAG, "Unable to update from " + oldPkg.name
7575                    + " to " + newPkg.packageName
7576                    + ": old package still exists");
7577            return false;
7578        }
7579        return true;
7580    }
7581
7582    void removeCodePathLI(File codePath) {
7583        if (codePath.isDirectory()) {
7584            try {
7585                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7586            } catch (InstallerException e) {
7587                Slog.w(TAG, "Failed to remove code path", e);
7588            }
7589        } else {
7590            codePath.delete();
7591        }
7592    }
7593
7594    private int[] resolveUserIds(int userId) {
7595        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7596    }
7597
7598    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7599        if (pkg == null) {
7600            Slog.wtf(TAG, "Package was null!", new Throwable());
7601            return;
7602        }
7603        clearAppDataLeafLIF(pkg, userId, flags);
7604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7605        for (int i = 0; i < childCount; i++) {
7606            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7607        }
7608    }
7609
7610    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7611        final PackageSetting ps;
7612        synchronized (mPackages) {
7613            ps = mSettings.mPackages.get(pkg.packageName);
7614        }
7615        for (int realUserId : resolveUserIds(userId)) {
7616            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7617            try {
7618                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7619                        ceDataInode);
7620            } catch (InstallerException e) {
7621                Slog.w(TAG, String.valueOf(e));
7622            }
7623        }
7624    }
7625
7626    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7627        if (pkg == null) {
7628            Slog.wtf(TAG, "Package was null!", new Throwable());
7629            return;
7630        }
7631        destroyAppDataLeafLIF(pkg, userId, flags);
7632        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7633        for (int i = 0; i < childCount; i++) {
7634            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7635        }
7636    }
7637
7638    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7639        final PackageSetting ps;
7640        synchronized (mPackages) {
7641            ps = mSettings.mPackages.get(pkg.packageName);
7642        }
7643        for (int realUserId : resolveUserIds(userId)) {
7644            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7645            try {
7646                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7647                        ceDataInode);
7648            } catch (InstallerException e) {
7649                Slog.w(TAG, String.valueOf(e));
7650            }
7651        }
7652    }
7653
7654    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7655        if (pkg == null) {
7656            Slog.wtf(TAG, "Package was null!", new Throwable());
7657            return;
7658        }
7659        destroyAppProfilesLeafLIF(pkg);
7660        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7661        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7662        for (int i = 0; i < childCount; i++) {
7663            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7664            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7665                    true /* removeBaseMarker */);
7666        }
7667    }
7668
7669    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7670            boolean removeBaseMarker) {
7671        if (pkg.isForwardLocked()) {
7672            return;
7673        }
7674
7675        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7676            try {
7677                path = PackageManagerServiceUtils.realpath(new File(path));
7678            } catch (IOException e) {
7679                // TODO: Should we return early here ?
7680                Slog.w(TAG, "Failed to get canonical path", e);
7681                continue;
7682            }
7683
7684            final String useMarker = path.replace('/', '@');
7685            for (int realUserId : resolveUserIds(userId)) {
7686                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7687                if (removeBaseMarker) {
7688                    File foreignUseMark = new File(profileDir, useMarker);
7689                    if (foreignUseMark.exists()) {
7690                        if (!foreignUseMark.delete()) {
7691                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7692                                    + pkg.packageName);
7693                        }
7694                    }
7695                }
7696
7697                File[] markers = profileDir.listFiles();
7698                if (markers != null) {
7699                    final String searchString = "@" + pkg.packageName + "@";
7700                    // We also delete all markers that contain the package name we're
7701                    // uninstalling. These are associated with secondary dex-files belonging
7702                    // to the package. Reconstructing the path of these dex files is messy
7703                    // in general.
7704                    for (File marker : markers) {
7705                        if (marker.getName().indexOf(searchString) > 0) {
7706                            if (!marker.delete()) {
7707                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7708                                    + pkg.packageName);
7709                            }
7710                        }
7711                    }
7712                }
7713            }
7714        }
7715    }
7716
7717    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7718        try {
7719            mInstaller.destroyAppProfiles(pkg.packageName);
7720        } catch (InstallerException e) {
7721            Slog.w(TAG, String.valueOf(e));
7722        }
7723    }
7724
7725    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7726        if (pkg == null) {
7727            Slog.wtf(TAG, "Package was null!", new Throwable());
7728            return;
7729        }
7730        clearAppProfilesLeafLIF(pkg);
7731        // We don't remove the base foreign use marker when clearing profiles because
7732        // we will rename it when the app is updated. Unlike the actual profile contents,
7733        // the foreign use marker is good across installs.
7734        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7735        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7736        for (int i = 0; i < childCount; i++) {
7737            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7738        }
7739    }
7740
7741    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7742        try {
7743            mInstaller.clearAppProfiles(pkg.packageName);
7744        } catch (InstallerException e) {
7745            Slog.w(TAG, String.valueOf(e));
7746        }
7747    }
7748
7749    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7750            long lastUpdateTime) {
7751        // Set parent install/update time
7752        PackageSetting ps = (PackageSetting) pkg.mExtras;
7753        if (ps != null) {
7754            ps.firstInstallTime = firstInstallTime;
7755            ps.lastUpdateTime = lastUpdateTime;
7756        }
7757        // Set children install/update time
7758        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7759        for (int i = 0; i < childCount; i++) {
7760            PackageParser.Package childPkg = pkg.childPackages.get(i);
7761            ps = (PackageSetting) childPkg.mExtras;
7762            if (ps != null) {
7763                ps.firstInstallTime = firstInstallTime;
7764                ps.lastUpdateTime = lastUpdateTime;
7765            }
7766        }
7767    }
7768
7769    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7770            PackageParser.Package changingLib) {
7771        if (file.path != null) {
7772            usesLibraryFiles.add(file.path);
7773            return;
7774        }
7775        PackageParser.Package p = mPackages.get(file.apk);
7776        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7777            // If we are doing this while in the middle of updating a library apk,
7778            // then we need to make sure to use that new apk for determining the
7779            // dependencies here.  (We haven't yet finished committing the new apk
7780            // to the package manager state.)
7781            if (p == null || p.packageName.equals(changingLib.packageName)) {
7782                p = changingLib;
7783            }
7784        }
7785        if (p != null) {
7786            usesLibraryFiles.addAll(p.getAllCodePaths());
7787        }
7788    }
7789
7790    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7791            PackageParser.Package changingLib) throws PackageManagerException {
7792        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7793            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7794            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7795            for (int i=0; i<N; i++) {
7796                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7797                if (file == null) {
7798                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7799                            "Package " + pkg.packageName + " requires unavailable shared library "
7800                            + pkg.usesLibraries.get(i) + "; failing!");
7801                }
7802                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7803            }
7804            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7805            for (int i=0; i<N; i++) {
7806                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7807                if (file == null) {
7808                    Slog.w(TAG, "Package " + pkg.packageName
7809                            + " desires unavailable shared library "
7810                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7811                } else {
7812                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7813                }
7814            }
7815            N = usesLibraryFiles.size();
7816            if (N > 0) {
7817                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7818            } else {
7819                pkg.usesLibraryFiles = null;
7820            }
7821        }
7822    }
7823
7824    private static boolean hasString(List<String> list, List<String> which) {
7825        if (list == null) {
7826            return false;
7827        }
7828        for (int i=list.size()-1; i>=0; i--) {
7829            for (int j=which.size()-1; j>=0; j--) {
7830                if (which.get(j).equals(list.get(i))) {
7831                    return true;
7832                }
7833            }
7834        }
7835        return false;
7836    }
7837
7838    private void updateAllSharedLibrariesLPw() {
7839        for (PackageParser.Package pkg : mPackages.values()) {
7840            try {
7841                updateSharedLibrariesLPw(pkg, null);
7842            } catch (PackageManagerException e) {
7843                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7844            }
7845        }
7846    }
7847
7848    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7849            PackageParser.Package changingPkg) {
7850        ArrayList<PackageParser.Package> res = null;
7851        for (PackageParser.Package pkg : mPackages.values()) {
7852            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7853                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7854                if (res == null) {
7855                    res = new ArrayList<PackageParser.Package>();
7856                }
7857                res.add(pkg);
7858                try {
7859                    updateSharedLibrariesLPw(pkg, changingPkg);
7860                } catch (PackageManagerException e) {
7861                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7862                }
7863            }
7864        }
7865        return res;
7866    }
7867
7868    /**
7869     * Derive the value of the {@code cpuAbiOverride} based on the provided
7870     * value and an optional stored value from the package settings.
7871     */
7872    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7873        String cpuAbiOverride = null;
7874
7875        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7876            cpuAbiOverride = null;
7877        } else if (abiOverride != null) {
7878            cpuAbiOverride = abiOverride;
7879        } else if (settings != null) {
7880            cpuAbiOverride = settings.cpuAbiOverrideString;
7881        }
7882
7883        return cpuAbiOverride;
7884    }
7885
7886    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7887            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7888                    throws PackageManagerException {
7889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7890        // If the package has children and this is the first dive in the function
7891        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7892        // whether all packages (parent and children) would be successfully scanned
7893        // before the actual scan since scanning mutates internal state and we want
7894        // to atomically install the package and its children.
7895        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7896            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7897                scanFlags |= SCAN_CHECK_ONLY;
7898            }
7899        } else {
7900            scanFlags &= ~SCAN_CHECK_ONLY;
7901        }
7902
7903        final PackageParser.Package scannedPkg;
7904        try {
7905            // Scan the parent
7906            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7907            // Scan the children
7908            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7909            for (int i = 0; i < childCount; i++) {
7910                PackageParser.Package childPkg = pkg.childPackages.get(i);
7911                scanPackageLI(childPkg, policyFlags,
7912                        scanFlags, currentTime, user);
7913            }
7914        } finally {
7915            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7916        }
7917
7918        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7919            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7920        }
7921
7922        return scannedPkg;
7923    }
7924
7925    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7926            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7927        boolean success = false;
7928        try {
7929            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7930                    currentTime, user);
7931            success = true;
7932            return res;
7933        } finally {
7934            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7935                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7936                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7937                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7938                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7939            }
7940        }
7941    }
7942
7943    /**
7944     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7945     */
7946    private static boolean apkHasCode(String fileName) {
7947        StrictJarFile jarFile = null;
7948        try {
7949            jarFile = new StrictJarFile(fileName,
7950                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7951            return jarFile.findEntry("classes.dex") != null;
7952        } catch (IOException ignore) {
7953        } finally {
7954            try {
7955                if (jarFile != null) {
7956                    jarFile.close();
7957                }
7958            } catch (IOException ignore) {}
7959        }
7960        return false;
7961    }
7962
7963    /**
7964     * Enforces code policy for the package. This ensures that if an APK has
7965     * declared hasCode="true" in its manifest that the APK actually contains
7966     * code.
7967     *
7968     * @throws PackageManagerException If bytecode could not be found when it should exist
7969     */
7970    private static void enforceCodePolicy(PackageParser.Package pkg)
7971            throws PackageManagerException {
7972        final boolean shouldHaveCode =
7973                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7974        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7975            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7976                    "Package " + pkg.baseCodePath + " code is missing");
7977        }
7978
7979        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7980            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7981                final boolean splitShouldHaveCode =
7982                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7983                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7984                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7985                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7986                }
7987            }
7988        }
7989    }
7990
7991    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7992            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7993            throws PackageManagerException {
7994        final File scanFile = new File(pkg.codePath);
7995        if (pkg.applicationInfo.getCodePath() == null ||
7996                pkg.applicationInfo.getResourcePath() == null) {
7997            // Bail out. The resource and code paths haven't been set.
7998            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7999                    "Code and resource paths haven't been set correctly");
8000        }
8001
8002        // Apply policy
8003        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8004            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8005            if (pkg.applicationInfo.isDirectBootAware()) {
8006                // we're direct boot aware; set for all components
8007                for (PackageParser.Service s : pkg.services) {
8008                    s.info.encryptionAware = s.info.directBootAware = true;
8009                }
8010                for (PackageParser.Provider p : pkg.providers) {
8011                    p.info.encryptionAware = p.info.directBootAware = true;
8012                }
8013                for (PackageParser.Activity a : pkg.activities) {
8014                    a.info.encryptionAware = a.info.directBootAware = true;
8015                }
8016                for (PackageParser.Activity r : pkg.receivers) {
8017                    r.info.encryptionAware = r.info.directBootAware = true;
8018                }
8019            }
8020        } else {
8021            // Only allow system apps to be flagged as core apps.
8022            pkg.coreApp = false;
8023            // clear flags not applicable to regular apps
8024            pkg.applicationInfo.privateFlags &=
8025                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8026            pkg.applicationInfo.privateFlags &=
8027                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8028        }
8029        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8030
8031        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8032            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8033        }
8034
8035        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8036            enforceCodePolicy(pkg);
8037        }
8038
8039        if (mCustomResolverComponentName != null &&
8040                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8041            setUpCustomResolverActivity(pkg);
8042        }
8043
8044        if (pkg.packageName.equals("android")) {
8045            synchronized (mPackages) {
8046                if (mAndroidApplication != null) {
8047                    Slog.w(TAG, "*************************************************");
8048                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8049                    Slog.w(TAG, " file=" + scanFile);
8050                    Slog.w(TAG, "*************************************************");
8051                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8052                            "Core android package being redefined.  Skipping.");
8053                }
8054
8055                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8056                    // Set up information for our fall-back user intent resolution activity.
8057                    mPlatformPackage = pkg;
8058                    pkg.mVersionCode = mSdkVersion;
8059                    mAndroidApplication = pkg.applicationInfo;
8060
8061                    if (!mResolverReplaced) {
8062                        mResolveActivity.applicationInfo = mAndroidApplication;
8063                        mResolveActivity.name = ResolverActivity.class.getName();
8064                        mResolveActivity.packageName = mAndroidApplication.packageName;
8065                        mResolveActivity.processName = "system:ui";
8066                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8067                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8068                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8069                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8070                        mResolveActivity.exported = true;
8071                        mResolveActivity.enabled = true;
8072                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8073                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8074                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8075                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8076                                | ActivityInfo.CONFIG_ORIENTATION
8077                                | ActivityInfo.CONFIG_KEYBOARD
8078                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8079                        mResolveInfo.activityInfo = mResolveActivity;
8080                        mResolveInfo.priority = 0;
8081                        mResolveInfo.preferredOrder = 0;
8082                        mResolveInfo.match = 0;
8083                        mResolveComponentName = new ComponentName(
8084                                mAndroidApplication.packageName, mResolveActivity.name);
8085                    }
8086                }
8087            }
8088        }
8089
8090        if (DEBUG_PACKAGE_SCANNING) {
8091            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8092                Log.d(TAG, "Scanning package " + pkg.packageName);
8093        }
8094
8095        synchronized (mPackages) {
8096            if (mPackages.containsKey(pkg.packageName)
8097                    || mSharedLibraries.containsKey(pkg.packageName)) {
8098                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8099                        "Application package " + pkg.packageName
8100                                + " already installed.  Skipping duplicate.");
8101            }
8102
8103            // If we're only installing presumed-existing packages, require that the
8104            // scanned APK is both already known and at the path previously established
8105            // for it.  Previously unknown packages we pick up normally, but if we have an
8106            // a priori expectation about this package's install presence, enforce it.
8107            // With a singular exception for new system packages. When an OTA contains
8108            // a new system package, we allow the codepath to change from a system location
8109            // to the user-installed location. If we don't allow this change, any newer,
8110            // user-installed version of the application will be ignored.
8111            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8112                if (mExpectingBetter.containsKey(pkg.packageName)) {
8113                    logCriticalInfo(Log.WARN,
8114                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8115                } else {
8116                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8117                    if (known != null) {
8118                        if (DEBUG_PACKAGE_SCANNING) {
8119                            Log.d(TAG, "Examining " + pkg.codePath
8120                                    + " and requiring known paths " + known.codePathString
8121                                    + " & " + known.resourcePathString);
8122                        }
8123                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8124                                || !pkg.applicationInfo.getResourcePath().equals(
8125                                known.resourcePathString)) {
8126                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8127                                    "Application package " + pkg.packageName
8128                                            + " found at " + pkg.applicationInfo.getCodePath()
8129                                            + " but expected at " + known.codePathString
8130                                            + "; ignoring.");
8131                        }
8132                    }
8133                }
8134            }
8135        }
8136
8137        // Initialize package source and resource directories
8138        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8139        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8140
8141        SharedUserSetting suid = null;
8142        PackageSetting pkgSetting = null;
8143
8144        if (!isSystemApp(pkg)) {
8145            // Only system apps can use these features.
8146            pkg.mOriginalPackages = null;
8147            pkg.mRealPackage = null;
8148            pkg.mAdoptPermissions = null;
8149        }
8150
8151        // Getting the package setting may have a side-effect, so if we
8152        // are only checking if scan would succeed, stash a copy of the
8153        // old setting to restore at the end.
8154        PackageSetting nonMutatedPs = null;
8155
8156        // writer
8157        synchronized (mPackages) {
8158            if (pkg.mSharedUserId != null) {
8159                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8160                if (suid == null) {
8161                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8162                            "Creating application package " + pkg.packageName
8163                            + " for shared user failed");
8164                }
8165                if (DEBUG_PACKAGE_SCANNING) {
8166                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8167                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8168                                + "): packages=" + suid.packages);
8169                }
8170            }
8171
8172            // Check if we are renaming from an original package name.
8173            PackageSetting origPackage = null;
8174            String realName = null;
8175            if (pkg.mOriginalPackages != null) {
8176                // This package may need to be renamed to a previously
8177                // installed name.  Let's check on that...
8178                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8179                if (pkg.mOriginalPackages.contains(renamed)) {
8180                    // This package had originally been installed as the
8181                    // original name, and we have already taken care of
8182                    // transitioning to the new one.  Just update the new
8183                    // one to continue using the old name.
8184                    realName = pkg.mRealPackage;
8185                    if (!pkg.packageName.equals(renamed)) {
8186                        // Callers into this function may have already taken
8187                        // care of renaming the package; only do it here if
8188                        // it is not already done.
8189                        pkg.setPackageName(renamed);
8190                    }
8191
8192                } else {
8193                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8194                        if ((origPackage = mSettings.peekPackageLPr(
8195                                pkg.mOriginalPackages.get(i))) != null) {
8196                            // We do have the package already installed under its
8197                            // original name...  should we use it?
8198                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8199                                // New package is not compatible with original.
8200                                origPackage = null;
8201                                continue;
8202                            } else if (origPackage.sharedUser != null) {
8203                                // Make sure uid is compatible between packages.
8204                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8205                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8206                                            + " to " + pkg.packageName + ": old uid "
8207                                            + origPackage.sharedUser.name
8208                                            + " differs from " + pkg.mSharedUserId);
8209                                    origPackage = null;
8210                                    continue;
8211                                }
8212                                // TODO: Add case when shared user id is added [b/28144775]
8213                            } else {
8214                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8215                                        + pkg.packageName + " to old name " + origPackage.name);
8216                            }
8217                            break;
8218                        }
8219                    }
8220                }
8221            }
8222
8223            if (mTransferedPackages.contains(pkg.packageName)) {
8224                Slog.w(TAG, "Package " + pkg.packageName
8225                        + " was transferred to another, but its .apk remains");
8226            }
8227
8228            // See comments in nonMutatedPs declaration
8229            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8230                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8231                if (foundPs != null) {
8232                    nonMutatedPs = new PackageSetting(foundPs);
8233                }
8234            }
8235
8236            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8237            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8238                PackageManagerService.reportSettingsProblem(Log.WARN,
8239                        "Package " + pkg.packageName + " shared user changed from "
8240                        + (pkgSetting.sharedUser != null ? pkgSetting.sharedUser.name : "<nothing>")
8241                        + " to "
8242                        + (suid != null ? suid.name : "<nothing>")
8243                        + "; replacing with new");
8244                pkgSetting = null;
8245            }
8246            final PackageSetting oldPkgSetting =
8247                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8248            final PackageSetting disabledPkgSetting =
8249                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8250            if (pkgSetting == null) {
8251                final String parentPackageName = (pkg.parentPackage != null)
8252                        ? pkg.parentPackage.packageName : null;
8253                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8254                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8255                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8256                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8257                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8258                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8259                        UserManagerService.getInstance());
8260                if (origPackage != null) {
8261                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8262                }
8263                mSettings.addUserToSettingLPw(pkgSetting);
8264            } else {
8265                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8266                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8267                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8268                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8269                        UserManagerService.getInstance());
8270            }
8271            mSettings.writeUserRestrictions(pkgSetting, oldPkgSetting);
8272
8273            if (pkgSetting.origPackage != null) {
8274                // If we are first transitioning from an original package,
8275                // fix up the new package's name now.  We need to do this after
8276                // looking up the package under its new name, so getPackageLP
8277                // can take care of fiddling things correctly.
8278                pkg.setPackageName(origPackage.name);
8279
8280                // File a report about this.
8281                String msg = "New package " + pkgSetting.realName
8282                        + " renamed to replace old package " + pkgSetting.name;
8283                reportSettingsProblem(Log.WARN, msg);
8284
8285                // Make a note of it.
8286                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8287                    mTransferedPackages.add(origPackage.name);
8288                }
8289
8290                // No longer need to retain this.
8291                pkgSetting.origPackage = null;
8292            }
8293
8294            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8295                // Make a note of it.
8296                mTransferedPackages.add(pkg.packageName);
8297            }
8298
8299            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8300                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8301            }
8302
8303            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8304                // Check all shared libraries and map to their actual file path.
8305                // We only do this here for apps not on a system dir, because those
8306                // are the only ones that can fail an install due to this.  We
8307                // will take care of the system apps by updating all of their
8308                // library paths after the scan is done.
8309                updateSharedLibrariesLPw(pkg, null);
8310            }
8311
8312            if (mFoundPolicyFile) {
8313                SELinuxMMAC.assignSeinfoValue(pkg);
8314            }
8315
8316            pkg.applicationInfo.uid = pkgSetting.appId;
8317            pkg.mExtras = pkgSetting;
8318            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8319                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8320                    // We just determined the app is signed correctly, so bring
8321                    // over the latest parsed certs.
8322                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8323                } else {
8324                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8325                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8326                                "Package " + pkg.packageName + " upgrade keys do not match the "
8327                                + "previously installed version");
8328                    } else {
8329                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8330                        String msg = "System package " + pkg.packageName
8331                            + " signature changed; retaining data.";
8332                        reportSettingsProblem(Log.WARN, msg);
8333                    }
8334                }
8335            } else {
8336                try {
8337                    verifySignaturesLP(pkgSetting, pkg);
8338                    // We just determined the app is signed correctly, so bring
8339                    // over the latest parsed certs.
8340                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8341                } catch (PackageManagerException e) {
8342                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8343                        throw e;
8344                    }
8345                    // The signature has changed, but this package is in the system
8346                    // image...  let's recover!
8347                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8348                    // However...  if this package is part of a shared user, but it
8349                    // doesn't match the signature of the shared user, let's fail.
8350                    // What this means is that you can't change the signatures
8351                    // associated with an overall shared user, which doesn't seem all
8352                    // that unreasonable.
8353                    if (pkgSetting.sharedUser != null) {
8354                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8355                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8356                            throw new PackageManagerException(
8357                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8358                                            "Signature mismatch for shared user: "
8359                                            + pkgSetting.sharedUser);
8360                        }
8361                    }
8362                    // File a report about this.
8363                    String msg = "System package " + pkg.packageName
8364                        + " signature changed; retaining data.";
8365                    reportSettingsProblem(Log.WARN, msg);
8366                }
8367            }
8368            // Verify that this new package doesn't have any content providers
8369            // that conflict with existing packages.  Only do this if the
8370            // package isn't already installed, since we don't want to break
8371            // things that are installed.
8372            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8373                final int N = pkg.providers.size();
8374                int i;
8375                for (i=0; i<N; i++) {
8376                    PackageParser.Provider p = pkg.providers.get(i);
8377                    if (p.info.authority != null) {
8378                        String names[] = p.info.authority.split(";");
8379                        for (int j = 0; j < names.length; j++) {
8380                            if (mProvidersByAuthority.containsKey(names[j])) {
8381                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8382                                final String otherPackageName =
8383                                        ((other != null && other.getComponentName() != null) ?
8384                                                other.getComponentName().getPackageName() : "?");
8385                                throw new PackageManagerException(
8386                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8387                                                "Can't install because provider name " + names[j]
8388                                                + " (in package " + pkg.applicationInfo.packageName
8389                                                + ") is already used by " + otherPackageName);
8390                            }
8391                        }
8392                    }
8393                }
8394            }
8395
8396            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8397                // This package wants to adopt ownership of permissions from
8398                // another package.
8399                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8400                    final String origName = pkg.mAdoptPermissions.get(i);
8401                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8402                    if (orig != null) {
8403                        if (verifyPackageUpdateLPr(orig, pkg)) {
8404                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8405                                    + pkg.packageName);
8406                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8407                        }
8408                    }
8409                }
8410            }
8411        }
8412
8413        final String pkgName = pkg.packageName;
8414
8415        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8416        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8417        pkg.applicationInfo.processName = fixProcessName(
8418                pkg.applicationInfo.packageName,
8419                pkg.applicationInfo.processName,
8420                pkg.applicationInfo.uid);
8421
8422        if (pkg != mPlatformPackage) {
8423            // Get all of our default paths setup
8424            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8425        }
8426
8427        final String path = scanFile.getPath();
8428        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8429
8430        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8432            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /*extractLibs*/);
8433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8434
8435            // Some system apps still use directory structure for native libraries
8436            // in which case we might end up not detecting abi solely based on apk
8437            // structure. Try to detect abi based on directory structure.
8438            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8439                    pkg.applicationInfo.primaryCpuAbi == null) {
8440                setBundledAppAbisAndRoots(pkg, pkgSetting);
8441                setNativeLibraryPaths(pkg);
8442            }
8443
8444        } else {
8445            if ((scanFlags & SCAN_MOVE) != 0) {
8446                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8447                // but we already have this packages package info in the PackageSetting. We just
8448                // use that and derive the native library path based on the new codepath.
8449                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8450                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8451            }
8452
8453            // Set native library paths again. For moves, the path will be updated based on the
8454            // ABIs we've determined above. For non-moves, the path will be updated based on the
8455            // ABIs we determined during compilation, but the path will depend on the final
8456            // package path (after the rename away from the stage path).
8457            setNativeLibraryPaths(pkg);
8458        }
8459
8460        // This is a special case for the "system" package, where the ABI is
8461        // dictated by the zygote configuration (and init.rc). We should keep track
8462        // of this ABI so that we can deal with "normal" applications that run under
8463        // the same UID correctly.
8464        if (mPlatformPackage == pkg) {
8465            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8466                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8467        }
8468
8469        // If there's a mismatch between the abi-override in the package setting
8470        // and the abiOverride specified for the install. Warn about this because we
8471        // would've already compiled the app without taking the package setting into
8472        // account.
8473        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8474            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8475                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8476                        " for package " + pkg.packageName);
8477            }
8478        }
8479
8480        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8481        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8482        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8483
8484        // Copy the derived override back to the parsed package, so that we can
8485        // update the package settings accordingly.
8486        pkg.cpuAbiOverride = cpuAbiOverride;
8487
8488        if (DEBUG_ABI_SELECTION) {
8489            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8490                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8491                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8492        }
8493
8494        // Push the derived path down into PackageSettings so we know what to
8495        // clean up at uninstall time.
8496        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8497
8498        if (DEBUG_ABI_SELECTION) {
8499            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8500                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8501                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8502        }
8503
8504        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8505            // We don't do this here during boot because we can do it all
8506            // at once after scanning all existing packages.
8507            //
8508            // We also do this *before* we perform dexopt on this package, so that
8509            // we can avoid redundant dexopts, and also to make sure we've got the
8510            // code and package path correct.
8511            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8512                    pkg, true /* boot complete */);
8513        }
8514
8515        if (mFactoryTest && pkg.requestedPermissions.contains(
8516                android.Manifest.permission.FACTORY_TEST)) {
8517            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8518        }
8519
8520        if (isSystemApp(pkg)) {
8521            pkgSetting.isOrphaned = true;
8522        }
8523
8524        ArrayList<PackageParser.Package> clientLibPkgs = null;
8525
8526        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8527            if (nonMutatedPs != null) {
8528                synchronized (mPackages) {
8529                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8530                }
8531            }
8532            return pkg;
8533        }
8534
8535        // Only privileged apps and updated privileged apps can add child packages.
8536        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8537            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8538                throw new PackageManagerException("Only privileged apps and updated "
8539                        + "privileged apps can add child packages. Ignoring package "
8540                        + pkg.packageName);
8541            }
8542            final int childCount = pkg.childPackages.size();
8543            for (int i = 0; i < childCount; i++) {
8544                PackageParser.Package childPkg = pkg.childPackages.get(i);
8545                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8546                        childPkg.packageName)) {
8547                    throw new PackageManagerException("Cannot override a child package of "
8548                            + "another disabled system app. Ignoring package " + pkg.packageName);
8549                }
8550            }
8551        }
8552
8553        // writer
8554        synchronized (mPackages) {
8555            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8556                // Only system apps can add new shared libraries.
8557                if (pkg.libraryNames != null) {
8558                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8559                        String name = pkg.libraryNames.get(i);
8560                        boolean allowed = false;
8561                        if (pkg.isUpdatedSystemApp()) {
8562                            // New library entries can only be added through the
8563                            // system image.  This is important to get rid of a lot
8564                            // of nasty edge cases: for example if we allowed a non-
8565                            // system update of the app to add a library, then uninstalling
8566                            // the update would make the library go away, and assumptions
8567                            // we made such as through app install filtering would now
8568                            // have allowed apps on the device which aren't compatible
8569                            // with it.  Better to just have the restriction here, be
8570                            // conservative, and create many fewer cases that can negatively
8571                            // impact the user experience.
8572                            final PackageSetting sysPs = mSettings
8573                                    .getDisabledSystemPkgLPr(pkg.packageName);
8574                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8575                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8576                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8577                                        allowed = true;
8578                                        break;
8579                                    }
8580                                }
8581                            }
8582                        } else {
8583                            allowed = true;
8584                        }
8585                        if (allowed) {
8586                            if (!mSharedLibraries.containsKey(name)) {
8587                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8588                            } else if (!name.equals(pkg.packageName)) {
8589                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8590                                        + name + " already exists; skipping");
8591                            }
8592                        } else {
8593                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8594                                    + name + " that is not declared on system image; skipping");
8595                        }
8596                    }
8597                    if ((scanFlags & SCAN_BOOTING) == 0) {
8598                        // If we are not booting, we need to update any applications
8599                        // that are clients of our shared library.  If we are booting,
8600                        // this will all be done once the scan is complete.
8601                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8602                    }
8603                }
8604            }
8605        }
8606
8607        if ((scanFlags & SCAN_BOOTING) != 0) {
8608            // No apps can run during boot scan, so they don't need to be frozen
8609        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8610            // Caller asked to not kill app, so it's probably not frozen
8611        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8612            // Caller asked us to ignore frozen check for some reason; they
8613            // probably didn't know the package name
8614        } else {
8615            // We're doing major surgery on this package, so it better be frozen
8616            // right now to keep it from launching
8617            checkPackageFrozen(pkgName);
8618        }
8619
8620        // Also need to kill any apps that are dependent on the library.
8621        if (clientLibPkgs != null) {
8622            for (int i=0; i<clientLibPkgs.size(); i++) {
8623                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8624                killApplication(clientPkg.applicationInfo.packageName,
8625                        clientPkg.applicationInfo.uid, "update lib");
8626            }
8627        }
8628
8629        // Make sure we're not adding any bogus keyset info
8630        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8631        ksms.assertScannedPackageValid(pkg);
8632
8633        // writer
8634        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8635
8636        boolean createIdmapFailed = false;
8637        synchronized (mPackages) {
8638            // We don't expect installation to fail beyond this point
8639
8640            if (pkgSetting.pkg != null) {
8641                // Note that |user| might be null during the initial boot scan. If a codePath
8642                // for an app has changed during a boot scan, it's due to an app update that's
8643                // part of the system partition and marker changes must be applied to all users.
8644                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8645                    (user != null) ? user : UserHandle.ALL);
8646            }
8647
8648            // Add the new setting to mSettings
8649            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8650            // Add the new setting to mPackages
8651            mPackages.put(pkg.applicationInfo.packageName, pkg);
8652            // Make sure we don't accidentally delete its data.
8653            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8654            while (iter.hasNext()) {
8655                PackageCleanItem item = iter.next();
8656                if (pkgName.equals(item.packageName)) {
8657                    iter.remove();
8658                }
8659            }
8660
8661            // Take care of first install / last update times.
8662            if (currentTime != 0) {
8663                if (pkgSetting.firstInstallTime == 0) {
8664                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8665                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8666                    pkgSetting.lastUpdateTime = currentTime;
8667                }
8668            } else if (pkgSetting.firstInstallTime == 0) {
8669                // We need *something*.  Take time time stamp of the file.
8670                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8671            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8672                if (scanFileTime != pkgSetting.timeStamp) {
8673                    // A package on the system image has changed; consider this
8674                    // to be an update.
8675                    pkgSetting.lastUpdateTime = scanFileTime;
8676                }
8677            }
8678
8679            // Add the package's KeySets to the global KeySetManagerService
8680            ksms.addScannedPackageLPw(pkg);
8681
8682            int N = pkg.providers.size();
8683            StringBuilder r = null;
8684            int i;
8685            for (i=0; i<N; i++) {
8686                PackageParser.Provider p = pkg.providers.get(i);
8687                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8688                        p.info.processName, pkg.applicationInfo.uid);
8689                mProviders.addProvider(p);
8690                p.syncable = p.info.isSyncable;
8691                if (p.info.authority != null) {
8692                    String names[] = p.info.authority.split(";");
8693                    p.info.authority = null;
8694                    for (int j = 0; j < names.length; j++) {
8695                        if (j == 1 && p.syncable) {
8696                            // We only want the first authority for a provider to possibly be
8697                            // syncable, so if we already added this provider using a different
8698                            // authority clear the syncable flag. We copy the provider before
8699                            // changing it because the mProviders object contains a reference
8700                            // to a provider that we don't want to change.
8701                            // Only do this for the second authority since the resulting provider
8702                            // object can be the same for all future authorities for this provider.
8703                            p = new PackageParser.Provider(p);
8704                            p.syncable = false;
8705                        }
8706                        if (!mProvidersByAuthority.containsKey(names[j])) {
8707                            mProvidersByAuthority.put(names[j], p);
8708                            if (p.info.authority == null) {
8709                                p.info.authority = names[j];
8710                            } else {
8711                                p.info.authority = p.info.authority + ";" + names[j];
8712                            }
8713                            if (DEBUG_PACKAGE_SCANNING) {
8714                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8715                                    Log.d(TAG, "Registered content provider: " + names[j]
8716                                            + ", className = " + p.info.name + ", isSyncable = "
8717                                            + p.info.isSyncable);
8718                            }
8719                        } else {
8720                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8721                            Slog.w(TAG, "Skipping provider name " + names[j] +
8722                                    " (in package " + pkg.applicationInfo.packageName +
8723                                    "): name already used by "
8724                                    + ((other != null && other.getComponentName() != null)
8725                                            ? other.getComponentName().getPackageName() : "?"));
8726                        }
8727                    }
8728                }
8729                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8730                    if (r == null) {
8731                        r = new StringBuilder(256);
8732                    } else {
8733                        r.append(' ');
8734                    }
8735                    r.append(p.info.name);
8736                }
8737            }
8738            if (r != null) {
8739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8740            }
8741
8742            N = pkg.services.size();
8743            r = null;
8744            for (i=0; i<N; i++) {
8745                PackageParser.Service s = pkg.services.get(i);
8746                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8747                        s.info.processName, pkg.applicationInfo.uid);
8748                mServices.addService(s);
8749                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8750                    if (r == null) {
8751                        r = new StringBuilder(256);
8752                    } else {
8753                        r.append(' ');
8754                    }
8755                    r.append(s.info.name);
8756                }
8757            }
8758            if (r != null) {
8759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8760            }
8761
8762            N = pkg.receivers.size();
8763            r = null;
8764            for (i=0; i<N; i++) {
8765                PackageParser.Activity a = pkg.receivers.get(i);
8766                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8767                        a.info.processName, pkg.applicationInfo.uid);
8768                mReceivers.addActivity(a, "receiver");
8769                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8770                    if (r == null) {
8771                        r = new StringBuilder(256);
8772                    } else {
8773                        r.append(' ');
8774                    }
8775                    r.append(a.info.name);
8776                }
8777            }
8778            if (r != null) {
8779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8780            }
8781
8782            N = pkg.activities.size();
8783            r = null;
8784            for (i=0; i<N; i++) {
8785                PackageParser.Activity a = pkg.activities.get(i);
8786                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8787                        a.info.processName, pkg.applicationInfo.uid);
8788                mActivities.addActivity(a, "activity");
8789                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8790                    if (r == null) {
8791                        r = new StringBuilder(256);
8792                    } else {
8793                        r.append(' ');
8794                    }
8795                    r.append(a.info.name);
8796                }
8797            }
8798            if (r != null) {
8799                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8800            }
8801
8802            N = pkg.permissionGroups.size();
8803            r = null;
8804            for (i=0; i<N; i++) {
8805                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8806                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8807                final String curPackageName = cur == null ? null : cur.info.packageName;
8808                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8809                if (cur == null || isPackageUpdate) {
8810                    mPermissionGroups.put(pg.info.name, pg);
8811                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8812                        if (r == null) {
8813                            r = new StringBuilder(256);
8814                        } else {
8815                            r.append(' ');
8816                        }
8817                        if (isPackageUpdate) {
8818                            r.append("UPD:");
8819                        }
8820                        r.append(pg.info.name);
8821                    }
8822                } else {
8823                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8824                            + pg.info.packageName + " ignored: original from "
8825                            + cur.info.packageName);
8826                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8827                        if (r == null) {
8828                            r = new StringBuilder(256);
8829                        } else {
8830                            r.append(' ');
8831                        }
8832                        r.append("DUP:");
8833                        r.append(pg.info.name);
8834                    }
8835                }
8836            }
8837            if (r != null) {
8838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8839            }
8840
8841            N = pkg.permissions.size();
8842            r = null;
8843            for (i=0; i<N; i++) {
8844                PackageParser.Permission p = pkg.permissions.get(i);
8845
8846                // Assume by default that we did not install this permission into the system.
8847                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8848
8849                // Now that permission groups have a special meaning, we ignore permission
8850                // groups for legacy apps to prevent unexpected behavior. In particular,
8851                // permissions for one app being granted to someone just becase they happen
8852                // to be in a group defined by another app (before this had no implications).
8853                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8854                    p.group = mPermissionGroups.get(p.info.group);
8855                    // Warn for a permission in an unknown group.
8856                    if (p.info.group != null && p.group == null) {
8857                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8858                                + p.info.packageName + " in an unknown group " + p.info.group);
8859                    }
8860                }
8861
8862                ArrayMap<String, BasePermission> permissionMap =
8863                        p.tree ? mSettings.mPermissionTrees
8864                                : mSettings.mPermissions;
8865                BasePermission bp = permissionMap.get(p.info.name);
8866
8867                // Allow system apps to redefine non-system permissions
8868                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8869                    final boolean currentOwnerIsSystem = (bp.perm != null
8870                            && isSystemApp(bp.perm.owner));
8871                    if (isSystemApp(p.owner)) {
8872                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8873                            // It's a built-in permission and no owner, take ownership now
8874                            bp.packageSetting = pkgSetting;
8875                            bp.perm = p;
8876                            bp.uid = pkg.applicationInfo.uid;
8877                            bp.sourcePackage = p.info.packageName;
8878                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8879                        } else if (!currentOwnerIsSystem) {
8880                            String msg = "New decl " + p.owner + " of permission  "
8881                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8882                            reportSettingsProblem(Log.WARN, msg);
8883                            bp = null;
8884                        }
8885                    }
8886                }
8887
8888                if (bp == null) {
8889                    bp = new BasePermission(p.info.name, p.info.packageName,
8890                            BasePermission.TYPE_NORMAL);
8891                    permissionMap.put(p.info.name, bp);
8892                }
8893
8894                if (bp.perm == null) {
8895                    if (bp.sourcePackage == null
8896                            || bp.sourcePackage.equals(p.info.packageName)) {
8897                        BasePermission tree = findPermissionTreeLP(p.info.name);
8898                        if (tree == null
8899                                || tree.sourcePackage.equals(p.info.packageName)) {
8900                            bp.packageSetting = pkgSetting;
8901                            bp.perm = p;
8902                            bp.uid = pkg.applicationInfo.uid;
8903                            bp.sourcePackage = p.info.packageName;
8904                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8905                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8906                                if (r == null) {
8907                                    r = new StringBuilder(256);
8908                                } else {
8909                                    r.append(' ');
8910                                }
8911                                r.append(p.info.name);
8912                            }
8913                        } else {
8914                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8915                                    + p.info.packageName + " ignored: base tree "
8916                                    + tree.name + " is from package "
8917                                    + tree.sourcePackage);
8918                        }
8919                    } else {
8920                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8921                                + p.info.packageName + " ignored: original from "
8922                                + bp.sourcePackage);
8923                    }
8924                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8925                    if (r == null) {
8926                        r = new StringBuilder(256);
8927                    } else {
8928                        r.append(' ');
8929                    }
8930                    r.append("DUP:");
8931                    r.append(p.info.name);
8932                }
8933                if (bp.perm == p) {
8934                    bp.protectionLevel = p.info.protectionLevel;
8935                }
8936            }
8937
8938            if (r != null) {
8939                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8940            }
8941
8942            N = pkg.instrumentation.size();
8943            r = null;
8944            for (i=0; i<N; i++) {
8945                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8946                a.info.packageName = pkg.applicationInfo.packageName;
8947                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8948                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8949                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8950                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8951                a.info.dataDir = pkg.applicationInfo.dataDir;
8952                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8953                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8954
8955                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8956                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8957                mInstrumentation.put(a.getComponentName(), a);
8958                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8959                    if (r == null) {
8960                        r = new StringBuilder(256);
8961                    } else {
8962                        r.append(' ');
8963                    }
8964                    r.append(a.info.name);
8965                }
8966            }
8967            if (r != null) {
8968                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8969            }
8970
8971            if (pkg.protectedBroadcasts != null) {
8972                N = pkg.protectedBroadcasts.size();
8973                for (i=0; i<N; i++) {
8974                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8975                }
8976            }
8977
8978            pkgSetting.setTimeStamp(scanFileTime);
8979
8980            // Create idmap files for pairs of (packages, overlay packages).
8981            // Note: "android", ie framework-res.apk, is handled by native layers.
8982            if (pkg.mOverlayTarget != null) {
8983                // This is an overlay package.
8984                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8985                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8986                        mOverlays.put(pkg.mOverlayTarget,
8987                                new ArrayMap<String, PackageParser.Package>());
8988                    }
8989                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8990                    map.put(pkg.packageName, pkg);
8991                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8992                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8993                        createIdmapFailed = true;
8994                    }
8995                }
8996            } else if (mOverlays.containsKey(pkg.packageName) &&
8997                    !pkg.packageName.equals("android")) {
8998                // This is a regular package, with one or more known overlay packages.
8999                createIdmapsForPackageLI(pkg);
9000            }
9001        }
9002
9003        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9004
9005        if (createIdmapFailed) {
9006            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9007                    "scanPackageLI failed to createIdmap");
9008        }
9009        return pkg;
9010    }
9011
9012    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9013            PackageParser.Package update, UserHandle user) {
9014        if (existing.applicationInfo == null || update.applicationInfo == null) {
9015            // This isn't due to an app installation.
9016            return;
9017        }
9018
9019        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9020        final File newCodePath = new File(update.applicationInfo.getCodePath());
9021
9022        // The codePath hasn't changed, so there's nothing for us to do.
9023        if (Objects.equals(oldCodePath, newCodePath)) {
9024            return;
9025        }
9026
9027        File canonicalNewCodePath;
9028        try {
9029            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9030        } catch (IOException e) {
9031            Slog.w(TAG, "Failed to get canonical path.", e);
9032            return;
9033        }
9034
9035        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9036        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9037        // that the last component of the path (i.e, the name) doesn't need canonicalization
9038        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9039        // but may change in the future. Hopefully this function won't exist at that point.
9040        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9041                oldCodePath.getName());
9042
9043        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9044        // with "@".
9045        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9046        if (!oldMarkerPrefix.endsWith("@")) {
9047            oldMarkerPrefix += "@";
9048        }
9049        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9050        if (!newMarkerPrefix.endsWith("@")) {
9051            newMarkerPrefix += "@";
9052        }
9053
9054        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9055        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9056        for (String updatedPath : updatedPaths) {
9057            String updatedPathName = new File(updatedPath).getName();
9058            markerSuffixes.add(updatedPathName.replace('/', '@'));
9059        }
9060
9061        for (int userId : resolveUserIds(user.getIdentifier())) {
9062            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9063
9064            for (String markerSuffix : markerSuffixes) {
9065                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9066                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9067                if (oldForeignUseMark.exists()) {
9068                    try {
9069                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9070                                newForeignUseMark.getAbsolutePath());
9071                    } catch (ErrnoException e) {
9072                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9073                        oldForeignUseMark.delete();
9074                    }
9075                }
9076            }
9077        }
9078    }
9079
9080    /**
9081     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9082     * is derived purely on the basis of the contents of {@code scanFile} and
9083     * {@code cpuAbiOverride}.
9084     *
9085     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9086     */
9087    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9088                                 String cpuAbiOverride, boolean extractLibs)
9089            throws PackageManagerException {
9090        // TODO: We can probably be smarter about this stuff. For installed apps,
9091        // we can calculate this information at install time once and for all. For
9092        // system apps, we can probably assume that this information doesn't change
9093        // after the first boot scan. As things stand, we do lots of unnecessary work.
9094
9095        // Give ourselves some initial paths; we'll come back for another
9096        // pass once we've determined ABI below.
9097        setNativeLibraryPaths(pkg);
9098
9099        // We would never need to extract libs for forward-locked and external packages,
9100        // since the container service will do it for us. We shouldn't attempt to
9101        // extract libs from system app when it was not updated.
9102        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9103                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9104            extractLibs = false;
9105        }
9106
9107        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9108        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9109
9110        NativeLibraryHelper.Handle handle = null;
9111        try {
9112            handle = NativeLibraryHelper.Handle.create(pkg);
9113            // TODO(multiArch): This can be null for apps that didn't go through the
9114            // usual installation process. We can calculate it again, like we
9115            // do during install time.
9116            //
9117            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9118            // unnecessary.
9119            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9120
9121            // Null out the abis so that they can be recalculated.
9122            pkg.applicationInfo.primaryCpuAbi = null;
9123            pkg.applicationInfo.secondaryCpuAbi = null;
9124            if (isMultiArch(pkg.applicationInfo)) {
9125                // Warn if we've set an abiOverride for multi-lib packages..
9126                // By definition, we need to copy both 32 and 64 bit libraries for
9127                // such packages.
9128                if (pkg.cpuAbiOverride != null
9129                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9130                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9131                }
9132
9133                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9134                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9135                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9136                    if (extractLibs) {
9137                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9138                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9139                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9140                                useIsaSpecificSubdirs);
9141                    } else {
9142                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9143                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9144                    }
9145                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9146                }
9147
9148                maybeThrowExceptionForMultiArchCopy(
9149                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9150
9151                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9152                    if (extractLibs) {
9153                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9154                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9155                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9156                                useIsaSpecificSubdirs);
9157                    } else {
9158                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9159                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9160                    }
9161                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9162                }
9163
9164                maybeThrowExceptionForMultiArchCopy(
9165                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9166
9167                if (abi64 >= 0) {
9168                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9169                }
9170
9171                if (abi32 >= 0) {
9172                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9173                    if (abi64 >= 0) {
9174                        if (pkg.use32bitAbi) {
9175                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9176                            pkg.applicationInfo.primaryCpuAbi = abi;
9177                        } else {
9178                            pkg.applicationInfo.secondaryCpuAbi = abi;
9179                        }
9180                    } else {
9181                        pkg.applicationInfo.primaryCpuAbi = abi;
9182                    }
9183                }
9184
9185            } else {
9186                String[] abiList = (cpuAbiOverride != null) ?
9187                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9188
9189                // Enable gross and lame hacks for apps that are built with old
9190                // SDK tools. We must scan their APKs for renderscript bitcode and
9191                // not launch them if it's present. Don't bother checking on devices
9192                // that don't have 64 bit support.
9193                boolean needsRenderScriptOverride = false;
9194                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9195                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9196                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9197                    needsRenderScriptOverride = true;
9198                }
9199
9200                final int copyRet;
9201                if (extractLibs) {
9202                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9203                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9204                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9205                } else {
9206                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9207                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9208                }
9209                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9210
9211                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9212                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9213                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9214                }
9215
9216                if (copyRet >= 0) {
9217                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9218                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9219                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9220                } else if (needsRenderScriptOverride) {
9221                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9222                }
9223            }
9224        } catch (IOException ioe) {
9225            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9226        } finally {
9227            IoUtils.closeQuietly(handle);
9228        }
9229
9230        // Now that we've calculated the ABIs and determined if it's an internal app,
9231        // we will go ahead and populate the nativeLibraryPath.
9232        setNativeLibraryPaths(pkg);
9233    }
9234
9235    /**
9236     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9237     * i.e, so that all packages can be run inside a single process if required.
9238     *
9239     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9240     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9241     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9242     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9243     * updating a package that belongs to a shared user.
9244     *
9245     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9246     * adds unnecessary complexity.
9247     */
9248    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9249            PackageParser.Package scannedPackage, boolean bootComplete) {
9250        String requiredInstructionSet = null;
9251        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9252            requiredInstructionSet = VMRuntime.getInstructionSet(
9253                     scannedPackage.applicationInfo.primaryCpuAbi);
9254        }
9255
9256        PackageSetting requirer = null;
9257        for (PackageSetting ps : packagesForUser) {
9258            // If packagesForUser contains scannedPackage, we skip it. This will happen
9259            // when scannedPackage is an update of an existing package. Without this check,
9260            // we will never be able to change the ABI of any package belonging to a shared
9261            // user, even if it's compatible with other packages.
9262            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9263                if (ps.primaryCpuAbiString == null) {
9264                    continue;
9265                }
9266
9267                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9268                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9269                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9270                    // this but there's not much we can do.
9271                    String errorMessage = "Instruction set mismatch, "
9272                            + ((requirer == null) ? "[caller]" : requirer)
9273                            + " requires " + requiredInstructionSet + " whereas " + ps
9274                            + " requires " + instructionSet;
9275                    Slog.w(TAG, errorMessage);
9276                }
9277
9278                if (requiredInstructionSet == null) {
9279                    requiredInstructionSet = instructionSet;
9280                    requirer = ps;
9281                }
9282            }
9283        }
9284
9285        if (requiredInstructionSet != null) {
9286            String adjustedAbi;
9287            if (requirer != null) {
9288                // requirer != null implies that either scannedPackage was null or that scannedPackage
9289                // did not require an ABI, in which case we have to adjust scannedPackage to match
9290                // the ABI of the set (which is the same as requirer's ABI)
9291                adjustedAbi = requirer.primaryCpuAbiString;
9292                if (scannedPackage != null) {
9293                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9294                }
9295            } else {
9296                // requirer == null implies that we're updating all ABIs in the set to
9297                // match scannedPackage.
9298                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9299            }
9300
9301            for (PackageSetting ps : packagesForUser) {
9302                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9303                    if (ps.primaryCpuAbiString != null) {
9304                        continue;
9305                    }
9306
9307                    ps.primaryCpuAbiString = adjustedAbi;
9308                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9309                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9310                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9311                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9312                                + " (requirer="
9313                                + (requirer == null ? "null" : requirer.pkg.packageName)
9314                                + ", scannedPackage="
9315                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9316                                + ")");
9317                        try {
9318                            mInstaller.rmdex(ps.codePathString,
9319                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9320                        } catch (InstallerException ignored) {
9321                        }
9322                    }
9323                }
9324            }
9325        }
9326    }
9327
9328    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9329        synchronized (mPackages) {
9330            mResolverReplaced = true;
9331            // Set up information for custom user intent resolution activity.
9332            mResolveActivity.applicationInfo = pkg.applicationInfo;
9333            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9334            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9335            mResolveActivity.processName = pkg.applicationInfo.packageName;
9336            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9337            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9338                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9339            mResolveActivity.theme = 0;
9340            mResolveActivity.exported = true;
9341            mResolveActivity.enabled = true;
9342            mResolveInfo.activityInfo = mResolveActivity;
9343            mResolveInfo.priority = 0;
9344            mResolveInfo.preferredOrder = 0;
9345            mResolveInfo.match = 0;
9346            mResolveComponentName = mCustomResolverComponentName;
9347            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9348                    mResolveComponentName);
9349        }
9350    }
9351
9352    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9353        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9354
9355        // Set up information for ephemeral installer activity
9356        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9357        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9358        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9359        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9360        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9361        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9362                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9363        mEphemeralInstallerActivity.theme = 0;
9364        mEphemeralInstallerActivity.exported = true;
9365        mEphemeralInstallerActivity.enabled = true;
9366        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9367        mEphemeralInstallerInfo.priority = 0;
9368        mEphemeralInstallerInfo.preferredOrder = 1;
9369        mEphemeralInstallerInfo.isDefault = true;
9370        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9371                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9372
9373        if (DEBUG_EPHEMERAL) {
9374            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9375        }
9376    }
9377
9378    private static String calculateBundledApkRoot(final String codePathString) {
9379        final File codePath = new File(codePathString);
9380        final File codeRoot;
9381        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9382            codeRoot = Environment.getRootDirectory();
9383        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9384            codeRoot = Environment.getOemDirectory();
9385        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9386            codeRoot = Environment.getVendorDirectory();
9387        } else {
9388            // Unrecognized code path; take its top real segment as the apk root:
9389            // e.g. /something/app/blah.apk => /something
9390            try {
9391                File f = codePath.getCanonicalFile();
9392                File parent = f.getParentFile();    // non-null because codePath is a file
9393                File tmp;
9394                while ((tmp = parent.getParentFile()) != null) {
9395                    f = parent;
9396                    parent = tmp;
9397                }
9398                codeRoot = f;
9399                Slog.w(TAG, "Unrecognized code path "
9400                        + codePath + " - using " + codeRoot);
9401            } catch (IOException e) {
9402                // Can't canonicalize the code path -- shenanigans?
9403                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9404                return Environment.getRootDirectory().getPath();
9405            }
9406        }
9407        return codeRoot.getPath();
9408    }
9409
9410    /**
9411     * Derive and set the location of native libraries for the given package,
9412     * which varies depending on where and how the package was installed.
9413     */
9414    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9415        final ApplicationInfo info = pkg.applicationInfo;
9416        final String codePath = pkg.codePath;
9417        final File codeFile = new File(codePath);
9418        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9419        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9420
9421        info.nativeLibraryRootDir = null;
9422        info.nativeLibraryRootRequiresIsa = false;
9423        info.nativeLibraryDir = null;
9424        info.secondaryNativeLibraryDir = null;
9425
9426        if (isApkFile(codeFile)) {
9427            // Monolithic install
9428            if (bundledApp) {
9429                // If "/system/lib64/apkname" exists, assume that is the per-package
9430                // native library directory to use; otherwise use "/system/lib/apkname".
9431                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9432                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9433                        getPrimaryInstructionSet(info));
9434
9435                // This is a bundled system app so choose the path based on the ABI.
9436                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9437                // is just the default path.
9438                final String apkName = deriveCodePathName(codePath);
9439                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9440                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9441                        apkName).getAbsolutePath();
9442
9443                if (info.secondaryCpuAbi != null) {
9444                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9445                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9446                            secondaryLibDir, apkName).getAbsolutePath();
9447                }
9448            } else if (asecApp) {
9449                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9450                        .getAbsolutePath();
9451            } else {
9452                final String apkName = deriveCodePathName(codePath);
9453                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9454                        .getAbsolutePath();
9455            }
9456
9457            info.nativeLibraryRootRequiresIsa = false;
9458            info.nativeLibraryDir = info.nativeLibraryRootDir;
9459        } else {
9460            // Cluster install
9461            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9462            info.nativeLibraryRootRequiresIsa = true;
9463
9464            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9465                    getPrimaryInstructionSet(info)).getAbsolutePath();
9466
9467            if (info.secondaryCpuAbi != null) {
9468                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9469                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9470            }
9471        }
9472    }
9473
9474    /**
9475     * Calculate the abis and roots for a bundled app. These can uniquely
9476     * be determined from the contents of the system partition, i.e whether
9477     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9478     * of this information, and instead assume that the system was built
9479     * sensibly.
9480     */
9481    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9482                                           PackageSetting pkgSetting) {
9483        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9484
9485        // If "/system/lib64/apkname" exists, assume that is the per-package
9486        // native library directory to use; otherwise use "/system/lib/apkname".
9487        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9488        setBundledAppAbi(pkg, apkRoot, apkName);
9489        // pkgSetting might be null during rescan following uninstall of updates
9490        // to a bundled app, so accommodate that possibility.  The settings in
9491        // that case will be established later from the parsed package.
9492        //
9493        // If the settings aren't null, sync them up with what we've just derived.
9494        // note that apkRoot isn't stored in the package settings.
9495        if (pkgSetting != null) {
9496            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9497            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9498        }
9499    }
9500
9501    /**
9502     * Deduces the ABI of a bundled app and sets the relevant fields on the
9503     * parsed pkg object.
9504     *
9505     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9506     *        under which system libraries are installed.
9507     * @param apkName the name of the installed package.
9508     */
9509    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9510        final File codeFile = new File(pkg.codePath);
9511
9512        final boolean has64BitLibs;
9513        final boolean has32BitLibs;
9514        if (isApkFile(codeFile)) {
9515            // Monolithic install
9516            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9517            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9518        } else {
9519            // Cluster install
9520            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9521            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9522                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9523                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9524                has64BitLibs = (new File(rootDir, isa)).exists();
9525            } else {
9526                has64BitLibs = false;
9527            }
9528            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9529                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9530                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9531                has32BitLibs = (new File(rootDir, isa)).exists();
9532            } else {
9533                has32BitLibs = false;
9534            }
9535        }
9536
9537        if (has64BitLibs && !has32BitLibs) {
9538            // The package has 64 bit libs, but not 32 bit libs. Its primary
9539            // ABI should be 64 bit. We can safely assume here that the bundled
9540            // native libraries correspond to the most preferred ABI in the list.
9541
9542            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9543            pkg.applicationInfo.secondaryCpuAbi = null;
9544        } else if (has32BitLibs && !has64BitLibs) {
9545            // The package has 32 bit libs but not 64 bit libs. Its primary
9546            // ABI should be 32 bit.
9547
9548            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9549            pkg.applicationInfo.secondaryCpuAbi = null;
9550        } else if (has32BitLibs && has64BitLibs) {
9551            // The application has both 64 and 32 bit bundled libraries. We check
9552            // here that the app declares multiArch support, and warn if it doesn't.
9553            //
9554            // We will be lenient here and record both ABIs. The primary will be the
9555            // ABI that's higher on the list, i.e, a device that's configured to prefer
9556            // 64 bit apps will see a 64 bit primary ABI,
9557
9558            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9559                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9560            }
9561
9562            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9563                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9564                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9565            } else {
9566                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9567                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9568            }
9569        } else {
9570            pkg.applicationInfo.primaryCpuAbi = null;
9571            pkg.applicationInfo.secondaryCpuAbi = null;
9572        }
9573    }
9574
9575    private void killApplication(String pkgName, int appId, String reason) {
9576        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9577    }
9578
9579    private void killApplication(String pkgName, int appId, int userId, String reason) {
9580        // Request the ActivityManager to kill the process(only for existing packages)
9581        // so that we do not end up in a confused state while the user is still using the older
9582        // version of the application while the new one gets installed.
9583        final long token = Binder.clearCallingIdentity();
9584        try {
9585            IActivityManager am = ActivityManagerNative.getDefault();
9586            if (am != null) {
9587                try {
9588                    am.killApplication(pkgName, appId, userId, reason);
9589                } catch (RemoteException e) {
9590                }
9591            }
9592        } finally {
9593            Binder.restoreCallingIdentity(token);
9594        }
9595    }
9596
9597    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9598        // Remove the parent package setting
9599        PackageSetting ps = (PackageSetting) pkg.mExtras;
9600        if (ps != null) {
9601            removePackageLI(ps, chatty);
9602        }
9603        // Remove the child package setting
9604        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9605        for (int i = 0; i < childCount; i++) {
9606            PackageParser.Package childPkg = pkg.childPackages.get(i);
9607            ps = (PackageSetting) childPkg.mExtras;
9608            if (ps != null) {
9609                removePackageLI(ps, chatty);
9610            }
9611        }
9612    }
9613
9614    void removePackageLI(PackageSetting ps, boolean chatty) {
9615        if (DEBUG_INSTALL) {
9616            if (chatty)
9617                Log.d(TAG, "Removing package " + ps.name);
9618        }
9619
9620        // writer
9621        synchronized (mPackages) {
9622            mPackages.remove(ps.name);
9623            final PackageParser.Package pkg = ps.pkg;
9624            if (pkg != null) {
9625                cleanPackageDataStructuresLILPw(pkg, chatty);
9626            }
9627        }
9628    }
9629
9630    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9631        if (DEBUG_INSTALL) {
9632            if (chatty)
9633                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9634        }
9635
9636        // writer
9637        synchronized (mPackages) {
9638            // Remove the parent package
9639            mPackages.remove(pkg.applicationInfo.packageName);
9640            cleanPackageDataStructuresLILPw(pkg, chatty);
9641
9642            // Remove the child packages
9643            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9644            for (int i = 0; i < childCount; i++) {
9645                PackageParser.Package childPkg = pkg.childPackages.get(i);
9646                mPackages.remove(childPkg.applicationInfo.packageName);
9647                cleanPackageDataStructuresLILPw(childPkg, chatty);
9648            }
9649        }
9650    }
9651
9652    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9653        int N = pkg.providers.size();
9654        StringBuilder r = null;
9655        int i;
9656        for (i=0; i<N; i++) {
9657            PackageParser.Provider p = pkg.providers.get(i);
9658            mProviders.removeProvider(p);
9659            if (p.info.authority == null) {
9660
9661                /* There was another ContentProvider with this authority when
9662                 * this app was installed so this authority is null,
9663                 * Ignore it as we don't have to unregister the provider.
9664                 */
9665                continue;
9666            }
9667            String names[] = p.info.authority.split(";");
9668            for (int j = 0; j < names.length; j++) {
9669                if (mProvidersByAuthority.get(names[j]) == p) {
9670                    mProvidersByAuthority.remove(names[j]);
9671                    if (DEBUG_REMOVE) {
9672                        if (chatty)
9673                            Log.d(TAG, "Unregistered content provider: " + names[j]
9674                                    + ", className = " + p.info.name + ", isSyncable = "
9675                                    + p.info.isSyncable);
9676                    }
9677                }
9678            }
9679            if (DEBUG_REMOVE && chatty) {
9680                if (r == null) {
9681                    r = new StringBuilder(256);
9682                } else {
9683                    r.append(' ');
9684                }
9685                r.append(p.info.name);
9686            }
9687        }
9688        if (r != null) {
9689            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9690        }
9691
9692        N = pkg.services.size();
9693        r = null;
9694        for (i=0; i<N; i++) {
9695            PackageParser.Service s = pkg.services.get(i);
9696            mServices.removeService(s);
9697            if (chatty) {
9698                if (r == null) {
9699                    r = new StringBuilder(256);
9700                } else {
9701                    r.append(' ');
9702                }
9703                r.append(s.info.name);
9704            }
9705        }
9706        if (r != null) {
9707            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9708        }
9709
9710        N = pkg.receivers.size();
9711        r = null;
9712        for (i=0; i<N; i++) {
9713            PackageParser.Activity a = pkg.receivers.get(i);
9714            mReceivers.removeActivity(a, "receiver");
9715            if (DEBUG_REMOVE && chatty) {
9716                if (r == null) {
9717                    r = new StringBuilder(256);
9718                } else {
9719                    r.append(' ');
9720                }
9721                r.append(a.info.name);
9722            }
9723        }
9724        if (r != null) {
9725            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9726        }
9727
9728        N = pkg.activities.size();
9729        r = null;
9730        for (i=0; i<N; i++) {
9731            PackageParser.Activity a = pkg.activities.get(i);
9732            mActivities.removeActivity(a, "activity");
9733            if (DEBUG_REMOVE && chatty) {
9734                if (r == null) {
9735                    r = new StringBuilder(256);
9736                } else {
9737                    r.append(' ');
9738                }
9739                r.append(a.info.name);
9740            }
9741        }
9742        if (r != null) {
9743            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9744        }
9745
9746        N = pkg.permissions.size();
9747        r = null;
9748        for (i=0; i<N; i++) {
9749            PackageParser.Permission p = pkg.permissions.get(i);
9750            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9751            if (bp == null) {
9752                bp = mSettings.mPermissionTrees.get(p.info.name);
9753            }
9754            if (bp != null && bp.perm == p) {
9755                bp.perm = null;
9756                if (DEBUG_REMOVE && chatty) {
9757                    if (r == null) {
9758                        r = new StringBuilder(256);
9759                    } else {
9760                        r.append(' ');
9761                    }
9762                    r.append(p.info.name);
9763                }
9764            }
9765            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9766                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9767                if (appOpPkgs != null) {
9768                    appOpPkgs.remove(pkg.packageName);
9769                }
9770            }
9771        }
9772        if (r != null) {
9773            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9774        }
9775
9776        N = pkg.requestedPermissions.size();
9777        r = null;
9778        for (i=0; i<N; i++) {
9779            String perm = pkg.requestedPermissions.get(i);
9780            BasePermission bp = mSettings.mPermissions.get(perm);
9781            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9782                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9783                if (appOpPkgs != null) {
9784                    appOpPkgs.remove(pkg.packageName);
9785                    if (appOpPkgs.isEmpty()) {
9786                        mAppOpPermissionPackages.remove(perm);
9787                    }
9788                }
9789            }
9790        }
9791        if (r != null) {
9792            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9793        }
9794
9795        N = pkg.instrumentation.size();
9796        r = null;
9797        for (i=0; i<N; i++) {
9798            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9799            mInstrumentation.remove(a.getComponentName());
9800            if (DEBUG_REMOVE && chatty) {
9801                if (r == null) {
9802                    r = new StringBuilder(256);
9803                } else {
9804                    r.append(' ');
9805                }
9806                r.append(a.info.name);
9807            }
9808        }
9809        if (r != null) {
9810            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9811        }
9812
9813        r = null;
9814        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9815            // Only system apps can hold shared libraries.
9816            if (pkg.libraryNames != null) {
9817                for (i=0; i<pkg.libraryNames.size(); i++) {
9818                    String name = pkg.libraryNames.get(i);
9819                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9820                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9821                        mSharedLibraries.remove(name);
9822                        if (DEBUG_REMOVE && chatty) {
9823                            if (r == null) {
9824                                r = new StringBuilder(256);
9825                            } else {
9826                                r.append(' ');
9827                            }
9828                            r.append(name);
9829                        }
9830                    }
9831                }
9832            }
9833        }
9834        if (r != null) {
9835            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9836        }
9837    }
9838
9839    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9840        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9841            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9842                return true;
9843            }
9844        }
9845        return false;
9846    }
9847
9848    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9849    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9850    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9851
9852    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9853        // Update the parent permissions
9854        updatePermissionsLPw(pkg.packageName, pkg, flags);
9855        // Update the child permissions
9856        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9857        for (int i = 0; i < childCount; i++) {
9858            PackageParser.Package childPkg = pkg.childPackages.get(i);
9859            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9860        }
9861    }
9862
9863    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9864            int flags) {
9865        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9866        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9867    }
9868
9869    private void updatePermissionsLPw(String changingPkg,
9870            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9871        // Make sure there are no dangling permission trees.
9872        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9873        while (it.hasNext()) {
9874            final BasePermission bp = it.next();
9875            if (bp.packageSetting == null) {
9876                // We may not yet have parsed the package, so just see if
9877                // we still know about its settings.
9878                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9879            }
9880            if (bp.packageSetting == null) {
9881                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9882                        + " from package " + bp.sourcePackage);
9883                it.remove();
9884            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9885                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9886                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9887                            + " from package " + bp.sourcePackage);
9888                    flags |= UPDATE_PERMISSIONS_ALL;
9889                    it.remove();
9890                }
9891            }
9892        }
9893
9894        // Make sure all dynamic permissions have been assigned to a package,
9895        // and make sure there are no dangling permissions.
9896        it = mSettings.mPermissions.values().iterator();
9897        while (it.hasNext()) {
9898            final BasePermission bp = it.next();
9899            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9900                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9901                        + bp.name + " pkg=" + bp.sourcePackage
9902                        + " info=" + bp.pendingInfo);
9903                if (bp.packageSetting == null && bp.pendingInfo != null) {
9904                    final BasePermission tree = findPermissionTreeLP(bp.name);
9905                    if (tree != null && tree.perm != null) {
9906                        bp.packageSetting = tree.packageSetting;
9907                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9908                                new PermissionInfo(bp.pendingInfo));
9909                        bp.perm.info.packageName = tree.perm.info.packageName;
9910                        bp.perm.info.name = bp.name;
9911                        bp.uid = tree.uid;
9912                    }
9913                }
9914            }
9915            if (bp.packageSetting == null) {
9916                // We may not yet have parsed the package, so just see if
9917                // we still know about its settings.
9918                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9919            }
9920            if (bp.packageSetting == null) {
9921                Slog.w(TAG, "Removing dangling permission: " + bp.name
9922                        + " from package " + bp.sourcePackage);
9923                it.remove();
9924            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9925                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9926                    Slog.i(TAG, "Removing old permission: " + bp.name
9927                            + " from package " + bp.sourcePackage);
9928                    flags |= UPDATE_PERMISSIONS_ALL;
9929                    it.remove();
9930                }
9931            }
9932        }
9933
9934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9935        // Now update the permissions for all packages, in particular
9936        // replace the granted permissions of the system packages.
9937        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9938            for (PackageParser.Package pkg : mPackages.values()) {
9939                if (pkg != pkgInfo) {
9940                    // Only replace for packages on requested volume
9941                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9942                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9943                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9944                    grantPermissionsLPw(pkg, replace, changingPkg);
9945                }
9946            }
9947        }
9948
9949        if (pkgInfo != null) {
9950            // Only replace for packages on requested volume
9951            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9952            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9953                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9954            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9955        }
9956        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9957    }
9958
9959    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9960            String packageOfInterest) {
9961        // IMPORTANT: There are two types of permissions: install and runtime.
9962        // Install time permissions are granted when the app is installed to
9963        // all device users and users added in the future. Runtime permissions
9964        // are granted at runtime explicitly to specific users. Normal and signature
9965        // protected permissions are install time permissions. Dangerous permissions
9966        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9967        // otherwise they are runtime permissions. This function does not manage
9968        // runtime permissions except for the case an app targeting Lollipop MR1
9969        // being upgraded to target a newer SDK, in which case dangerous permissions
9970        // are transformed from install time to runtime ones.
9971
9972        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9973        if (ps == null) {
9974            return;
9975        }
9976
9977        PermissionsState permissionsState = ps.getPermissionsState();
9978        PermissionsState origPermissions = permissionsState;
9979
9980        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9981
9982        boolean runtimePermissionsRevoked = false;
9983        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9984
9985        boolean changedInstallPermission = false;
9986
9987        if (replace) {
9988            ps.installPermissionsFixed = false;
9989            if (!ps.isSharedUser()) {
9990                origPermissions = new PermissionsState(permissionsState);
9991                permissionsState.reset();
9992            } else {
9993                // We need to know only about runtime permission changes since the
9994                // calling code always writes the install permissions state but
9995                // the runtime ones are written only if changed. The only cases of
9996                // changed runtime permissions here are promotion of an install to
9997                // runtime and revocation of a runtime from a shared user.
9998                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9999                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10000                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10001                    runtimePermissionsRevoked = true;
10002                }
10003            }
10004        }
10005
10006        permissionsState.setGlobalGids(mGlobalGids);
10007
10008        final int N = pkg.requestedPermissions.size();
10009        for (int i=0; i<N; i++) {
10010            final String name = pkg.requestedPermissions.get(i);
10011            final BasePermission bp = mSettings.mPermissions.get(name);
10012
10013            if (DEBUG_INSTALL) {
10014                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10015            }
10016
10017            if (bp == null || bp.packageSetting == null) {
10018                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10019                    Slog.w(TAG, "Unknown permission " + name
10020                            + " in package " + pkg.packageName);
10021                }
10022                continue;
10023            }
10024
10025            final String perm = bp.name;
10026            boolean allowedSig = false;
10027            int grant = GRANT_DENIED;
10028
10029            // Keep track of app op permissions.
10030            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10031                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10032                if (pkgs == null) {
10033                    pkgs = new ArraySet<>();
10034                    mAppOpPermissionPackages.put(bp.name, pkgs);
10035                }
10036                pkgs.add(pkg.packageName);
10037            }
10038
10039            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10040            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10041                    >= Build.VERSION_CODES.M;
10042            switch (level) {
10043                case PermissionInfo.PROTECTION_NORMAL: {
10044                    // For all apps normal permissions are install time ones.
10045                    grant = GRANT_INSTALL;
10046                } break;
10047
10048                case PermissionInfo.PROTECTION_DANGEROUS: {
10049                    // If a permission review is required for legacy apps we represent
10050                    // their permissions as always granted runtime ones since we need
10051                    // to keep the review required permission flag per user while an
10052                    // install permission's state is shared across all users.
10053                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10054                        // For legacy apps dangerous permissions are install time ones.
10055                        grant = GRANT_INSTALL;
10056                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10057                        // For legacy apps that became modern, install becomes runtime.
10058                        grant = GRANT_UPGRADE;
10059                    } else if (mPromoteSystemApps
10060                            && isSystemApp(ps)
10061                            && mExistingSystemPackages.contains(ps.name)) {
10062                        // For legacy system apps, install becomes runtime.
10063                        // We cannot check hasInstallPermission() for system apps since those
10064                        // permissions were granted implicitly and not persisted pre-M.
10065                        grant = GRANT_UPGRADE;
10066                    } else {
10067                        // For modern apps keep runtime permissions unchanged.
10068                        grant = GRANT_RUNTIME;
10069                    }
10070                } break;
10071
10072                case PermissionInfo.PROTECTION_SIGNATURE: {
10073                    // For all apps signature permissions are install time ones.
10074                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10075                    if (allowedSig) {
10076                        grant = GRANT_INSTALL;
10077                    }
10078                } break;
10079            }
10080
10081            if (DEBUG_INSTALL) {
10082                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10083            }
10084
10085            if (grant != GRANT_DENIED) {
10086                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10087                    // If this is an existing, non-system package, then
10088                    // we can't add any new permissions to it.
10089                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10090                        // Except...  if this is a permission that was added
10091                        // to the platform (note: need to only do this when
10092                        // updating the platform).
10093                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10094                            grant = GRANT_DENIED;
10095                        }
10096                    }
10097                }
10098
10099                switch (grant) {
10100                    case GRANT_INSTALL: {
10101                        // Revoke this as runtime permission to handle the case of
10102                        // a runtime permission being downgraded to an install one.
10103                        // Also in permission review mode we keep dangerous permissions
10104                        // for legacy apps
10105                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10106                            if (origPermissions.getRuntimePermissionState(
10107                                    bp.name, userId) != null) {
10108                                // Revoke the runtime permission and clear the flags.
10109                                origPermissions.revokeRuntimePermission(bp, userId);
10110                                origPermissions.updatePermissionFlags(bp, userId,
10111                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10112                                // If we revoked a permission permission, we have to write.
10113                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10114                                        changedRuntimePermissionUserIds, userId);
10115                            }
10116                        }
10117                        // Grant an install permission.
10118                        if (permissionsState.grantInstallPermission(bp) !=
10119                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10120                            changedInstallPermission = true;
10121                        }
10122                    } break;
10123
10124                    case GRANT_RUNTIME: {
10125                        // Grant previously granted runtime permissions.
10126                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10127                            PermissionState permissionState = origPermissions
10128                                    .getRuntimePermissionState(bp.name, userId);
10129                            int flags = permissionState != null
10130                                    ? permissionState.getFlags() : 0;
10131                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10132                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10133                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10134                                    // If we cannot put the permission as it was, we have to write.
10135                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10136                                            changedRuntimePermissionUserIds, userId);
10137                                }
10138                                // If the app supports runtime permissions no need for a review.
10139                                if (mPermissionReviewRequired
10140                                        && appSupportsRuntimePermissions
10141                                        && (flags & PackageManager
10142                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10143                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10144                                    // Since we changed the flags, we have to write.
10145                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10146                                            changedRuntimePermissionUserIds, userId);
10147                                }
10148                            } else if (mPermissionReviewRequired
10149                                    && !appSupportsRuntimePermissions) {
10150                                // For legacy apps that need a permission review, every new
10151                                // runtime permission is granted but it is pending a review.
10152                                // We also need to review only platform defined runtime
10153                                // permissions as these are the only ones the platform knows
10154                                // how to disable the API to simulate revocation as legacy
10155                                // apps don't expect to run with revoked permissions.
10156                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10157                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10158                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10159                                        // We changed the flags, hence have to write.
10160                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10161                                                changedRuntimePermissionUserIds, userId);
10162                                    }
10163                                }
10164                                if (permissionsState.grantRuntimePermission(bp, userId)
10165                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10166                                    // We changed the permission, hence have to write.
10167                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10168                                            changedRuntimePermissionUserIds, userId);
10169                                }
10170                            }
10171                            // Propagate the permission flags.
10172                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10173                        }
10174                    } break;
10175
10176                    case GRANT_UPGRADE: {
10177                        // Grant runtime permissions for a previously held install permission.
10178                        PermissionState permissionState = origPermissions
10179                                .getInstallPermissionState(bp.name);
10180                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10181
10182                        if (origPermissions.revokeInstallPermission(bp)
10183                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10184                            // We will be transferring the permission flags, so clear them.
10185                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10186                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10187                            changedInstallPermission = true;
10188                        }
10189
10190                        // If the permission is not to be promoted to runtime we ignore it and
10191                        // also its other flags as they are not applicable to install permissions.
10192                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10193                            for (int userId : currentUserIds) {
10194                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10195                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10196                                    // Transfer the permission flags.
10197                                    permissionsState.updatePermissionFlags(bp, userId,
10198                                            flags, flags);
10199                                    // If we granted the permission, we have to write.
10200                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10201                                            changedRuntimePermissionUserIds, userId);
10202                                }
10203                            }
10204                        }
10205                    } break;
10206
10207                    default: {
10208                        if (packageOfInterest == null
10209                                || packageOfInterest.equals(pkg.packageName)) {
10210                            Slog.w(TAG, "Not granting permission " + perm
10211                                    + " to package " + pkg.packageName
10212                                    + " because it was previously installed without");
10213                        }
10214                    } break;
10215                }
10216            } else {
10217                if (permissionsState.revokeInstallPermission(bp) !=
10218                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10219                    // Also drop the permission flags.
10220                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10221                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10222                    changedInstallPermission = true;
10223                    Slog.i(TAG, "Un-granting permission " + perm
10224                            + " from package " + pkg.packageName
10225                            + " (protectionLevel=" + bp.protectionLevel
10226                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10227                            + ")");
10228                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10229                    // Don't print warning for app op permissions, since it is fine for them
10230                    // not to be granted, there is a UI for the user to decide.
10231                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10232                        Slog.w(TAG, "Not granting permission " + perm
10233                                + " to package " + pkg.packageName
10234                                + " (protectionLevel=" + bp.protectionLevel
10235                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10236                                + ")");
10237                    }
10238                }
10239            }
10240        }
10241
10242        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10243                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10244            // This is the first that we have heard about this package, so the
10245            // permissions we have now selected are fixed until explicitly
10246            // changed.
10247            ps.installPermissionsFixed = true;
10248        }
10249
10250        // Persist the runtime permissions state for users with changes. If permissions
10251        // were revoked because no app in the shared user declares them we have to
10252        // write synchronously to avoid losing runtime permissions state.
10253        for (int userId : changedRuntimePermissionUserIds) {
10254            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10255        }
10256    }
10257
10258    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10259        boolean allowed = false;
10260        final int NP = PackageParser.NEW_PERMISSIONS.length;
10261        for (int ip=0; ip<NP; ip++) {
10262            final PackageParser.NewPermissionInfo npi
10263                    = PackageParser.NEW_PERMISSIONS[ip];
10264            if (npi.name.equals(perm)
10265                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10266                allowed = true;
10267                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10268                        + pkg.packageName);
10269                break;
10270            }
10271        }
10272        return allowed;
10273    }
10274
10275    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10276            BasePermission bp, PermissionsState origPermissions) {
10277        boolean allowed;
10278        allowed = (compareSignatures(
10279                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10280                        == PackageManager.SIGNATURE_MATCH)
10281                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10282                        == PackageManager.SIGNATURE_MATCH);
10283        if (!allowed && (bp.protectionLevel
10284                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10285            if (isSystemApp(pkg)) {
10286                // For updated system applications, a system permission
10287                // is granted only if it had been defined by the original application.
10288                if (pkg.isUpdatedSystemApp()) {
10289                    final PackageSetting sysPs = mSettings
10290                            .getDisabledSystemPkgLPr(pkg.packageName);
10291                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10292                        // If the original was granted this permission, we take
10293                        // that grant decision as read and propagate it to the
10294                        // update.
10295                        if (sysPs.isPrivileged()) {
10296                            allowed = true;
10297                        }
10298                    } else {
10299                        // The system apk may have been updated with an older
10300                        // version of the one on the data partition, but which
10301                        // granted a new system permission that it didn't have
10302                        // before.  In this case we do want to allow the app to
10303                        // now get the new permission if the ancestral apk is
10304                        // privileged to get it.
10305                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10306                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10307                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10308                                    allowed = true;
10309                                    break;
10310                                }
10311                            }
10312                        }
10313                        // Also if a privileged parent package on the system image or any of
10314                        // its children requested a privileged permission, the updated child
10315                        // packages can also get the permission.
10316                        if (pkg.parentPackage != null) {
10317                            final PackageSetting disabledSysParentPs = mSettings
10318                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10319                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10320                                    && disabledSysParentPs.isPrivileged()) {
10321                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10322                                    allowed = true;
10323                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10324                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10325                                    for (int i = 0; i < count; i++) {
10326                                        PackageParser.Package disabledSysChildPkg =
10327                                                disabledSysParentPs.pkg.childPackages.get(i);
10328                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10329                                                perm)) {
10330                                            allowed = true;
10331                                            break;
10332                                        }
10333                                    }
10334                                }
10335                            }
10336                        }
10337                    }
10338                } else {
10339                    allowed = isPrivilegedApp(pkg);
10340                }
10341            }
10342        }
10343        if (!allowed) {
10344            if (!allowed && (bp.protectionLevel
10345                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10346                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10347                // If this was a previously normal/dangerous permission that got moved
10348                // to a system permission as part of the runtime permission redesign, then
10349                // we still want to blindly grant it to old apps.
10350                allowed = true;
10351            }
10352            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10353                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10354                // If this permission is to be granted to the system installer and
10355                // this app is an installer, then it gets the permission.
10356                allowed = true;
10357            }
10358            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10359                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10360                // If this permission is to be granted to the system verifier and
10361                // this app is a verifier, then it gets the permission.
10362                allowed = true;
10363            }
10364            if (!allowed && (bp.protectionLevel
10365                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10366                    && isSystemApp(pkg)) {
10367                // Any pre-installed system app is allowed to get this permission.
10368                allowed = true;
10369            }
10370            if (!allowed && (bp.protectionLevel
10371                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10372                // For development permissions, a development permission
10373                // is granted only if it was already granted.
10374                allowed = origPermissions.hasInstallPermission(perm);
10375            }
10376            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10377                    && pkg.packageName.equals(mSetupWizardPackage)) {
10378                // If this permission is to be granted to the system setup wizard and
10379                // this app is a setup wizard, then it gets the permission.
10380                allowed = true;
10381            }
10382        }
10383        return allowed;
10384    }
10385
10386    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10387        final int permCount = pkg.requestedPermissions.size();
10388        for (int j = 0; j < permCount; j++) {
10389            String requestedPermission = pkg.requestedPermissions.get(j);
10390            if (permission.equals(requestedPermission)) {
10391                return true;
10392            }
10393        }
10394        return false;
10395    }
10396
10397    final class ActivityIntentResolver
10398            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10399        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10400                boolean defaultOnly, int userId) {
10401            if (!sUserManager.exists(userId)) return null;
10402            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10403            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10404        }
10405
10406        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10407                int userId) {
10408            if (!sUserManager.exists(userId)) return null;
10409            mFlags = flags;
10410            return super.queryIntent(intent, resolvedType,
10411                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10412        }
10413
10414        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10415                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10416            if (!sUserManager.exists(userId)) return null;
10417            if (packageActivities == null) {
10418                return null;
10419            }
10420            mFlags = flags;
10421            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10422            final int N = packageActivities.size();
10423            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10424                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10425
10426            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10427            for (int i = 0; i < N; ++i) {
10428                intentFilters = packageActivities.get(i).intents;
10429                if (intentFilters != null && intentFilters.size() > 0) {
10430                    PackageParser.ActivityIntentInfo[] array =
10431                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10432                    intentFilters.toArray(array);
10433                    listCut.add(array);
10434                }
10435            }
10436            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10437        }
10438
10439        /**
10440         * Finds a privileged activity that matches the specified activity names.
10441         */
10442        private PackageParser.Activity findMatchingActivity(
10443                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10444            for (PackageParser.Activity sysActivity : activityList) {
10445                if (sysActivity.info.name.equals(activityInfo.name)) {
10446                    return sysActivity;
10447                }
10448                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10449                    return sysActivity;
10450                }
10451                if (sysActivity.info.targetActivity != null) {
10452                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10453                        return sysActivity;
10454                    }
10455                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10456                        return sysActivity;
10457                    }
10458                }
10459            }
10460            return null;
10461        }
10462
10463        public class IterGenerator<E> {
10464            public Iterator<E> generate(ActivityIntentInfo info) {
10465                return null;
10466            }
10467        }
10468
10469        public class ActionIterGenerator extends IterGenerator<String> {
10470            @Override
10471            public Iterator<String> generate(ActivityIntentInfo info) {
10472                return info.actionsIterator();
10473            }
10474        }
10475
10476        public class CategoriesIterGenerator extends IterGenerator<String> {
10477            @Override
10478            public Iterator<String> generate(ActivityIntentInfo info) {
10479                return info.categoriesIterator();
10480            }
10481        }
10482
10483        public class SchemesIterGenerator extends IterGenerator<String> {
10484            @Override
10485            public Iterator<String> generate(ActivityIntentInfo info) {
10486                return info.schemesIterator();
10487            }
10488        }
10489
10490        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10491            @Override
10492            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10493                return info.authoritiesIterator();
10494            }
10495        }
10496
10497        /**
10498         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10499         * MODIFIED. Do not pass in a list that should not be changed.
10500         */
10501        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10502                IterGenerator<T> generator, Iterator<T> searchIterator) {
10503            // loop through the set of actions; every one must be found in the intent filter
10504            while (searchIterator.hasNext()) {
10505                // we must have at least one filter in the list to consider a match
10506                if (intentList.size() == 0) {
10507                    break;
10508                }
10509
10510                final T searchAction = searchIterator.next();
10511
10512                // loop through the set of intent filters
10513                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10514                while (intentIter.hasNext()) {
10515                    final ActivityIntentInfo intentInfo = intentIter.next();
10516                    boolean selectionFound = false;
10517
10518                    // loop through the intent filter's selection criteria; at least one
10519                    // of them must match the searched criteria
10520                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10521                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10522                        final T intentSelection = intentSelectionIter.next();
10523                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10524                            selectionFound = true;
10525                            break;
10526                        }
10527                    }
10528
10529                    // the selection criteria wasn't found in this filter's set; this filter
10530                    // is not a potential match
10531                    if (!selectionFound) {
10532                        intentIter.remove();
10533                    }
10534                }
10535            }
10536        }
10537
10538        private boolean isProtectedAction(ActivityIntentInfo filter) {
10539            final Iterator<String> actionsIter = filter.actionsIterator();
10540            while (actionsIter != null && actionsIter.hasNext()) {
10541                final String filterAction = actionsIter.next();
10542                if (PROTECTED_ACTIONS.contains(filterAction)) {
10543                    return true;
10544                }
10545            }
10546            return false;
10547        }
10548
10549        /**
10550         * Adjusts the priority of the given intent filter according to policy.
10551         * <p>
10552         * <ul>
10553         * <li>The priority for non privileged applications is capped to '0'</li>
10554         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10555         * <li>The priority for unbundled updates to privileged applications is capped to the
10556         *      priority defined on the system partition</li>
10557         * </ul>
10558         * <p>
10559         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10560         * allowed to obtain any priority on any action.
10561         */
10562        private void adjustPriority(
10563                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10564            // nothing to do; priority is fine as-is
10565            if (intent.getPriority() <= 0) {
10566                return;
10567            }
10568
10569            final ActivityInfo activityInfo = intent.activity.info;
10570            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10571
10572            final boolean privilegedApp =
10573                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10574            if (!privilegedApp) {
10575                // non-privileged applications can never define a priority >0
10576                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10577                        + " package: " + applicationInfo.packageName
10578                        + " activity: " + intent.activity.className
10579                        + " origPrio: " + intent.getPriority());
10580                intent.setPriority(0);
10581                return;
10582            }
10583
10584            if (systemActivities == null) {
10585                // the system package is not disabled; we're parsing the system partition
10586                if (isProtectedAction(intent)) {
10587                    if (mDeferProtectedFilters) {
10588                        // We can't deal with these just yet. No component should ever obtain a
10589                        // >0 priority for a protected actions, with ONE exception -- the setup
10590                        // wizard. The setup wizard, however, cannot be known until we're able to
10591                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10592                        // until all intent filters have been processed. Chicken, meet egg.
10593                        // Let the filter temporarily have a high priority and rectify the
10594                        // priorities after all system packages have been scanned.
10595                        mProtectedFilters.add(intent);
10596                        if (DEBUG_FILTERS) {
10597                            Slog.i(TAG, "Protected action; save for later;"
10598                                    + " package: " + applicationInfo.packageName
10599                                    + " activity: " + intent.activity.className
10600                                    + " origPrio: " + intent.getPriority());
10601                        }
10602                        return;
10603                    } else {
10604                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10605                            Slog.i(TAG, "No setup wizard;"
10606                                + " All protected intents capped to priority 0");
10607                        }
10608                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10609                            if (DEBUG_FILTERS) {
10610                                Slog.i(TAG, "Found setup wizard;"
10611                                    + " allow priority " + intent.getPriority() + ";"
10612                                    + " package: " + intent.activity.info.packageName
10613                                    + " activity: " + intent.activity.className
10614                                    + " priority: " + intent.getPriority());
10615                            }
10616                            // setup wizard gets whatever it wants
10617                            return;
10618                        }
10619                        Slog.w(TAG, "Protected action; cap priority to 0;"
10620                                + " package: " + intent.activity.info.packageName
10621                                + " activity: " + intent.activity.className
10622                                + " origPrio: " + intent.getPriority());
10623                        intent.setPriority(0);
10624                        return;
10625                    }
10626                }
10627                // privileged apps on the system image get whatever priority they request
10628                return;
10629            }
10630
10631            // privileged app unbundled update ... try to find the same activity
10632            final PackageParser.Activity foundActivity =
10633                    findMatchingActivity(systemActivities, activityInfo);
10634            if (foundActivity == null) {
10635                // this is a new activity; it cannot obtain >0 priority
10636                if (DEBUG_FILTERS) {
10637                    Slog.i(TAG, "New activity; cap priority to 0;"
10638                            + " package: " + applicationInfo.packageName
10639                            + " activity: " + intent.activity.className
10640                            + " origPrio: " + intent.getPriority());
10641                }
10642                intent.setPriority(0);
10643                return;
10644            }
10645
10646            // found activity, now check for filter equivalence
10647
10648            // a shallow copy is enough; we modify the list, not its contents
10649            final List<ActivityIntentInfo> intentListCopy =
10650                    new ArrayList<>(foundActivity.intents);
10651            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10652
10653            // find matching action subsets
10654            final Iterator<String> actionsIterator = intent.actionsIterator();
10655            if (actionsIterator != null) {
10656                getIntentListSubset(
10657                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10658                if (intentListCopy.size() == 0) {
10659                    // no more intents to match; we're not equivalent
10660                    if (DEBUG_FILTERS) {
10661                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10662                                + " package: " + applicationInfo.packageName
10663                                + " activity: " + intent.activity.className
10664                                + " origPrio: " + intent.getPriority());
10665                    }
10666                    intent.setPriority(0);
10667                    return;
10668                }
10669            }
10670
10671            // find matching category subsets
10672            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10673            if (categoriesIterator != null) {
10674                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10675                        categoriesIterator);
10676                if (intentListCopy.size() == 0) {
10677                    // no more intents to match; we're not equivalent
10678                    if (DEBUG_FILTERS) {
10679                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10680                                + " package: " + applicationInfo.packageName
10681                                + " activity: " + intent.activity.className
10682                                + " origPrio: " + intent.getPriority());
10683                    }
10684                    intent.setPriority(0);
10685                    return;
10686                }
10687            }
10688
10689            // find matching schemes subsets
10690            final Iterator<String> schemesIterator = intent.schemesIterator();
10691            if (schemesIterator != null) {
10692                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10693                        schemesIterator);
10694                if (intentListCopy.size() == 0) {
10695                    // no more intents to match; we're not equivalent
10696                    if (DEBUG_FILTERS) {
10697                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10698                                + " package: " + applicationInfo.packageName
10699                                + " activity: " + intent.activity.className
10700                                + " origPrio: " + intent.getPriority());
10701                    }
10702                    intent.setPriority(0);
10703                    return;
10704                }
10705            }
10706
10707            // find matching authorities subsets
10708            final Iterator<IntentFilter.AuthorityEntry>
10709                    authoritiesIterator = intent.authoritiesIterator();
10710            if (authoritiesIterator != null) {
10711                getIntentListSubset(intentListCopy,
10712                        new AuthoritiesIterGenerator(),
10713                        authoritiesIterator);
10714                if (intentListCopy.size() == 0) {
10715                    // no more intents to match; we're not equivalent
10716                    if (DEBUG_FILTERS) {
10717                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10718                                + " package: " + applicationInfo.packageName
10719                                + " activity: " + intent.activity.className
10720                                + " origPrio: " + intent.getPriority());
10721                    }
10722                    intent.setPriority(0);
10723                    return;
10724                }
10725            }
10726
10727            // we found matching filter(s); app gets the max priority of all intents
10728            int cappedPriority = 0;
10729            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10730                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10731            }
10732            if (intent.getPriority() > cappedPriority) {
10733                if (DEBUG_FILTERS) {
10734                    Slog.i(TAG, "Found matching filter(s);"
10735                            + " cap priority to " + cappedPriority + ";"
10736                            + " package: " + applicationInfo.packageName
10737                            + " activity: " + intent.activity.className
10738                            + " origPrio: " + intent.getPriority());
10739                }
10740                intent.setPriority(cappedPriority);
10741                return;
10742            }
10743            // all this for nothing; the requested priority was <= what was on the system
10744        }
10745
10746        public final void addActivity(PackageParser.Activity a, String type) {
10747            mActivities.put(a.getComponentName(), a);
10748            if (DEBUG_SHOW_INFO)
10749                Log.v(
10750                TAG, "  " + type + " " +
10751                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10752            if (DEBUG_SHOW_INFO)
10753                Log.v(TAG, "    Class=" + a.info.name);
10754            final int NI = a.intents.size();
10755            for (int j=0; j<NI; j++) {
10756                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10757                if ("activity".equals(type)) {
10758                    final PackageSetting ps =
10759                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10760                    final List<PackageParser.Activity> systemActivities =
10761                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10762                    adjustPriority(systemActivities, intent);
10763                }
10764                if (DEBUG_SHOW_INFO) {
10765                    Log.v(TAG, "    IntentFilter:");
10766                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10767                }
10768                if (!intent.debugCheck()) {
10769                    Log.w(TAG, "==> For Activity " + a.info.name);
10770                }
10771                addFilter(intent);
10772            }
10773        }
10774
10775        public final void removeActivity(PackageParser.Activity a, String type) {
10776            mActivities.remove(a.getComponentName());
10777            if (DEBUG_SHOW_INFO) {
10778                Log.v(TAG, "  " + type + " "
10779                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10780                                : a.info.name) + ":");
10781                Log.v(TAG, "    Class=" + a.info.name);
10782            }
10783            final int NI = a.intents.size();
10784            for (int j=0; j<NI; j++) {
10785                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10786                if (DEBUG_SHOW_INFO) {
10787                    Log.v(TAG, "    IntentFilter:");
10788                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10789                }
10790                removeFilter(intent);
10791            }
10792        }
10793
10794        @Override
10795        protected boolean allowFilterResult(
10796                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10797            ActivityInfo filterAi = filter.activity.info;
10798            for (int i=dest.size()-1; i>=0; i--) {
10799                ActivityInfo destAi = dest.get(i).activityInfo;
10800                if (destAi.name == filterAi.name
10801                        && destAi.packageName == filterAi.packageName) {
10802                    return false;
10803                }
10804            }
10805            return true;
10806        }
10807
10808        @Override
10809        protected ActivityIntentInfo[] newArray(int size) {
10810            return new ActivityIntentInfo[size];
10811        }
10812
10813        @Override
10814        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10815            if (!sUserManager.exists(userId)) return true;
10816            PackageParser.Package p = filter.activity.owner;
10817            if (p != null) {
10818                PackageSetting ps = (PackageSetting)p.mExtras;
10819                if (ps != null) {
10820                    // System apps are never considered stopped for purposes of
10821                    // filtering, because there may be no way for the user to
10822                    // actually re-launch them.
10823                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10824                            && ps.getStopped(userId);
10825                }
10826            }
10827            return false;
10828        }
10829
10830        @Override
10831        protected boolean isPackageForFilter(String packageName,
10832                PackageParser.ActivityIntentInfo info) {
10833            return packageName.equals(info.activity.owner.packageName);
10834        }
10835
10836        @Override
10837        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10838                int match, int userId) {
10839            if (!sUserManager.exists(userId)) return null;
10840            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10841                return null;
10842            }
10843            final PackageParser.Activity activity = info.activity;
10844            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10845            if (ps == null) {
10846                return null;
10847            }
10848            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10849                    ps.readUserState(userId), userId);
10850            if (ai == null) {
10851                return null;
10852            }
10853            final ResolveInfo res = new ResolveInfo();
10854            res.activityInfo = ai;
10855            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10856                res.filter = info;
10857            }
10858            if (info != null) {
10859                res.handleAllWebDataURI = info.handleAllWebDataURI();
10860            }
10861            res.priority = info.getPriority();
10862            res.preferredOrder = activity.owner.mPreferredOrder;
10863            //System.out.println("Result: " + res.activityInfo.className +
10864            //                   " = " + res.priority);
10865            res.match = match;
10866            res.isDefault = info.hasDefault;
10867            res.labelRes = info.labelRes;
10868            res.nonLocalizedLabel = info.nonLocalizedLabel;
10869            if (userNeedsBadging(userId)) {
10870                res.noResourceId = true;
10871            } else {
10872                res.icon = info.icon;
10873            }
10874            res.iconResourceId = info.icon;
10875            res.system = res.activityInfo.applicationInfo.isSystemApp();
10876            return res;
10877        }
10878
10879        @Override
10880        protected void sortResults(List<ResolveInfo> results) {
10881            Collections.sort(results, mResolvePrioritySorter);
10882        }
10883
10884        @Override
10885        protected void dumpFilter(PrintWriter out, String prefix,
10886                PackageParser.ActivityIntentInfo filter) {
10887            out.print(prefix); out.print(
10888                    Integer.toHexString(System.identityHashCode(filter.activity)));
10889                    out.print(' ');
10890                    filter.activity.printComponentShortName(out);
10891                    out.print(" filter ");
10892                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10893        }
10894
10895        @Override
10896        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10897            return filter.activity;
10898        }
10899
10900        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10901            PackageParser.Activity activity = (PackageParser.Activity)label;
10902            out.print(prefix); out.print(
10903                    Integer.toHexString(System.identityHashCode(activity)));
10904                    out.print(' ');
10905                    activity.printComponentShortName(out);
10906            if (count > 1) {
10907                out.print(" ("); out.print(count); out.print(" filters)");
10908            }
10909            out.println();
10910        }
10911
10912        // Keys are String (activity class name), values are Activity.
10913        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10914                = new ArrayMap<ComponentName, PackageParser.Activity>();
10915        private int mFlags;
10916    }
10917
10918    private final class ServiceIntentResolver
10919            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10920        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10921                boolean defaultOnly, int userId) {
10922            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10923            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10924        }
10925
10926        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10927                int userId) {
10928            if (!sUserManager.exists(userId)) return null;
10929            mFlags = flags;
10930            return super.queryIntent(intent, resolvedType,
10931                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10932        }
10933
10934        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10935                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10936            if (!sUserManager.exists(userId)) return null;
10937            if (packageServices == null) {
10938                return null;
10939            }
10940            mFlags = flags;
10941            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10942            final int N = packageServices.size();
10943            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10944                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10945
10946            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10947            for (int i = 0; i < N; ++i) {
10948                intentFilters = packageServices.get(i).intents;
10949                if (intentFilters != null && intentFilters.size() > 0) {
10950                    PackageParser.ServiceIntentInfo[] array =
10951                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10952                    intentFilters.toArray(array);
10953                    listCut.add(array);
10954                }
10955            }
10956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10957        }
10958
10959        public final void addService(PackageParser.Service s) {
10960            mServices.put(s.getComponentName(), s);
10961            if (DEBUG_SHOW_INFO) {
10962                Log.v(TAG, "  "
10963                        + (s.info.nonLocalizedLabel != null
10964                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10965                Log.v(TAG, "    Class=" + s.info.name);
10966            }
10967            final int NI = s.intents.size();
10968            int j;
10969            for (j=0; j<NI; j++) {
10970                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10971                if (DEBUG_SHOW_INFO) {
10972                    Log.v(TAG, "    IntentFilter:");
10973                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10974                }
10975                if (!intent.debugCheck()) {
10976                    Log.w(TAG, "==> For Service " + s.info.name);
10977                }
10978                addFilter(intent);
10979            }
10980        }
10981
10982        public final void removeService(PackageParser.Service s) {
10983            mServices.remove(s.getComponentName());
10984            if (DEBUG_SHOW_INFO) {
10985                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10986                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10987                Log.v(TAG, "    Class=" + s.info.name);
10988            }
10989            final int NI = s.intents.size();
10990            int j;
10991            for (j=0; j<NI; j++) {
10992                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10993                if (DEBUG_SHOW_INFO) {
10994                    Log.v(TAG, "    IntentFilter:");
10995                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10996                }
10997                removeFilter(intent);
10998            }
10999        }
11000
11001        @Override
11002        protected boolean allowFilterResult(
11003                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11004            ServiceInfo filterSi = filter.service.info;
11005            for (int i=dest.size()-1; i>=0; i--) {
11006                ServiceInfo destAi = dest.get(i).serviceInfo;
11007                if (destAi.name == filterSi.name
11008                        && destAi.packageName == filterSi.packageName) {
11009                    return false;
11010                }
11011            }
11012            return true;
11013        }
11014
11015        @Override
11016        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11017            return new PackageParser.ServiceIntentInfo[size];
11018        }
11019
11020        @Override
11021        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11022            if (!sUserManager.exists(userId)) return true;
11023            PackageParser.Package p = filter.service.owner;
11024            if (p != null) {
11025                PackageSetting ps = (PackageSetting)p.mExtras;
11026                if (ps != null) {
11027                    // System apps are never considered stopped for purposes of
11028                    // filtering, because there may be no way for the user to
11029                    // actually re-launch them.
11030                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11031                            && ps.getStopped(userId);
11032                }
11033            }
11034            return false;
11035        }
11036
11037        @Override
11038        protected boolean isPackageForFilter(String packageName,
11039                PackageParser.ServiceIntentInfo info) {
11040            return packageName.equals(info.service.owner.packageName);
11041        }
11042
11043        @Override
11044        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11045                int match, int userId) {
11046            if (!sUserManager.exists(userId)) return null;
11047            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11048            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11049                return null;
11050            }
11051            final PackageParser.Service service = info.service;
11052            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11053            if (ps == null) {
11054                return null;
11055            }
11056            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11057                    ps.readUserState(userId), userId);
11058            if (si == null) {
11059                return null;
11060            }
11061            final ResolveInfo res = new ResolveInfo();
11062            res.serviceInfo = si;
11063            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11064                res.filter = filter;
11065            }
11066            res.priority = info.getPriority();
11067            res.preferredOrder = service.owner.mPreferredOrder;
11068            res.match = match;
11069            res.isDefault = info.hasDefault;
11070            res.labelRes = info.labelRes;
11071            res.nonLocalizedLabel = info.nonLocalizedLabel;
11072            res.icon = info.icon;
11073            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11074            return res;
11075        }
11076
11077        @Override
11078        protected void sortResults(List<ResolveInfo> results) {
11079            Collections.sort(results, mResolvePrioritySorter);
11080        }
11081
11082        @Override
11083        protected void dumpFilter(PrintWriter out, String prefix,
11084                PackageParser.ServiceIntentInfo filter) {
11085            out.print(prefix); out.print(
11086                    Integer.toHexString(System.identityHashCode(filter.service)));
11087                    out.print(' ');
11088                    filter.service.printComponentShortName(out);
11089                    out.print(" filter ");
11090                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11091        }
11092
11093        @Override
11094        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11095            return filter.service;
11096        }
11097
11098        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11099            PackageParser.Service service = (PackageParser.Service)label;
11100            out.print(prefix); out.print(
11101                    Integer.toHexString(System.identityHashCode(service)));
11102                    out.print(' ');
11103                    service.printComponentShortName(out);
11104            if (count > 1) {
11105                out.print(" ("); out.print(count); out.print(" filters)");
11106            }
11107            out.println();
11108        }
11109
11110//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11111//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11112//            final List<ResolveInfo> retList = Lists.newArrayList();
11113//            while (i.hasNext()) {
11114//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11115//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11116//                    retList.add(resolveInfo);
11117//                }
11118//            }
11119//            return retList;
11120//        }
11121
11122        // Keys are String (activity class name), values are Activity.
11123        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11124                = new ArrayMap<ComponentName, PackageParser.Service>();
11125        private int mFlags;
11126    };
11127
11128    private final class ProviderIntentResolver
11129            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11130        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11131                boolean defaultOnly, int userId) {
11132            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11133            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11134        }
11135
11136        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11137                int userId) {
11138            if (!sUserManager.exists(userId))
11139                return null;
11140            mFlags = flags;
11141            return super.queryIntent(intent, resolvedType,
11142                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11143        }
11144
11145        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11146                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11147            if (!sUserManager.exists(userId))
11148                return null;
11149            if (packageProviders == null) {
11150                return null;
11151            }
11152            mFlags = flags;
11153            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11154            final int N = packageProviders.size();
11155            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11156                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11157
11158            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11159            for (int i = 0; i < N; ++i) {
11160                intentFilters = packageProviders.get(i).intents;
11161                if (intentFilters != null && intentFilters.size() > 0) {
11162                    PackageParser.ProviderIntentInfo[] array =
11163                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11164                    intentFilters.toArray(array);
11165                    listCut.add(array);
11166                }
11167            }
11168            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11169        }
11170
11171        public final void addProvider(PackageParser.Provider p) {
11172            if (mProviders.containsKey(p.getComponentName())) {
11173                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11174                return;
11175            }
11176
11177            mProviders.put(p.getComponentName(), p);
11178            if (DEBUG_SHOW_INFO) {
11179                Log.v(TAG, "  "
11180                        + (p.info.nonLocalizedLabel != null
11181                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11182                Log.v(TAG, "    Class=" + p.info.name);
11183            }
11184            final int NI = p.intents.size();
11185            int j;
11186            for (j = 0; j < NI; j++) {
11187                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11188                if (DEBUG_SHOW_INFO) {
11189                    Log.v(TAG, "    IntentFilter:");
11190                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11191                }
11192                if (!intent.debugCheck()) {
11193                    Log.w(TAG, "==> For Provider " + p.info.name);
11194                }
11195                addFilter(intent);
11196            }
11197        }
11198
11199        public final void removeProvider(PackageParser.Provider p) {
11200            mProviders.remove(p.getComponentName());
11201            if (DEBUG_SHOW_INFO) {
11202                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11203                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11204                Log.v(TAG, "    Class=" + p.info.name);
11205            }
11206            final int NI = p.intents.size();
11207            int j;
11208            for (j = 0; j < NI; j++) {
11209                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11210                if (DEBUG_SHOW_INFO) {
11211                    Log.v(TAG, "    IntentFilter:");
11212                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11213                }
11214                removeFilter(intent);
11215            }
11216        }
11217
11218        @Override
11219        protected boolean allowFilterResult(
11220                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11221            ProviderInfo filterPi = filter.provider.info;
11222            for (int i = dest.size() - 1; i >= 0; i--) {
11223                ProviderInfo destPi = dest.get(i).providerInfo;
11224                if (destPi.name == filterPi.name
11225                        && destPi.packageName == filterPi.packageName) {
11226                    return false;
11227                }
11228            }
11229            return true;
11230        }
11231
11232        @Override
11233        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11234            return new PackageParser.ProviderIntentInfo[size];
11235        }
11236
11237        @Override
11238        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11239            if (!sUserManager.exists(userId))
11240                return true;
11241            PackageParser.Package p = filter.provider.owner;
11242            if (p != null) {
11243                PackageSetting ps = (PackageSetting) p.mExtras;
11244                if (ps != null) {
11245                    // System apps are never considered stopped for purposes of
11246                    // filtering, because there may be no way for the user to
11247                    // actually re-launch them.
11248                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11249                            && ps.getStopped(userId);
11250                }
11251            }
11252            return false;
11253        }
11254
11255        @Override
11256        protected boolean isPackageForFilter(String packageName,
11257                PackageParser.ProviderIntentInfo info) {
11258            return packageName.equals(info.provider.owner.packageName);
11259        }
11260
11261        @Override
11262        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11263                int match, int userId) {
11264            if (!sUserManager.exists(userId))
11265                return null;
11266            final PackageParser.ProviderIntentInfo info = filter;
11267            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11268                return null;
11269            }
11270            final PackageParser.Provider provider = info.provider;
11271            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11272            if (ps == null) {
11273                return null;
11274            }
11275            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11276                    ps.readUserState(userId), userId);
11277            if (pi == null) {
11278                return null;
11279            }
11280            final ResolveInfo res = new ResolveInfo();
11281            res.providerInfo = pi;
11282            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11283                res.filter = filter;
11284            }
11285            res.priority = info.getPriority();
11286            res.preferredOrder = provider.owner.mPreferredOrder;
11287            res.match = match;
11288            res.isDefault = info.hasDefault;
11289            res.labelRes = info.labelRes;
11290            res.nonLocalizedLabel = info.nonLocalizedLabel;
11291            res.icon = info.icon;
11292            res.system = res.providerInfo.applicationInfo.isSystemApp();
11293            return res;
11294        }
11295
11296        @Override
11297        protected void sortResults(List<ResolveInfo> results) {
11298            Collections.sort(results, mResolvePrioritySorter);
11299        }
11300
11301        @Override
11302        protected void dumpFilter(PrintWriter out, String prefix,
11303                PackageParser.ProviderIntentInfo filter) {
11304            out.print(prefix);
11305            out.print(
11306                    Integer.toHexString(System.identityHashCode(filter.provider)));
11307            out.print(' ');
11308            filter.provider.printComponentShortName(out);
11309            out.print(" filter ");
11310            out.println(Integer.toHexString(System.identityHashCode(filter)));
11311        }
11312
11313        @Override
11314        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11315            return filter.provider;
11316        }
11317
11318        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11319            PackageParser.Provider provider = (PackageParser.Provider)label;
11320            out.print(prefix); out.print(
11321                    Integer.toHexString(System.identityHashCode(provider)));
11322                    out.print(' ');
11323                    provider.printComponentShortName(out);
11324            if (count > 1) {
11325                out.print(" ("); out.print(count); out.print(" filters)");
11326            }
11327            out.println();
11328        }
11329
11330        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11331                = new ArrayMap<ComponentName, PackageParser.Provider>();
11332        private int mFlags;
11333    }
11334
11335    private static final class EphemeralIntentResolver
11336            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11337        /**
11338         * The result that has the highest defined order. Ordering applies on a
11339         * per-package basis. Mapping is from package name to Pair of order and
11340         * EphemeralResolveInfo.
11341         * <p>
11342         * NOTE: This is implemented as a field variable for convenience and efficiency.
11343         * By having a field variable, we're able to track filter ordering as soon as
11344         * a non-zero order is defined. Otherwise, multiple loops across the result set
11345         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11346         * this needs to be contained entirely within {@link #filterResults()}.
11347         */
11348        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11349
11350        @Override
11351        protected EphemeralResolveIntentInfo[] newArray(int size) {
11352            return new EphemeralResolveIntentInfo[size];
11353        }
11354
11355        @Override
11356        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11357            return true;
11358        }
11359
11360        @Override
11361        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11362                int userId) {
11363            if (!sUserManager.exists(userId)) {
11364                return null;
11365            }
11366            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11367            final Integer order = info.getOrder();
11368            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11369                    mOrderResult.get(packageName);
11370            // ordering is enabled and this item's order isn't high enough
11371            if (lastOrderResult != null && lastOrderResult.first >= order) {
11372                return null;
11373            }
11374            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11375            if (order > 0) {
11376                // non-zero order, enable ordering
11377                mOrderResult.put(packageName, new Pair<>(order, res));
11378            }
11379            return res;
11380        }
11381
11382        @Override
11383        protected void filterResults(List<EphemeralResolveInfo> results) {
11384            // only do work if ordering is enabled [most of the time it won't be]
11385            if (mOrderResult.size() == 0) {
11386                return;
11387            }
11388            int resultSize = results.size();
11389            for (int i = 0; i < resultSize; i++) {
11390                final EphemeralResolveInfo info = results.get(i);
11391                final String packageName = info.getPackageName();
11392                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11393                if (savedInfo == null) {
11394                    // package doesn't having ordering
11395                    continue;
11396                }
11397                if (savedInfo.second == info) {
11398                    // circled back to the highest ordered item; remove from order list
11399                    mOrderResult.remove(savedInfo);
11400                    if (mOrderResult.size() == 0) {
11401                        // no more ordered items
11402                        break;
11403                    }
11404                    continue;
11405                }
11406                // item has a worse order, remove it from the result list
11407                results.remove(i);
11408                resultSize--;
11409                i--;
11410            }
11411        }
11412    }
11413
11414    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11415            new Comparator<ResolveInfo>() {
11416        public int compare(ResolveInfo r1, ResolveInfo r2) {
11417            int v1 = r1.priority;
11418            int v2 = r2.priority;
11419            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11420            if (v1 != v2) {
11421                return (v1 > v2) ? -1 : 1;
11422            }
11423            v1 = r1.preferredOrder;
11424            v2 = r2.preferredOrder;
11425            if (v1 != v2) {
11426                return (v1 > v2) ? -1 : 1;
11427            }
11428            if (r1.isDefault != r2.isDefault) {
11429                return r1.isDefault ? -1 : 1;
11430            }
11431            v1 = r1.match;
11432            v2 = r2.match;
11433            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11434            if (v1 != v2) {
11435                return (v1 > v2) ? -1 : 1;
11436            }
11437            if (r1.system != r2.system) {
11438                return r1.system ? -1 : 1;
11439            }
11440            if (r1.activityInfo != null) {
11441                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11442            }
11443            if (r1.serviceInfo != null) {
11444                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11445            }
11446            if (r1.providerInfo != null) {
11447                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11448            }
11449            return 0;
11450        }
11451    };
11452
11453    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11454            new Comparator<ProviderInfo>() {
11455        public int compare(ProviderInfo p1, ProviderInfo p2) {
11456            final int v1 = p1.initOrder;
11457            final int v2 = p2.initOrder;
11458            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11459        }
11460    };
11461
11462    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11463            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11464            final int[] userIds) {
11465        mHandler.post(new Runnable() {
11466            @Override
11467            public void run() {
11468                try {
11469                    final IActivityManager am = ActivityManagerNative.getDefault();
11470                    if (am == null) return;
11471                    final int[] resolvedUserIds;
11472                    if (userIds == null) {
11473                        resolvedUserIds = am.getRunningUserIds();
11474                    } else {
11475                        resolvedUserIds = userIds;
11476                    }
11477                    for (int id : resolvedUserIds) {
11478                        final Intent intent = new Intent(action,
11479                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11480                        if (extras != null) {
11481                            intent.putExtras(extras);
11482                        }
11483                        if (targetPkg != null) {
11484                            intent.setPackage(targetPkg);
11485                        }
11486                        // Modify the UID when posting to other users
11487                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11488                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11489                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11490                            intent.putExtra(Intent.EXTRA_UID, uid);
11491                        }
11492                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11493                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11494                        if (DEBUG_BROADCASTS) {
11495                            RuntimeException here = new RuntimeException("here");
11496                            here.fillInStackTrace();
11497                            Slog.d(TAG, "Sending to user " + id + ": "
11498                                    + intent.toShortString(false, true, false, false)
11499                                    + " " + intent.getExtras(), here);
11500                        }
11501                        am.broadcastIntent(null, intent, null, finishedReceiver,
11502                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11503                                null, finishedReceiver != null, false, id);
11504                    }
11505                } catch (RemoteException ex) {
11506                }
11507            }
11508        });
11509    }
11510
11511    /**
11512     * Check if the external storage media is available. This is true if there
11513     * is a mounted external storage medium or if the external storage is
11514     * emulated.
11515     */
11516    private boolean isExternalMediaAvailable() {
11517        return mMediaMounted || Environment.isExternalStorageEmulated();
11518    }
11519
11520    @Override
11521    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11522        // writer
11523        synchronized (mPackages) {
11524            if (!isExternalMediaAvailable()) {
11525                // If the external storage is no longer mounted at this point,
11526                // the caller may not have been able to delete all of this
11527                // packages files and can not delete any more.  Bail.
11528                return null;
11529            }
11530            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11531            if (lastPackage != null) {
11532                pkgs.remove(lastPackage);
11533            }
11534            if (pkgs.size() > 0) {
11535                return pkgs.get(0);
11536            }
11537        }
11538        return null;
11539    }
11540
11541    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11542        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11543                userId, andCode ? 1 : 0, packageName);
11544        if (mSystemReady) {
11545            msg.sendToTarget();
11546        } else {
11547            if (mPostSystemReadyMessages == null) {
11548                mPostSystemReadyMessages = new ArrayList<>();
11549            }
11550            mPostSystemReadyMessages.add(msg);
11551        }
11552    }
11553
11554    void startCleaningPackages() {
11555        // reader
11556        if (!isExternalMediaAvailable()) {
11557            return;
11558        }
11559        synchronized (mPackages) {
11560            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11561                return;
11562            }
11563        }
11564        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11565        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11566        IActivityManager am = ActivityManagerNative.getDefault();
11567        if (am != null) {
11568            try {
11569                am.startService(null, intent, null, mContext.getOpPackageName(),
11570                        UserHandle.USER_SYSTEM);
11571            } catch (RemoteException e) {
11572            }
11573        }
11574    }
11575
11576    @Override
11577    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11578            int installFlags, String installerPackageName, int userId) {
11579        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11580
11581        final int callingUid = Binder.getCallingUid();
11582        enforceCrossUserPermission(callingUid, userId,
11583                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11584
11585        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11586            try {
11587                if (observer != null) {
11588                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11589                }
11590            } catch (RemoteException re) {
11591            }
11592            return;
11593        }
11594
11595        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11596            installFlags |= PackageManager.INSTALL_FROM_ADB;
11597
11598        } else {
11599            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11600            // about installerPackageName.
11601
11602            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11603            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11604        }
11605
11606        UserHandle user;
11607        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11608            user = UserHandle.ALL;
11609        } else {
11610            user = new UserHandle(userId);
11611        }
11612
11613        // Only system components can circumvent runtime permissions when installing.
11614        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11615                && mContext.checkCallingOrSelfPermission(Manifest.permission
11616                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11617            throw new SecurityException("You need the "
11618                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11619                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11620        }
11621
11622        final File originFile = new File(originPath);
11623        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11624
11625        final Message msg = mHandler.obtainMessage(INIT_COPY);
11626        final VerificationInfo verificationInfo = new VerificationInfo(
11627                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11628        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11629                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11630                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11631                null /*certificates*/);
11632        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11633        msg.obj = params;
11634
11635        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11636                System.identityHashCode(msg.obj));
11637        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11638                System.identityHashCode(msg.obj));
11639
11640        mHandler.sendMessage(msg);
11641    }
11642
11643    void installStage(String packageName, File stagedDir, String stagedCid,
11644            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11645            String installerPackageName, int installerUid, UserHandle user,
11646            Certificate[][] certificates) {
11647        if (DEBUG_EPHEMERAL) {
11648            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11649                Slog.d(TAG, "Ephemeral install of " + packageName);
11650            }
11651        }
11652        final VerificationInfo verificationInfo = new VerificationInfo(
11653                sessionParams.originatingUri, sessionParams.referrerUri,
11654                sessionParams.originatingUid, installerUid);
11655
11656        final OriginInfo origin;
11657        if (stagedDir != null) {
11658            origin = OriginInfo.fromStagedFile(stagedDir);
11659        } else {
11660            origin = OriginInfo.fromStagedContainer(stagedCid);
11661        }
11662
11663        final Message msg = mHandler.obtainMessage(INIT_COPY);
11664        final InstallParams params = new InstallParams(origin, null, observer,
11665                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11666                verificationInfo, user, sessionParams.abiOverride,
11667                sessionParams.grantedRuntimePermissions, certificates);
11668        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11669        msg.obj = params;
11670
11671        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11672                System.identityHashCode(msg.obj));
11673        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11674                System.identityHashCode(msg.obj));
11675
11676        mHandler.sendMessage(msg);
11677    }
11678
11679    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11680            int userId) {
11681        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11682        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11683    }
11684
11685    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11686            int appId, int userId) {
11687        Bundle extras = new Bundle(1);
11688        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11689
11690        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11691                packageName, extras, 0, null, null, new int[] {userId});
11692        try {
11693            IActivityManager am = ActivityManagerNative.getDefault();
11694            if (isSystem && am.isUserRunning(userId, 0)) {
11695                // The just-installed/enabled app is bundled on the system, so presumed
11696                // to be able to run automatically without needing an explicit launch.
11697                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11698                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11699                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11700                        .setPackage(packageName);
11701                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11702                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11703            }
11704        } catch (RemoteException e) {
11705            // shouldn't happen
11706            Slog.w(TAG, "Unable to bootstrap installed package", e);
11707        }
11708    }
11709
11710    @Override
11711    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11712            int userId) {
11713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11714        PackageSetting pkgSetting;
11715        final int uid = Binder.getCallingUid();
11716        enforceCrossUserPermission(uid, userId,
11717                true /* requireFullPermission */, true /* checkShell */,
11718                "setApplicationHiddenSetting for user " + userId);
11719
11720        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11721            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11722            return false;
11723        }
11724
11725        long callingId = Binder.clearCallingIdentity();
11726        try {
11727            boolean sendAdded = false;
11728            boolean sendRemoved = false;
11729            // writer
11730            synchronized (mPackages) {
11731                pkgSetting = mSettings.mPackages.get(packageName);
11732                if (pkgSetting == null) {
11733                    return false;
11734                }
11735                // Do not allow "android" is being disabled
11736                if ("android".equals(packageName)) {
11737                    Slog.w(TAG, "Cannot hide package: android");
11738                    return false;
11739                }
11740                // Only allow protected packages to hide themselves.
11741                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11742                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11743                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11744                    return false;
11745                }
11746
11747                if (pkgSetting.getHidden(userId) != hidden) {
11748                    pkgSetting.setHidden(hidden, userId);
11749                    mSettings.writePackageRestrictionsLPr(userId);
11750                    if (hidden) {
11751                        sendRemoved = true;
11752                    } else {
11753                        sendAdded = true;
11754                    }
11755                }
11756            }
11757            if (sendAdded) {
11758                sendPackageAddedForUser(packageName, pkgSetting, userId);
11759                return true;
11760            }
11761            if (sendRemoved) {
11762                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11763                        "hiding pkg");
11764                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11765                return true;
11766            }
11767        } finally {
11768            Binder.restoreCallingIdentity(callingId);
11769        }
11770        return false;
11771    }
11772
11773    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11774            int userId) {
11775        final PackageRemovedInfo info = new PackageRemovedInfo();
11776        info.removedPackage = packageName;
11777        info.removedUsers = new int[] {userId};
11778        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11779        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11780    }
11781
11782    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11783        if (pkgList.length > 0) {
11784            Bundle extras = new Bundle(1);
11785            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11786
11787            sendPackageBroadcast(
11788                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11789                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11790                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11791                    new int[] {userId});
11792        }
11793    }
11794
11795    /**
11796     * Returns true if application is not found or there was an error. Otherwise it returns
11797     * the hidden state of the package for the given user.
11798     */
11799    @Override
11800    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11802        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11803                true /* requireFullPermission */, false /* checkShell */,
11804                "getApplicationHidden for user " + userId);
11805        PackageSetting pkgSetting;
11806        long callingId = Binder.clearCallingIdentity();
11807        try {
11808            // writer
11809            synchronized (mPackages) {
11810                pkgSetting = mSettings.mPackages.get(packageName);
11811                if (pkgSetting == null) {
11812                    return true;
11813                }
11814                return pkgSetting.getHidden(userId);
11815            }
11816        } finally {
11817            Binder.restoreCallingIdentity(callingId);
11818        }
11819    }
11820
11821    /**
11822     * @hide
11823     */
11824    @Override
11825    public int installExistingPackageAsUser(String packageName, int userId) {
11826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11827                null);
11828        PackageSetting pkgSetting;
11829        final int uid = Binder.getCallingUid();
11830        enforceCrossUserPermission(uid, userId,
11831                true /* requireFullPermission */, true /* checkShell */,
11832                "installExistingPackage for user " + userId);
11833        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11834            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11835        }
11836
11837        long callingId = Binder.clearCallingIdentity();
11838        try {
11839            boolean installed = false;
11840
11841            // writer
11842            synchronized (mPackages) {
11843                pkgSetting = mSettings.mPackages.get(packageName);
11844                if (pkgSetting == null) {
11845                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11846                }
11847                if (!pkgSetting.getInstalled(userId)) {
11848                    pkgSetting.setInstalled(true, userId);
11849                    pkgSetting.setHidden(false, userId);
11850                    mSettings.writePackageRestrictionsLPr(userId);
11851                    installed = true;
11852                }
11853            }
11854
11855            if (installed) {
11856                if (pkgSetting.pkg != null) {
11857                    synchronized (mInstallLock) {
11858                        // We don't need to freeze for a brand new install
11859                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11860                    }
11861                }
11862                sendPackageAddedForUser(packageName, pkgSetting, userId);
11863            }
11864        } finally {
11865            Binder.restoreCallingIdentity(callingId);
11866        }
11867
11868        return PackageManager.INSTALL_SUCCEEDED;
11869    }
11870
11871    boolean isUserRestricted(int userId, String restrictionKey) {
11872        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11873        if (restrictions.getBoolean(restrictionKey, false)) {
11874            Log.w(TAG, "User is restricted: " + restrictionKey);
11875            return true;
11876        }
11877        return false;
11878    }
11879
11880    @Override
11881    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11882            int userId) {
11883        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11884        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11885                true /* requireFullPermission */, true /* checkShell */,
11886                "setPackagesSuspended for user " + userId);
11887
11888        if (ArrayUtils.isEmpty(packageNames)) {
11889            return packageNames;
11890        }
11891
11892        // List of package names for whom the suspended state has changed.
11893        List<String> changedPackages = new ArrayList<>(packageNames.length);
11894        // List of package names for whom the suspended state is not set as requested in this
11895        // method.
11896        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11897        long callingId = Binder.clearCallingIdentity();
11898        try {
11899            for (int i = 0; i < packageNames.length; i++) {
11900                String packageName = packageNames[i];
11901                boolean changed = false;
11902                final int appId;
11903                synchronized (mPackages) {
11904                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11905                    if (pkgSetting == null) {
11906                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11907                                + "\". Skipping suspending/un-suspending.");
11908                        unactionedPackages.add(packageName);
11909                        continue;
11910                    }
11911                    appId = pkgSetting.appId;
11912                    if (pkgSetting.getSuspended(userId) != suspended) {
11913                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11914                            unactionedPackages.add(packageName);
11915                            continue;
11916                        }
11917                        pkgSetting.setSuspended(suspended, userId);
11918                        mSettings.writePackageRestrictionsLPr(userId);
11919                        changed = true;
11920                        changedPackages.add(packageName);
11921                    }
11922                }
11923
11924                if (changed && suspended) {
11925                    killApplication(packageName, UserHandle.getUid(userId, appId),
11926                            "suspending package");
11927                }
11928            }
11929        } finally {
11930            Binder.restoreCallingIdentity(callingId);
11931        }
11932
11933        if (!changedPackages.isEmpty()) {
11934            sendPackagesSuspendedForUser(changedPackages.toArray(
11935                    new String[changedPackages.size()]), userId, suspended);
11936        }
11937
11938        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11939    }
11940
11941    @Override
11942    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11943        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11944                true /* requireFullPermission */, false /* checkShell */,
11945                "isPackageSuspendedForUser for user " + userId);
11946        synchronized (mPackages) {
11947            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11948            if (pkgSetting == null) {
11949                throw new IllegalArgumentException("Unknown target package: " + packageName);
11950            }
11951            return pkgSetting.getSuspended(userId);
11952        }
11953    }
11954
11955    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11956        if (isPackageDeviceAdmin(packageName, userId)) {
11957            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11958                    + "\": has an active device admin");
11959            return false;
11960        }
11961
11962        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11963        if (packageName.equals(activeLauncherPackageName)) {
11964            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11965                    + "\": contains the active launcher");
11966            return false;
11967        }
11968
11969        if (packageName.equals(mRequiredInstallerPackage)) {
11970            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11971                    + "\": required for package installation");
11972            return false;
11973        }
11974
11975        if (packageName.equals(mRequiredUninstallerPackage)) {
11976            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11977                    + "\": required for package uninstallation");
11978            return false;
11979        }
11980
11981        if (packageName.equals(mRequiredVerifierPackage)) {
11982            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11983                    + "\": required for package verification");
11984            return false;
11985        }
11986
11987        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11988            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11989                    + "\": is the default dialer");
11990            return false;
11991        }
11992
11993        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11994            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11995                    + "\": protected package");
11996            return false;
11997        }
11998
11999        return true;
12000    }
12001
12002    private String getActiveLauncherPackageName(int userId) {
12003        Intent intent = new Intent(Intent.ACTION_MAIN);
12004        intent.addCategory(Intent.CATEGORY_HOME);
12005        ResolveInfo resolveInfo = resolveIntent(
12006                intent,
12007                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12008                PackageManager.MATCH_DEFAULT_ONLY,
12009                userId);
12010
12011        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12012    }
12013
12014    private String getDefaultDialerPackageName(int userId) {
12015        synchronized (mPackages) {
12016            return mSettings.getDefaultDialerPackageNameLPw(userId);
12017        }
12018    }
12019
12020    @Override
12021    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12022        mContext.enforceCallingOrSelfPermission(
12023                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12024                "Only package verification agents can verify applications");
12025
12026        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12027        final PackageVerificationResponse response = new PackageVerificationResponse(
12028                verificationCode, Binder.getCallingUid());
12029        msg.arg1 = id;
12030        msg.obj = response;
12031        mHandler.sendMessage(msg);
12032    }
12033
12034    @Override
12035    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12036            long millisecondsToDelay) {
12037        mContext.enforceCallingOrSelfPermission(
12038                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12039                "Only package verification agents can extend verification timeouts");
12040
12041        final PackageVerificationState state = mPendingVerification.get(id);
12042        final PackageVerificationResponse response = new PackageVerificationResponse(
12043                verificationCodeAtTimeout, Binder.getCallingUid());
12044
12045        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12046            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12047        }
12048        if (millisecondsToDelay < 0) {
12049            millisecondsToDelay = 0;
12050        }
12051        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12052                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12053            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12054        }
12055
12056        if ((state != null) && !state.timeoutExtended()) {
12057            state.extendTimeout();
12058
12059            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12060            msg.arg1 = id;
12061            msg.obj = response;
12062            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12063        }
12064    }
12065
12066    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12067            int verificationCode, UserHandle user) {
12068        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12069        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12070        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12071        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12072        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12073
12074        mContext.sendBroadcastAsUser(intent, user,
12075                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12076    }
12077
12078    private ComponentName matchComponentForVerifier(String packageName,
12079            List<ResolveInfo> receivers) {
12080        ActivityInfo targetReceiver = null;
12081
12082        final int NR = receivers.size();
12083        for (int i = 0; i < NR; i++) {
12084            final ResolveInfo info = receivers.get(i);
12085            if (info.activityInfo == null) {
12086                continue;
12087            }
12088
12089            if (packageName.equals(info.activityInfo.packageName)) {
12090                targetReceiver = info.activityInfo;
12091                break;
12092            }
12093        }
12094
12095        if (targetReceiver == null) {
12096            return null;
12097        }
12098
12099        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12100    }
12101
12102    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12103            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12104        if (pkgInfo.verifiers.length == 0) {
12105            return null;
12106        }
12107
12108        final int N = pkgInfo.verifiers.length;
12109        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12110        for (int i = 0; i < N; i++) {
12111            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12112
12113            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12114                    receivers);
12115            if (comp == null) {
12116                continue;
12117            }
12118
12119            final int verifierUid = getUidForVerifier(verifierInfo);
12120            if (verifierUid == -1) {
12121                continue;
12122            }
12123
12124            if (DEBUG_VERIFY) {
12125                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12126                        + " with the correct signature");
12127            }
12128            sufficientVerifiers.add(comp);
12129            verificationState.addSufficientVerifier(verifierUid);
12130        }
12131
12132        return sufficientVerifiers;
12133    }
12134
12135    private int getUidForVerifier(VerifierInfo verifierInfo) {
12136        synchronized (mPackages) {
12137            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12138            if (pkg == null) {
12139                return -1;
12140            } else if (pkg.mSignatures.length != 1) {
12141                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12142                        + " has more than one signature; ignoring");
12143                return -1;
12144            }
12145
12146            /*
12147             * If the public key of the package's signature does not match
12148             * our expected public key, then this is a different package and
12149             * we should skip.
12150             */
12151
12152            final byte[] expectedPublicKey;
12153            try {
12154                final Signature verifierSig = pkg.mSignatures[0];
12155                final PublicKey publicKey = verifierSig.getPublicKey();
12156                expectedPublicKey = publicKey.getEncoded();
12157            } catch (CertificateException e) {
12158                return -1;
12159            }
12160
12161            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12162
12163            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12164                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12165                        + " does not have the expected public key; ignoring");
12166                return -1;
12167            }
12168
12169            return pkg.applicationInfo.uid;
12170        }
12171    }
12172
12173    @Override
12174    public void finishPackageInstall(int token, boolean didLaunch) {
12175        enforceSystemOrRoot("Only the system is allowed to finish installs");
12176
12177        if (DEBUG_INSTALL) {
12178            Slog.v(TAG, "BM finishing package install for " + token);
12179        }
12180        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12181
12182        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12183        mHandler.sendMessage(msg);
12184    }
12185
12186    /**
12187     * Get the verification agent timeout.
12188     *
12189     * @return verification timeout in milliseconds
12190     */
12191    private long getVerificationTimeout() {
12192        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12193                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12194                DEFAULT_VERIFICATION_TIMEOUT);
12195    }
12196
12197    /**
12198     * Get the default verification agent response code.
12199     *
12200     * @return default verification response code
12201     */
12202    private int getDefaultVerificationResponse() {
12203        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12204                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12205                DEFAULT_VERIFICATION_RESPONSE);
12206    }
12207
12208    /**
12209     * Check whether or not package verification has been enabled.
12210     *
12211     * @return true if verification should be performed
12212     */
12213    private boolean isVerificationEnabled(int userId, int installFlags) {
12214        if (!DEFAULT_VERIFY_ENABLE) {
12215            return false;
12216        }
12217        // Ephemeral apps don't get the full verification treatment
12218        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12219            if (DEBUG_EPHEMERAL) {
12220                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12221            }
12222            return false;
12223        }
12224
12225        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12226
12227        // Check if installing from ADB
12228        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12229            // Do not run verification in a test harness environment
12230            if (ActivityManager.isRunningInTestHarness()) {
12231                return false;
12232            }
12233            if (ensureVerifyAppsEnabled) {
12234                return true;
12235            }
12236            // Check if the developer does not want package verification for ADB installs
12237            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12238                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12239                return false;
12240            }
12241        }
12242
12243        if (ensureVerifyAppsEnabled) {
12244            return true;
12245        }
12246
12247        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12248                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12249    }
12250
12251    @Override
12252    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12253            throws RemoteException {
12254        mContext.enforceCallingOrSelfPermission(
12255                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12256                "Only intentfilter verification agents can verify applications");
12257
12258        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12259        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12260                Binder.getCallingUid(), verificationCode, failedDomains);
12261        msg.arg1 = id;
12262        msg.obj = response;
12263        mHandler.sendMessage(msg);
12264    }
12265
12266    @Override
12267    public int getIntentVerificationStatus(String packageName, int userId) {
12268        synchronized (mPackages) {
12269            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12270        }
12271    }
12272
12273    @Override
12274    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12275        mContext.enforceCallingOrSelfPermission(
12276                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12277
12278        boolean result = false;
12279        synchronized (mPackages) {
12280            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12281        }
12282        if (result) {
12283            scheduleWritePackageRestrictionsLocked(userId);
12284        }
12285        return result;
12286    }
12287
12288    @Override
12289    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12290            String packageName) {
12291        synchronized (mPackages) {
12292            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12293        }
12294    }
12295
12296    @Override
12297    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12298        if (TextUtils.isEmpty(packageName)) {
12299            return ParceledListSlice.emptyList();
12300        }
12301        synchronized (mPackages) {
12302            PackageParser.Package pkg = mPackages.get(packageName);
12303            if (pkg == null || pkg.activities == null) {
12304                return ParceledListSlice.emptyList();
12305            }
12306            final int count = pkg.activities.size();
12307            ArrayList<IntentFilter> result = new ArrayList<>();
12308            for (int n=0; n<count; n++) {
12309                PackageParser.Activity activity = pkg.activities.get(n);
12310                if (activity.intents != null && activity.intents.size() > 0) {
12311                    result.addAll(activity.intents);
12312                }
12313            }
12314            return new ParceledListSlice<>(result);
12315        }
12316    }
12317
12318    @Override
12319    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12320        mContext.enforceCallingOrSelfPermission(
12321                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12322
12323        synchronized (mPackages) {
12324            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12325            if (packageName != null) {
12326                result |= updateIntentVerificationStatus(packageName,
12327                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12328                        userId);
12329                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12330                        packageName, userId);
12331            }
12332            return result;
12333        }
12334    }
12335
12336    @Override
12337    public String getDefaultBrowserPackageName(int userId) {
12338        synchronized (mPackages) {
12339            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12340        }
12341    }
12342
12343    /**
12344     * Get the "allow unknown sources" setting.
12345     *
12346     * @return the current "allow unknown sources" setting
12347     */
12348    private int getUnknownSourcesSettings() {
12349        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12350                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12351                -1);
12352    }
12353
12354    @Override
12355    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12356        final int uid = Binder.getCallingUid();
12357        // writer
12358        synchronized (mPackages) {
12359            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12360            if (targetPackageSetting == null) {
12361                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12362            }
12363
12364            PackageSetting installerPackageSetting;
12365            if (installerPackageName != null) {
12366                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12367                if (installerPackageSetting == null) {
12368                    throw new IllegalArgumentException("Unknown installer package: "
12369                            + installerPackageName);
12370                }
12371            } else {
12372                installerPackageSetting = null;
12373            }
12374
12375            Signature[] callerSignature;
12376            Object obj = mSettings.getUserIdLPr(uid);
12377            if (obj != null) {
12378                if (obj instanceof SharedUserSetting) {
12379                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12380                } else if (obj instanceof PackageSetting) {
12381                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12382                } else {
12383                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12384                }
12385            } else {
12386                throw new SecurityException("Unknown calling UID: " + uid);
12387            }
12388
12389            // Verify: can't set installerPackageName to a package that is
12390            // not signed with the same cert as the caller.
12391            if (installerPackageSetting != null) {
12392                if (compareSignatures(callerSignature,
12393                        installerPackageSetting.signatures.mSignatures)
12394                        != PackageManager.SIGNATURE_MATCH) {
12395                    throw new SecurityException(
12396                            "Caller does not have same cert as new installer package "
12397                            + installerPackageName);
12398                }
12399            }
12400
12401            // Verify: if target already has an installer package, it must
12402            // be signed with the same cert as the caller.
12403            if (targetPackageSetting.installerPackageName != null) {
12404                PackageSetting setting = mSettings.mPackages.get(
12405                        targetPackageSetting.installerPackageName);
12406                // If the currently set package isn't valid, then it's always
12407                // okay to change it.
12408                if (setting != null) {
12409                    if (compareSignatures(callerSignature,
12410                            setting.signatures.mSignatures)
12411                            != PackageManager.SIGNATURE_MATCH) {
12412                        throw new SecurityException(
12413                                "Caller does not have same cert as old installer package "
12414                                + targetPackageSetting.installerPackageName);
12415                    }
12416                }
12417            }
12418
12419            // Okay!
12420            targetPackageSetting.installerPackageName = installerPackageName;
12421            if (installerPackageName != null) {
12422                mSettings.mInstallerPackages.add(installerPackageName);
12423            }
12424            scheduleWriteSettingsLocked();
12425        }
12426    }
12427
12428    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12429        // Queue up an async operation since the package installation may take a little while.
12430        mHandler.post(new Runnable() {
12431            public void run() {
12432                mHandler.removeCallbacks(this);
12433                 // Result object to be returned
12434                PackageInstalledInfo res = new PackageInstalledInfo();
12435                res.setReturnCode(currentStatus);
12436                res.uid = -1;
12437                res.pkg = null;
12438                res.removedInfo = null;
12439                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12440                    args.doPreInstall(res.returnCode);
12441                    synchronized (mInstallLock) {
12442                        installPackageTracedLI(args, res);
12443                    }
12444                    args.doPostInstall(res.returnCode, res.uid);
12445                }
12446
12447                // A restore should be performed at this point if (a) the install
12448                // succeeded, (b) the operation is not an update, and (c) the new
12449                // package has not opted out of backup participation.
12450                final boolean update = res.removedInfo != null
12451                        && res.removedInfo.removedPackage != null;
12452                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12453                boolean doRestore = !update
12454                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12455
12456                // Set up the post-install work request bookkeeping.  This will be used
12457                // and cleaned up by the post-install event handling regardless of whether
12458                // there's a restore pass performed.  Token values are >= 1.
12459                int token;
12460                if (mNextInstallToken < 0) mNextInstallToken = 1;
12461                token = mNextInstallToken++;
12462
12463                PostInstallData data = new PostInstallData(args, res);
12464                mRunningInstalls.put(token, data);
12465                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12466
12467                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12468                    // Pass responsibility to the Backup Manager.  It will perform a
12469                    // restore if appropriate, then pass responsibility back to the
12470                    // Package Manager to run the post-install observer callbacks
12471                    // and broadcasts.
12472                    IBackupManager bm = IBackupManager.Stub.asInterface(
12473                            ServiceManager.getService(Context.BACKUP_SERVICE));
12474                    if (bm != null) {
12475                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12476                                + " to BM for possible restore");
12477                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12478                        try {
12479                            // TODO: http://b/22388012
12480                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12481                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12482                            } else {
12483                                doRestore = false;
12484                            }
12485                        } catch (RemoteException e) {
12486                            // can't happen; the backup manager is local
12487                        } catch (Exception e) {
12488                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12489                            doRestore = false;
12490                        }
12491                    } else {
12492                        Slog.e(TAG, "Backup Manager not found!");
12493                        doRestore = false;
12494                    }
12495                }
12496
12497                if (!doRestore) {
12498                    // No restore possible, or the Backup Manager was mysteriously not
12499                    // available -- just fire the post-install work request directly.
12500                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12501
12502                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12503
12504                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12505                    mHandler.sendMessage(msg);
12506                }
12507            }
12508        });
12509    }
12510
12511    /**
12512     * Callback from PackageSettings whenever an app is first transitioned out of the
12513     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12514     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12515     * here whether the app is the target of an ongoing install, and only send the
12516     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12517     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12518     * handling.
12519     */
12520    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12521        // Serialize this with the rest of the install-process message chain.  In the
12522        // restore-at-install case, this Runnable will necessarily run before the
12523        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12524        // are coherent.  In the non-restore case, the app has already completed install
12525        // and been launched through some other means, so it is not in a problematic
12526        // state for observers to see the FIRST_LAUNCH signal.
12527        mHandler.post(new Runnable() {
12528            @Override
12529            public void run() {
12530                for (int i = 0; i < mRunningInstalls.size(); i++) {
12531                    final PostInstallData data = mRunningInstalls.valueAt(i);
12532                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12533                        continue;
12534                    }
12535                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12536                        // right package; but is it for the right user?
12537                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12538                            if (userId == data.res.newUsers[uIndex]) {
12539                                if (DEBUG_BACKUP) {
12540                                    Slog.i(TAG, "Package " + pkgName
12541                                            + " being restored so deferring FIRST_LAUNCH");
12542                                }
12543                                return;
12544                            }
12545                        }
12546                    }
12547                }
12548                // didn't find it, so not being restored
12549                if (DEBUG_BACKUP) {
12550                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12551                }
12552                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12553            }
12554        });
12555    }
12556
12557    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12558        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12559                installerPkg, null, userIds);
12560    }
12561
12562    private abstract class HandlerParams {
12563        private static final int MAX_RETRIES = 4;
12564
12565        /**
12566         * Number of times startCopy() has been attempted and had a non-fatal
12567         * error.
12568         */
12569        private int mRetries = 0;
12570
12571        /** User handle for the user requesting the information or installation. */
12572        private final UserHandle mUser;
12573        String traceMethod;
12574        int traceCookie;
12575
12576        HandlerParams(UserHandle user) {
12577            mUser = user;
12578        }
12579
12580        UserHandle getUser() {
12581            return mUser;
12582        }
12583
12584        HandlerParams setTraceMethod(String traceMethod) {
12585            this.traceMethod = traceMethod;
12586            return this;
12587        }
12588
12589        HandlerParams setTraceCookie(int traceCookie) {
12590            this.traceCookie = traceCookie;
12591            return this;
12592        }
12593
12594        final boolean startCopy() {
12595            boolean res;
12596            try {
12597                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12598
12599                if (++mRetries > MAX_RETRIES) {
12600                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12601                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12602                    handleServiceError();
12603                    return false;
12604                } else {
12605                    handleStartCopy();
12606                    res = true;
12607                }
12608            } catch (RemoteException e) {
12609                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12610                mHandler.sendEmptyMessage(MCS_RECONNECT);
12611                res = false;
12612            }
12613            handleReturnCode();
12614            return res;
12615        }
12616
12617        final void serviceError() {
12618            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12619            handleServiceError();
12620            handleReturnCode();
12621        }
12622
12623        abstract void handleStartCopy() throws RemoteException;
12624        abstract void handleServiceError();
12625        abstract void handleReturnCode();
12626    }
12627
12628    class MeasureParams extends HandlerParams {
12629        private final PackageStats mStats;
12630        private boolean mSuccess;
12631
12632        private final IPackageStatsObserver mObserver;
12633
12634        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12635            super(new UserHandle(stats.userHandle));
12636            mObserver = observer;
12637            mStats = stats;
12638        }
12639
12640        @Override
12641        public String toString() {
12642            return "MeasureParams{"
12643                + Integer.toHexString(System.identityHashCode(this))
12644                + " " + mStats.packageName + "}";
12645        }
12646
12647        @Override
12648        void handleStartCopy() throws RemoteException {
12649            synchronized (mInstallLock) {
12650                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12651            }
12652
12653            if (mSuccess) {
12654                boolean mounted = false;
12655                try {
12656                    final String status = Environment.getExternalStorageState();
12657                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12658                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12659                } catch (Exception e) {
12660                }
12661
12662                if (mounted) {
12663                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12664
12665                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12666                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12667
12668                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12669                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12670
12671                    // Always subtract cache size, since it's a subdirectory
12672                    mStats.externalDataSize -= mStats.externalCacheSize;
12673
12674                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12675                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12676
12677                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12678                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12679                }
12680            }
12681        }
12682
12683        @Override
12684        void handleReturnCode() {
12685            if (mObserver != null) {
12686                try {
12687                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12688                } catch (RemoteException e) {
12689                    Slog.i(TAG, "Observer no longer exists.");
12690                }
12691            }
12692        }
12693
12694        @Override
12695        void handleServiceError() {
12696            Slog.e(TAG, "Could not measure application " + mStats.packageName
12697                            + " external storage");
12698        }
12699    }
12700
12701    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12702            throws RemoteException {
12703        long result = 0;
12704        for (File path : paths) {
12705            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12706        }
12707        return result;
12708    }
12709
12710    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12711        for (File path : paths) {
12712            try {
12713                mcs.clearDirectory(path.getAbsolutePath());
12714            } catch (RemoteException e) {
12715            }
12716        }
12717    }
12718
12719    static class OriginInfo {
12720        /**
12721         * Location where install is coming from, before it has been
12722         * copied/renamed into place. This could be a single monolithic APK
12723         * file, or a cluster directory. This location may be untrusted.
12724         */
12725        final File file;
12726        final String cid;
12727
12728        /**
12729         * Flag indicating that {@link #file} or {@link #cid} has already been
12730         * staged, meaning downstream users don't need to defensively copy the
12731         * contents.
12732         */
12733        final boolean staged;
12734
12735        /**
12736         * Flag indicating that {@link #file} or {@link #cid} is an already
12737         * installed app that is being moved.
12738         */
12739        final boolean existing;
12740
12741        final String resolvedPath;
12742        final File resolvedFile;
12743
12744        static OriginInfo fromNothing() {
12745            return new OriginInfo(null, null, false, false);
12746        }
12747
12748        static OriginInfo fromUntrustedFile(File file) {
12749            return new OriginInfo(file, null, false, false);
12750        }
12751
12752        static OriginInfo fromExistingFile(File file) {
12753            return new OriginInfo(file, null, false, true);
12754        }
12755
12756        static OriginInfo fromStagedFile(File file) {
12757            return new OriginInfo(file, null, true, false);
12758        }
12759
12760        static OriginInfo fromStagedContainer(String cid) {
12761            return new OriginInfo(null, cid, true, false);
12762        }
12763
12764        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12765            this.file = file;
12766            this.cid = cid;
12767            this.staged = staged;
12768            this.existing = existing;
12769
12770            if (cid != null) {
12771                resolvedPath = PackageHelper.getSdDir(cid);
12772                resolvedFile = new File(resolvedPath);
12773            } else if (file != null) {
12774                resolvedPath = file.getAbsolutePath();
12775                resolvedFile = file;
12776            } else {
12777                resolvedPath = null;
12778                resolvedFile = null;
12779            }
12780        }
12781    }
12782
12783    static class MoveInfo {
12784        final int moveId;
12785        final String fromUuid;
12786        final String toUuid;
12787        final String packageName;
12788        final String dataAppName;
12789        final int appId;
12790        final String seinfo;
12791        final int targetSdkVersion;
12792
12793        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12794                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12795            this.moveId = moveId;
12796            this.fromUuid = fromUuid;
12797            this.toUuid = toUuid;
12798            this.packageName = packageName;
12799            this.dataAppName = dataAppName;
12800            this.appId = appId;
12801            this.seinfo = seinfo;
12802            this.targetSdkVersion = targetSdkVersion;
12803        }
12804    }
12805
12806    static class VerificationInfo {
12807        /** A constant used to indicate that a uid value is not present. */
12808        public static final int NO_UID = -1;
12809
12810        /** URI referencing where the package was downloaded from. */
12811        final Uri originatingUri;
12812
12813        /** HTTP referrer URI associated with the originatingURI. */
12814        final Uri referrer;
12815
12816        /** UID of the application that the install request originated from. */
12817        final int originatingUid;
12818
12819        /** UID of application requesting the install */
12820        final int installerUid;
12821
12822        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12823            this.originatingUri = originatingUri;
12824            this.referrer = referrer;
12825            this.originatingUid = originatingUid;
12826            this.installerUid = installerUid;
12827        }
12828    }
12829
12830    class InstallParams extends HandlerParams {
12831        final OriginInfo origin;
12832        final MoveInfo move;
12833        final IPackageInstallObserver2 observer;
12834        int installFlags;
12835        final String installerPackageName;
12836        final String volumeUuid;
12837        private InstallArgs mArgs;
12838        private int mRet;
12839        final String packageAbiOverride;
12840        final String[] grantedRuntimePermissions;
12841        final VerificationInfo verificationInfo;
12842        final Certificate[][] certificates;
12843
12844        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12845                int installFlags, String installerPackageName, String volumeUuid,
12846                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12847                String[] grantedPermissions, Certificate[][] certificates) {
12848            super(user);
12849            this.origin = origin;
12850            this.move = move;
12851            this.observer = observer;
12852            this.installFlags = installFlags;
12853            this.installerPackageName = installerPackageName;
12854            this.volumeUuid = volumeUuid;
12855            this.verificationInfo = verificationInfo;
12856            this.packageAbiOverride = packageAbiOverride;
12857            this.grantedRuntimePermissions = grantedPermissions;
12858            this.certificates = certificates;
12859        }
12860
12861        @Override
12862        public String toString() {
12863            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12864                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12865        }
12866
12867        private int installLocationPolicy(PackageInfoLite pkgLite) {
12868            String packageName = pkgLite.packageName;
12869            int installLocation = pkgLite.installLocation;
12870            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12871            // reader
12872            synchronized (mPackages) {
12873                // Currently installed package which the new package is attempting to replace or
12874                // null if no such package is installed.
12875                PackageParser.Package installedPkg = mPackages.get(packageName);
12876                // Package which currently owns the data which the new package will own if installed.
12877                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12878                // will be null whereas dataOwnerPkg will contain information about the package
12879                // which was uninstalled while keeping its data.
12880                PackageParser.Package dataOwnerPkg = installedPkg;
12881                if (dataOwnerPkg  == null) {
12882                    PackageSetting ps = mSettings.mPackages.get(packageName);
12883                    if (ps != null) {
12884                        dataOwnerPkg = ps.pkg;
12885                    }
12886                }
12887
12888                if (dataOwnerPkg != null) {
12889                    // If installed, the package will get access to data left on the device by its
12890                    // predecessor. As a security measure, this is permited only if this is not a
12891                    // version downgrade or if the predecessor package is marked as debuggable and
12892                    // a downgrade is explicitly requested.
12893                    //
12894                    // On debuggable platform builds, downgrades are permitted even for
12895                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12896                    // not offer security guarantees and thus it's OK to disable some security
12897                    // mechanisms to make debugging/testing easier on those builds. However, even on
12898                    // debuggable builds downgrades of packages are permitted only if requested via
12899                    // installFlags. This is because we aim to keep the behavior of debuggable
12900                    // platform builds as close as possible to the behavior of non-debuggable
12901                    // platform builds.
12902                    final boolean downgradeRequested =
12903                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12904                    final boolean packageDebuggable =
12905                                (dataOwnerPkg.applicationInfo.flags
12906                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12907                    final boolean downgradePermitted =
12908                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12909                    if (!downgradePermitted) {
12910                        try {
12911                            checkDowngrade(dataOwnerPkg, pkgLite);
12912                        } catch (PackageManagerException e) {
12913                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12914                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12915                        }
12916                    }
12917                }
12918
12919                if (installedPkg != null) {
12920                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12921                        // Check for updated system application.
12922                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12923                            if (onSd) {
12924                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12925                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12926                            }
12927                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12928                        } else {
12929                            if (onSd) {
12930                                // Install flag overrides everything.
12931                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12932                            }
12933                            // If current upgrade specifies particular preference
12934                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12935                                // Application explicitly specified internal.
12936                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12937                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12938                                // App explictly prefers external. Let policy decide
12939                            } else {
12940                                // Prefer previous location
12941                                if (isExternal(installedPkg)) {
12942                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12943                                }
12944                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12945                            }
12946                        }
12947                    } else {
12948                        // Invalid install. Return error code
12949                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12950                    }
12951                }
12952            }
12953            // All the special cases have been taken care of.
12954            // Return result based on recommended install location.
12955            if (onSd) {
12956                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12957            }
12958            return pkgLite.recommendedInstallLocation;
12959        }
12960
12961        /*
12962         * Invoke remote method to get package information and install
12963         * location values. Override install location based on default
12964         * policy if needed and then create install arguments based
12965         * on the install location.
12966         */
12967        public void handleStartCopy() throws RemoteException {
12968            int ret = PackageManager.INSTALL_SUCCEEDED;
12969
12970            // If we're already staged, we've firmly committed to an install location
12971            if (origin.staged) {
12972                if (origin.file != null) {
12973                    installFlags |= PackageManager.INSTALL_INTERNAL;
12974                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12975                } else if (origin.cid != null) {
12976                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12977                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12978                } else {
12979                    throw new IllegalStateException("Invalid stage location");
12980                }
12981            }
12982
12983            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12984            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12985            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12986            PackageInfoLite pkgLite = null;
12987
12988            if (onInt && onSd) {
12989                // Check if both bits are set.
12990                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12991                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12992            } else if (onSd && ephemeral) {
12993                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12994                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12995            } else {
12996                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12997                        packageAbiOverride);
12998
12999                if (DEBUG_EPHEMERAL && ephemeral) {
13000                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13001                }
13002
13003                /*
13004                 * If we have too little free space, try to free cache
13005                 * before giving up.
13006                 */
13007                if (!origin.staged && pkgLite.recommendedInstallLocation
13008                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13009                    // TODO: focus freeing disk space on the target device
13010                    final StorageManager storage = StorageManager.from(mContext);
13011                    final long lowThreshold = storage.getStorageLowBytes(
13012                            Environment.getDataDirectory());
13013
13014                    final long sizeBytes = mContainerService.calculateInstalledSize(
13015                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13016
13017                    try {
13018                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13019                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13020                                installFlags, packageAbiOverride);
13021                    } catch (InstallerException e) {
13022                        Slog.w(TAG, "Failed to free cache", e);
13023                    }
13024
13025                    /*
13026                     * The cache free must have deleted the file we
13027                     * downloaded to install.
13028                     *
13029                     * TODO: fix the "freeCache" call to not delete
13030                     *       the file we care about.
13031                     */
13032                    if (pkgLite.recommendedInstallLocation
13033                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13034                        pkgLite.recommendedInstallLocation
13035                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13036                    }
13037                }
13038            }
13039
13040            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13041                int loc = pkgLite.recommendedInstallLocation;
13042                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13043                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13044                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13045                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13046                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13047                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13048                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13049                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13050                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13051                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13052                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13053                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13054                } else {
13055                    // Override with defaults if needed.
13056                    loc = installLocationPolicy(pkgLite);
13057                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13058                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13059                    } else if (!onSd && !onInt) {
13060                        // Override install location with flags
13061                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13062                            // Set the flag to install on external media.
13063                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13064                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13065                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13066                            if (DEBUG_EPHEMERAL) {
13067                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13068                            }
13069                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13070                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13071                                    |PackageManager.INSTALL_INTERNAL);
13072                        } else {
13073                            // Make sure the flag for installing on external
13074                            // media is unset
13075                            installFlags |= PackageManager.INSTALL_INTERNAL;
13076                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13077                        }
13078                    }
13079                }
13080            }
13081
13082            final InstallArgs args = createInstallArgs(this);
13083            mArgs = args;
13084
13085            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13086                // TODO: http://b/22976637
13087                // Apps installed for "all" users use the device owner to verify the app
13088                UserHandle verifierUser = getUser();
13089                if (verifierUser == UserHandle.ALL) {
13090                    verifierUser = UserHandle.SYSTEM;
13091                }
13092
13093                /*
13094                 * Determine if we have any installed package verifiers. If we
13095                 * do, then we'll defer to them to verify the packages.
13096                 */
13097                final int requiredUid = mRequiredVerifierPackage == null ? -1
13098                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13099                                verifierUser.getIdentifier());
13100                if (!origin.existing && requiredUid != -1
13101                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13102                    final Intent verification = new Intent(
13103                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13104                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13105                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13106                            PACKAGE_MIME_TYPE);
13107                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13108
13109                    // Query all live verifiers based on current user state
13110                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13111                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13112
13113                    if (DEBUG_VERIFY) {
13114                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13115                                + verification.toString() + " with " + pkgLite.verifiers.length
13116                                + " optional verifiers");
13117                    }
13118
13119                    final int verificationId = mPendingVerificationToken++;
13120
13121                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13122
13123                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13124                            installerPackageName);
13125
13126                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13127                            installFlags);
13128
13129                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13130                            pkgLite.packageName);
13131
13132                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13133                            pkgLite.versionCode);
13134
13135                    if (verificationInfo != null) {
13136                        if (verificationInfo.originatingUri != null) {
13137                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13138                                    verificationInfo.originatingUri);
13139                        }
13140                        if (verificationInfo.referrer != null) {
13141                            verification.putExtra(Intent.EXTRA_REFERRER,
13142                                    verificationInfo.referrer);
13143                        }
13144                        if (verificationInfo.originatingUid >= 0) {
13145                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13146                                    verificationInfo.originatingUid);
13147                        }
13148                        if (verificationInfo.installerUid >= 0) {
13149                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13150                                    verificationInfo.installerUid);
13151                        }
13152                    }
13153
13154                    final PackageVerificationState verificationState = new PackageVerificationState(
13155                            requiredUid, args);
13156
13157                    mPendingVerification.append(verificationId, verificationState);
13158
13159                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13160                            receivers, verificationState);
13161
13162                    /*
13163                     * If any sufficient verifiers were listed in the package
13164                     * manifest, attempt to ask them.
13165                     */
13166                    if (sufficientVerifiers != null) {
13167                        final int N = sufficientVerifiers.size();
13168                        if (N == 0) {
13169                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13170                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13171                        } else {
13172                            for (int i = 0; i < N; i++) {
13173                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13174
13175                                final Intent sufficientIntent = new Intent(verification);
13176                                sufficientIntent.setComponent(verifierComponent);
13177                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13178                            }
13179                        }
13180                    }
13181
13182                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13183                            mRequiredVerifierPackage, receivers);
13184                    if (ret == PackageManager.INSTALL_SUCCEEDED
13185                            && mRequiredVerifierPackage != null) {
13186                        Trace.asyncTraceBegin(
13187                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13188                        /*
13189                         * Send the intent to the required verification agent,
13190                         * but only start the verification timeout after the
13191                         * target BroadcastReceivers have run.
13192                         */
13193                        verification.setComponent(requiredVerifierComponent);
13194                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13195                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13196                                new BroadcastReceiver() {
13197                                    @Override
13198                                    public void onReceive(Context context, Intent intent) {
13199                                        final Message msg = mHandler
13200                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13201                                        msg.arg1 = verificationId;
13202                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13203                                    }
13204                                }, null, 0, null, null);
13205
13206                        /*
13207                         * We don't want the copy to proceed until verification
13208                         * succeeds, so null out this field.
13209                         */
13210                        mArgs = null;
13211                    }
13212                } else {
13213                    /*
13214                     * No package verification is enabled, so immediately start
13215                     * the remote call to initiate copy using temporary file.
13216                     */
13217                    ret = args.copyApk(mContainerService, true);
13218                }
13219            }
13220
13221            mRet = ret;
13222        }
13223
13224        @Override
13225        void handleReturnCode() {
13226            // If mArgs is null, then MCS couldn't be reached. When it
13227            // reconnects, it will try again to install. At that point, this
13228            // will succeed.
13229            if (mArgs != null) {
13230                processPendingInstall(mArgs, mRet);
13231            }
13232        }
13233
13234        @Override
13235        void handleServiceError() {
13236            mArgs = createInstallArgs(this);
13237            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13238        }
13239
13240        public boolean isForwardLocked() {
13241            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13242        }
13243    }
13244
13245    /**
13246     * Used during creation of InstallArgs
13247     *
13248     * @param installFlags package installation flags
13249     * @return true if should be installed on external storage
13250     */
13251    private static boolean installOnExternalAsec(int installFlags) {
13252        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13253            return false;
13254        }
13255        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13256            return true;
13257        }
13258        return false;
13259    }
13260
13261    /**
13262     * Used during creation of InstallArgs
13263     *
13264     * @param installFlags package installation flags
13265     * @return true if should be installed as forward locked
13266     */
13267    private static boolean installForwardLocked(int installFlags) {
13268        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13269    }
13270
13271    private InstallArgs createInstallArgs(InstallParams params) {
13272        if (params.move != null) {
13273            return new MoveInstallArgs(params);
13274        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13275            return new AsecInstallArgs(params);
13276        } else {
13277            return new FileInstallArgs(params);
13278        }
13279    }
13280
13281    /**
13282     * Create args that describe an existing installed package. Typically used
13283     * when cleaning up old installs, or used as a move source.
13284     */
13285    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13286            String resourcePath, String[] instructionSets) {
13287        final boolean isInAsec;
13288        if (installOnExternalAsec(installFlags)) {
13289            /* Apps on SD card are always in ASEC containers. */
13290            isInAsec = true;
13291        } else if (installForwardLocked(installFlags)
13292                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13293            /*
13294             * Forward-locked apps are only in ASEC containers if they're the
13295             * new style
13296             */
13297            isInAsec = true;
13298        } else {
13299            isInAsec = false;
13300        }
13301
13302        if (isInAsec) {
13303            return new AsecInstallArgs(codePath, instructionSets,
13304                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13305        } else {
13306            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13307        }
13308    }
13309
13310    static abstract class InstallArgs {
13311        /** @see InstallParams#origin */
13312        final OriginInfo origin;
13313        /** @see InstallParams#move */
13314        final MoveInfo move;
13315
13316        final IPackageInstallObserver2 observer;
13317        // Always refers to PackageManager flags only
13318        final int installFlags;
13319        final String installerPackageName;
13320        final String volumeUuid;
13321        final UserHandle user;
13322        final String abiOverride;
13323        final String[] installGrantPermissions;
13324        /** If non-null, drop an async trace when the install completes */
13325        final String traceMethod;
13326        final int traceCookie;
13327        final Certificate[][] certificates;
13328
13329        // The list of instruction sets supported by this app. This is currently
13330        // only used during the rmdex() phase to clean up resources. We can get rid of this
13331        // if we move dex files under the common app path.
13332        /* nullable */ String[] instructionSets;
13333
13334        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13335                int installFlags, String installerPackageName, String volumeUuid,
13336                UserHandle user, String[] instructionSets,
13337                String abiOverride, String[] installGrantPermissions,
13338                String traceMethod, int traceCookie, Certificate[][] certificates) {
13339            this.origin = origin;
13340            this.move = move;
13341            this.installFlags = installFlags;
13342            this.observer = observer;
13343            this.installerPackageName = installerPackageName;
13344            this.volumeUuid = volumeUuid;
13345            this.user = user;
13346            this.instructionSets = instructionSets;
13347            this.abiOverride = abiOverride;
13348            this.installGrantPermissions = installGrantPermissions;
13349            this.traceMethod = traceMethod;
13350            this.traceCookie = traceCookie;
13351            this.certificates = certificates;
13352        }
13353
13354        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13355        abstract int doPreInstall(int status);
13356
13357        /**
13358         * Rename package into final resting place. All paths on the given
13359         * scanned package should be updated to reflect the rename.
13360         */
13361        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13362        abstract int doPostInstall(int status, int uid);
13363
13364        /** @see PackageSettingBase#codePathString */
13365        abstract String getCodePath();
13366        /** @see PackageSettingBase#resourcePathString */
13367        abstract String getResourcePath();
13368
13369        // Need installer lock especially for dex file removal.
13370        abstract void cleanUpResourcesLI();
13371        abstract boolean doPostDeleteLI(boolean delete);
13372
13373        /**
13374         * Called before the source arguments are copied. This is used mostly
13375         * for MoveParams when it needs to read the source file to put it in the
13376         * destination.
13377         */
13378        int doPreCopy() {
13379            return PackageManager.INSTALL_SUCCEEDED;
13380        }
13381
13382        /**
13383         * Called after the source arguments are copied. This is used mostly for
13384         * MoveParams when it needs to read the source file to put it in the
13385         * destination.
13386         */
13387        int doPostCopy(int uid) {
13388            return PackageManager.INSTALL_SUCCEEDED;
13389        }
13390
13391        protected boolean isFwdLocked() {
13392            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13393        }
13394
13395        protected boolean isExternalAsec() {
13396            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13397        }
13398
13399        protected boolean isEphemeral() {
13400            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13401        }
13402
13403        UserHandle getUser() {
13404            return user;
13405        }
13406    }
13407
13408    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13409        if (!allCodePaths.isEmpty()) {
13410            if (instructionSets == null) {
13411                throw new IllegalStateException("instructionSet == null");
13412            }
13413            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13414            for (String codePath : allCodePaths) {
13415                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13416                    try {
13417                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13418                    } catch (InstallerException ignored) {
13419                    }
13420                }
13421            }
13422        }
13423    }
13424
13425    /**
13426     * Logic to handle installation of non-ASEC applications, including copying
13427     * and renaming logic.
13428     */
13429    class FileInstallArgs extends InstallArgs {
13430        private File codeFile;
13431        private File resourceFile;
13432
13433        // Example topology:
13434        // /data/app/com.example/base.apk
13435        // /data/app/com.example/split_foo.apk
13436        // /data/app/com.example/lib/arm/libfoo.so
13437        // /data/app/com.example/lib/arm64/libfoo.so
13438        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13439
13440        /** New install */
13441        FileInstallArgs(InstallParams params) {
13442            super(params.origin, params.move, params.observer, params.installFlags,
13443                    params.installerPackageName, params.volumeUuid,
13444                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13445                    params.grantedRuntimePermissions,
13446                    params.traceMethod, params.traceCookie, params.certificates);
13447            if (isFwdLocked()) {
13448                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13449            }
13450        }
13451
13452        /** Existing install */
13453        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13454            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13455                    null, null, null, 0, null /*certificates*/);
13456            this.codeFile = (codePath != null) ? new File(codePath) : null;
13457            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13458        }
13459
13460        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13461            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13462            try {
13463                return doCopyApk(imcs, temp);
13464            } finally {
13465                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13466            }
13467        }
13468
13469        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13470            if (origin.staged) {
13471                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13472                codeFile = origin.file;
13473                resourceFile = origin.file;
13474                return PackageManager.INSTALL_SUCCEEDED;
13475            }
13476
13477            try {
13478                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13479                final File tempDir =
13480                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13481                codeFile = tempDir;
13482                resourceFile = tempDir;
13483            } catch (IOException e) {
13484                Slog.w(TAG, "Failed to create copy file: " + e);
13485                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13486            }
13487
13488            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13489                @Override
13490                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13491                    if (!FileUtils.isValidExtFilename(name)) {
13492                        throw new IllegalArgumentException("Invalid filename: " + name);
13493                    }
13494                    try {
13495                        final File file = new File(codeFile, name);
13496                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13497                                O_RDWR | O_CREAT, 0644);
13498                        Os.chmod(file.getAbsolutePath(), 0644);
13499                        return new ParcelFileDescriptor(fd);
13500                    } catch (ErrnoException e) {
13501                        throw new RemoteException("Failed to open: " + e.getMessage());
13502                    }
13503                }
13504            };
13505
13506            int ret = PackageManager.INSTALL_SUCCEEDED;
13507            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13508            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13509                Slog.e(TAG, "Failed to copy package");
13510                return ret;
13511            }
13512
13513            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13514            NativeLibraryHelper.Handle handle = null;
13515            try {
13516                handle = NativeLibraryHelper.Handle.create(codeFile);
13517                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13518                        abiOverride);
13519            } catch (IOException e) {
13520                Slog.e(TAG, "Copying native libraries failed", e);
13521                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13522            } finally {
13523                IoUtils.closeQuietly(handle);
13524            }
13525
13526            return ret;
13527        }
13528
13529        int doPreInstall(int status) {
13530            if (status != PackageManager.INSTALL_SUCCEEDED) {
13531                cleanUp();
13532            }
13533            return status;
13534        }
13535
13536        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13537            if (status != PackageManager.INSTALL_SUCCEEDED) {
13538                cleanUp();
13539                return false;
13540            }
13541
13542            final File targetDir = codeFile.getParentFile();
13543            final File beforeCodeFile = codeFile;
13544            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13545
13546            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13547            try {
13548                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13549            } catch (ErrnoException e) {
13550                Slog.w(TAG, "Failed to rename", e);
13551                return false;
13552            }
13553
13554            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13555                Slog.w(TAG, "Failed to restorecon");
13556                return false;
13557            }
13558
13559            // Reflect the rename internally
13560            codeFile = afterCodeFile;
13561            resourceFile = afterCodeFile;
13562
13563            // Reflect the rename in scanned details
13564            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13565            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13566                    afterCodeFile, pkg.baseCodePath));
13567            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13568                    afterCodeFile, pkg.splitCodePaths));
13569
13570            // Reflect the rename in app info
13571            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13572            pkg.setApplicationInfoCodePath(pkg.codePath);
13573            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13574            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13575            pkg.setApplicationInfoResourcePath(pkg.codePath);
13576            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13577            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13578
13579            return true;
13580        }
13581
13582        int doPostInstall(int status, int uid) {
13583            if (status != PackageManager.INSTALL_SUCCEEDED) {
13584                cleanUp();
13585            }
13586            return status;
13587        }
13588
13589        @Override
13590        String getCodePath() {
13591            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13592        }
13593
13594        @Override
13595        String getResourcePath() {
13596            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13597        }
13598
13599        private boolean cleanUp() {
13600            if (codeFile == null || !codeFile.exists()) {
13601                return false;
13602            }
13603
13604            removeCodePathLI(codeFile);
13605
13606            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13607                resourceFile.delete();
13608            }
13609
13610            return true;
13611        }
13612
13613        void cleanUpResourcesLI() {
13614            // Try enumerating all code paths before deleting
13615            List<String> allCodePaths = Collections.EMPTY_LIST;
13616            if (codeFile != null && codeFile.exists()) {
13617                try {
13618                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13619                    allCodePaths = pkg.getAllCodePaths();
13620                } catch (PackageParserException e) {
13621                    // Ignored; we tried our best
13622                }
13623            }
13624
13625            cleanUp();
13626            removeDexFiles(allCodePaths, instructionSets);
13627        }
13628
13629        boolean doPostDeleteLI(boolean delete) {
13630            // XXX err, shouldn't we respect the delete flag?
13631            cleanUpResourcesLI();
13632            return true;
13633        }
13634    }
13635
13636    private boolean isAsecExternal(String cid) {
13637        final String asecPath = PackageHelper.getSdFilesystem(cid);
13638        return !asecPath.startsWith(mAsecInternalPath);
13639    }
13640
13641    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13642            PackageManagerException {
13643        if (copyRet < 0) {
13644            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13645                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13646                throw new PackageManagerException(copyRet, message);
13647            }
13648        }
13649    }
13650
13651    /**
13652     * Extract the MountService "container ID" from the full code path of an
13653     * .apk.
13654     */
13655    static String cidFromCodePath(String fullCodePath) {
13656        int eidx = fullCodePath.lastIndexOf("/");
13657        String subStr1 = fullCodePath.substring(0, eidx);
13658        int sidx = subStr1.lastIndexOf("/");
13659        return subStr1.substring(sidx+1, eidx);
13660    }
13661
13662    /**
13663     * Logic to handle installation of ASEC applications, including copying and
13664     * renaming logic.
13665     */
13666    class AsecInstallArgs extends InstallArgs {
13667        static final String RES_FILE_NAME = "pkg.apk";
13668        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13669
13670        String cid;
13671        String packagePath;
13672        String resourcePath;
13673
13674        /** New install */
13675        AsecInstallArgs(InstallParams params) {
13676            super(params.origin, params.move, params.observer, params.installFlags,
13677                    params.installerPackageName, params.volumeUuid,
13678                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13679                    params.grantedRuntimePermissions,
13680                    params.traceMethod, params.traceCookie, params.certificates);
13681        }
13682
13683        /** Existing install */
13684        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13685                        boolean isExternal, boolean isForwardLocked) {
13686            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13687              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13688                    instructionSets, null, null, null, 0, null /*certificates*/);
13689            // Hackily pretend we're still looking at a full code path
13690            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13691                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13692            }
13693
13694            // Extract cid from fullCodePath
13695            int eidx = fullCodePath.lastIndexOf("/");
13696            String subStr1 = fullCodePath.substring(0, eidx);
13697            int sidx = subStr1.lastIndexOf("/");
13698            cid = subStr1.substring(sidx+1, eidx);
13699            setMountPath(subStr1);
13700        }
13701
13702        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13703            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13704              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13705                    instructionSets, null, null, null, 0, null /*certificates*/);
13706            this.cid = cid;
13707            setMountPath(PackageHelper.getSdDir(cid));
13708        }
13709
13710        void createCopyFile() {
13711            cid = mInstallerService.allocateExternalStageCidLegacy();
13712        }
13713
13714        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13715            if (origin.staged && origin.cid != null) {
13716                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13717                cid = origin.cid;
13718                setMountPath(PackageHelper.getSdDir(cid));
13719                return PackageManager.INSTALL_SUCCEEDED;
13720            }
13721
13722            if (temp) {
13723                createCopyFile();
13724            } else {
13725                /*
13726                 * Pre-emptively destroy the container since it's destroyed if
13727                 * copying fails due to it existing anyway.
13728                 */
13729                PackageHelper.destroySdDir(cid);
13730            }
13731
13732            final String newMountPath = imcs.copyPackageToContainer(
13733                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13734                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13735
13736            if (newMountPath != null) {
13737                setMountPath(newMountPath);
13738                return PackageManager.INSTALL_SUCCEEDED;
13739            } else {
13740                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13741            }
13742        }
13743
13744        @Override
13745        String getCodePath() {
13746            return packagePath;
13747        }
13748
13749        @Override
13750        String getResourcePath() {
13751            return resourcePath;
13752        }
13753
13754        int doPreInstall(int status) {
13755            if (status != PackageManager.INSTALL_SUCCEEDED) {
13756                // Destroy container
13757                PackageHelper.destroySdDir(cid);
13758            } else {
13759                boolean mounted = PackageHelper.isContainerMounted(cid);
13760                if (!mounted) {
13761                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13762                            Process.SYSTEM_UID);
13763                    if (newMountPath != null) {
13764                        setMountPath(newMountPath);
13765                    } else {
13766                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13767                    }
13768                }
13769            }
13770            return status;
13771        }
13772
13773        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13774            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13775            String newMountPath = null;
13776            if (PackageHelper.isContainerMounted(cid)) {
13777                // Unmount the container
13778                if (!PackageHelper.unMountSdDir(cid)) {
13779                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13780                    return false;
13781                }
13782            }
13783            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13784                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13785                        " which might be stale. Will try to clean up.");
13786                // Clean up the stale container and proceed to recreate.
13787                if (!PackageHelper.destroySdDir(newCacheId)) {
13788                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13789                    return false;
13790                }
13791                // Successfully cleaned up stale container. Try to rename again.
13792                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13793                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13794                            + " inspite of cleaning it up.");
13795                    return false;
13796                }
13797            }
13798            if (!PackageHelper.isContainerMounted(newCacheId)) {
13799                Slog.w(TAG, "Mounting container " + newCacheId);
13800                newMountPath = PackageHelper.mountSdDir(newCacheId,
13801                        getEncryptKey(), Process.SYSTEM_UID);
13802            } else {
13803                newMountPath = PackageHelper.getSdDir(newCacheId);
13804            }
13805            if (newMountPath == null) {
13806                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13807                return false;
13808            }
13809            Log.i(TAG, "Succesfully renamed " + cid +
13810                    " to " + newCacheId +
13811                    " at new path: " + newMountPath);
13812            cid = newCacheId;
13813
13814            final File beforeCodeFile = new File(packagePath);
13815            setMountPath(newMountPath);
13816            final File afterCodeFile = new File(packagePath);
13817
13818            // Reflect the rename in scanned details
13819            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13820            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13821                    afterCodeFile, pkg.baseCodePath));
13822            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13823                    afterCodeFile, pkg.splitCodePaths));
13824
13825            // Reflect the rename in app info
13826            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13827            pkg.setApplicationInfoCodePath(pkg.codePath);
13828            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13829            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13830            pkg.setApplicationInfoResourcePath(pkg.codePath);
13831            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13832            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13833
13834            return true;
13835        }
13836
13837        private void setMountPath(String mountPath) {
13838            final File mountFile = new File(mountPath);
13839
13840            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13841            if (monolithicFile.exists()) {
13842                packagePath = monolithicFile.getAbsolutePath();
13843                if (isFwdLocked()) {
13844                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13845                } else {
13846                    resourcePath = packagePath;
13847                }
13848            } else {
13849                packagePath = mountFile.getAbsolutePath();
13850                resourcePath = packagePath;
13851            }
13852        }
13853
13854        int doPostInstall(int status, int uid) {
13855            if (status != PackageManager.INSTALL_SUCCEEDED) {
13856                cleanUp();
13857            } else {
13858                final int groupOwner;
13859                final String protectedFile;
13860                if (isFwdLocked()) {
13861                    groupOwner = UserHandle.getSharedAppGid(uid);
13862                    protectedFile = RES_FILE_NAME;
13863                } else {
13864                    groupOwner = -1;
13865                    protectedFile = null;
13866                }
13867
13868                if (uid < Process.FIRST_APPLICATION_UID
13869                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13870                    Slog.e(TAG, "Failed to finalize " + cid);
13871                    PackageHelper.destroySdDir(cid);
13872                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13873                }
13874
13875                boolean mounted = PackageHelper.isContainerMounted(cid);
13876                if (!mounted) {
13877                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13878                }
13879            }
13880            return status;
13881        }
13882
13883        private void cleanUp() {
13884            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13885
13886            // Destroy secure container
13887            PackageHelper.destroySdDir(cid);
13888        }
13889
13890        private List<String> getAllCodePaths() {
13891            final File codeFile = new File(getCodePath());
13892            if (codeFile != null && codeFile.exists()) {
13893                try {
13894                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13895                    return pkg.getAllCodePaths();
13896                } catch (PackageParserException e) {
13897                    // Ignored; we tried our best
13898                }
13899            }
13900            return Collections.EMPTY_LIST;
13901        }
13902
13903        void cleanUpResourcesLI() {
13904            // Enumerate all code paths before deleting
13905            cleanUpResourcesLI(getAllCodePaths());
13906        }
13907
13908        private void cleanUpResourcesLI(List<String> allCodePaths) {
13909            cleanUp();
13910            removeDexFiles(allCodePaths, instructionSets);
13911        }
13912
13913        String getPackageName() {
13914            return getAsecPackageName(cid);
13915        }
13916
13917        boolean doPostDeleteLI(boolean delete) {
13918            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13919            final List<String> allCodePaths = getAllCodePaths();
13920            boolean mounted = PackageHelper.isContainerMounted(cid);
13921            if (mounted) {
13922                // Unmount first
13923                if (PackageHelper.unMountSdDir(cid)) {
13924                    mounted = false;
13925                }
13926            }
13927            if (!mounted && delete) {
13928                cleanUpResourcesLI(allCodePaths);
13929            }
13930            return !mounted;
13931        }
13932
13933        @Override
13934        int doPreCopy() {
13935            if (isFwdLocked()) {
13936                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13937                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13938                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13939                }
13940            }
13941
13942            return PackageManager.INSTALL_SUCCEEDED;
13943        }
13944
13945        @Override
13946        int doPostCopy(int uid) {
13947            if (isFwdLocked()) {
13948                if (uid < Process.FIRST_APPLICATION_UID
13949                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13950                                RES_FILE_NAME)) {
13951                    Slog.e(TAG, "Failed to finalize " + cid);
13952                    PackageHelper.destroySdDir(cid);
13953                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13954                }
13955            }
13956
13957            return PackageManager.INSTALL_SUCCEEDED;
13958        }
13959    }
13960
13961    /**
13962     * Logic to handle movement of existing installed applications.
13963     */
13964    class MoveInstallArgs extends InstallArgs {
13965        private File codeFile;
13966        private File resourceFile;
13967
13968        /** New install */
13969        MoveInstallArgs(InstallParams params) {
13970            super(params.origin, params.move, params.observer, params.installFlags,
13971                    params.installerPackageName, params.volumeUuid,
13972                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13973                    params.grantedRuntimePermissions,
13974                    params.traceMethod, params.traceCookie, params.certificates);
13975        }
13976
13977        int copyApk(IMediaContainerService imcs, boolean temp) {
13978            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13979                    + move.fromUuid + " to " + move.toUuid);
13980            synchronized (mInstaller) {
13981                try {
13982                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13983                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13984                } catch (InstallerException e) {
13985                    Slog.w(TAG, "Failed to move app", e);
13986                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13987                }
13988            }
13989
13990            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13991            resourceFile = codeFile;
13992            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13993
13994            return PackageManager.INSTALL_SUCCEEDED;
13995        }
13996
13997        int doPreInstall(int status) {
13998            if (status != PackageManager.INSTALL_SUCCEEDED) {
13999                cleanUp(move.toUuid);
14000            }
14001            return status;
14002        }
14003
14004        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14005            if (status != PackageManager.INSTALL_SUCCEEDED) {
14006                cleanUp(move.toUuid);
14007                return false;
14008            }
14009
14010            // Reflect the move in app info
14011            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14012            pkg.setApplicationInfoCodePath(pkg.codePath);
14013            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14014            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14015            pkg.setApplicationInfoResourcePath(pkg.codePath);
14016            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14017            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14018
14019            return true;
14020        }
14021
14022        int doPostInstall(int status, int uid) {
14023            if (status == PackageManager.INSTALL_SUCCEEDED) {
14024                cleanUp(move.fromUuid);
14025            } else {
14026                cleanUp(move.toUuid);
14027            }
14028            return status;
14029        }
14030
14031        @Override
14032        String getCodePath() {
14033            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14034        }
14035
14036        @Override
14037        String getResourcePath() {
14038            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14039        }
14040
14041        private boolean cleanUp(String volumeUuid) {
14042            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14043                    move.dataAppName);
14044            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14045            final int[] userIds = sUserManager.getUserIds();
14046            synchronized (mInstallLock) {
14047                // Clean up both app data and code
14048                // All package moves are frozen until finished
14049                for (int userId : userIds) {
14050                    try {
14051                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14052                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14053                    } catch (InstallerException e) {
14054                        Slog.w(TAG, String.valueOf(e));
14055                    }
14056                }
14057                removeCodePathLI(codeFile);
14058            }
14059            return true;
14060        }
14061
14062        void cleanUpResourcesLI() {
14063            throw new UnsupportedOperationException();
14064        }
14065
14066        boolean doPostDeleteLI(boolean delete) {
14067            throw new UnsupportedOperationException();
14068        }
14069    }
14070
14071    static String getAsecPackageName(String packageCid) {
14072        int idx = packageCid.lastIndexOf("-");
14073        if (idx == -1) {
14074            return packageCid;
14075        }
14076        return packageCid.substring(0, idx);
14077    }
14078
14079    // Utility method used to create code paths based on package name and available index.
14080    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14081        String idxStr = "";
14082        int idx = 1;
14083        // Fall back to default value of idx=1 if prefix is not
14084        // part of oldCodePath
14085        if (oldCodePath != null) {
14086            String subStr = oldCodePath;
14087            // Drop the suffix right away
14088            if (suffix != null && subStr.endsWith(suffix)) {
14089                subStr = subStr.substring(0, subStr.length() - suffix.length());
14090            }
14091            // If oldCodePath already contains prefix find out the
14092            // ending index to either increment or decrement.
14093            int sidx = subStr.lastIndexOf(prefix);
14094            if (sidx != -1) {
14095                subStr = subStr.substring(sidx + prefix.length());
14096                if (subStr != null) {
14097                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14098                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14099                    }
14100                    try {
14101                        idx = Integer.parseInt(subStr);
14102                        if (idx <= 1) {
14103                            idx++;
14104                        } else {
14105                            idx--;
14106                        }
14107                    } catch(NumberFormatException e) {
14108                    }
14109                }
14110            }
14111        }
14112        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14113        return prefix + idxStr;
14114    }
14115
14116    private File getNextCodePath(File targetDir, String packageName) {
14117        int suffix = 1;
14118        File result;
14119        do {
14120            result = new File(targetDir, packageName + "-" + suffix);
14121            suffix++;
14122        } while (result.exists());
14123        return result;
14124    }
14125
14126    // Utility method that returns the relative package path with respect
14127    // to the installation directory. Like say for /data/data/com.test-1.apk
14128    // string com.test-1 is returned.
14129    static String deriveCodePathName(String codePath) {
14130        if (codePath == null) {
14131            return null;
14132        }
14133        final File codeFile = new File(codePath);
14134        final String name = codeFile.getName();
14135        if (codeFile.isDirectory()) {
14136            return name;
14137        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14138            final int lastDot = name.lastIndexOf('.');
14139            return name.substring(0, lastDot);
14140        } else {
14141            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14142            return null;
14143        }
14144    }
14145
14146    static class PackageInstalledInfo {
14147        String name;
14148        int uid;
14149        // The set of users that originally had this package installed.
14150        int[] origUsers;
14151        // The set of users that now have this package installed.
14152        int[] newUsers;
14153        PackageParser.Package pkg;
14154        int returnCode;
14155        String returnMsg;
14156        PackageRemovedInfo removedInfo;
14157        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14158
14159        public void setError(int code, String msg) {
14160            setReturnCode(code);
14161            setReturnMessage(msg);
14162            Slog.w(TAG, msg);
14163        }
14164
14165        public void setError(String msg, PackageParserException e) {
14166            setReturnCode(e.error);
14167            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14168            Slog.w(TAG, msg, e);
14169        }
14170
14171        public void setError(String msg, PackageManagerException e) {
14172            returnCode = e.error;
14173            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14174            Slog.w(TAG, msg, e);
14175        }
14176
14177        public void setReturnCode(int returnCode) {
14178            this.returnCode = returnCode;
14179            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14180            for (int i = 0; i < childCount; i++) {
14181                addedChildPackages.valueAt(i).returnCode = returnCode;
14182            }
14183        }
14184
14185        private void setReturnMessage(String returnMsg) {
14186            this.returnMsg = returnMsg;
14187            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14188            for (int i = 0; i < childCount; i++) {
14189                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14190            }
14191        }
14192
14193        // In some error cases we want to convey more info back to the observer
14194        String origPackage;
14195        String origPermission;
14196    }
14197
14198    /*
14199     * Install a non-existing package.
14200     */
14201    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14202            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14203            PackageInstalledInfo res) {
14204        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14205
14206        // Remember this for later, in case we need to rollback this install
14207        String pkgName = pkg.packageName;
14208
14209        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14210
14211        synchronized(mPackages) {
14212            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14213            if (renamedPackage != null) {
14214                // A package with the same name is already installed, though
14215                // it has been renamed to an older name.  The package we
14216                // are trying to install should be installed as an update to
14217                // the existing one, but that has not been requested, so bail.
14218                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14219                        + " without first uninstalling package running as "
14220                        + renamedPackage);
14221                return;
14222            }
14223            if (mPackages.containsKey(pkgName)) {
14224                // Don't allow installation over an existing package with the same name.
14225                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14226                        + " without first uninstalling.");
14227                return;
14228            }
14229        }
14230
14231        try {
14232            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14233                    System.currentTimeMillis(), user);
14234
14235            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14236
14237            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14238                prepareAppDataAfterInstallLIF(newPackage);
14239
14240            } else {
14241                // Remove package from internal structures, but keep around any
14242                // data that might have already existed
14243                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14244                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14245            }
14246        } catch (PackageManagerException e) {
14247            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14248        }
14249
14250        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14251    }
14252
14253    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14254        // Can't rotate keys during boot or if sharedUser.
14255        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14256                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14257            return false;
14258        }
14259        // app is using upgradeKeySets; make sure all are valid
14260        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14261        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14262        for (int i = 0; i < upgradeKeySets.length; i++) {
14263            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14264                Slog.wtf(TAG, "Package "
14265                         + (oldPs.name != null ? oldPs.name : "<null>")
14266                         + " contains upgrade-key-set reference to unknown key-set: "
14267                         + upgradeKeySets[i]
14268                         + " reverting to signatures check.");
14269                return false;
14270            }
14271        }
14272        return true;
14273    }
14274
14275    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14276        // Upgrade keysets are being used.  Determine if new package has a superset of the
14277        // required keys.
14278        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14279        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14280        for (int i = 0; i < upgradeKeySets.length; i++) {
14281            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14282            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14283                return true;
14284            }
14285        }
14286        return false;
14287    }
14288
14289    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14290        try (DigestInputStream digestStream =
14291                new DigestInputStream(new FileInputStream(file), digest)) {
14292            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14293        }
14294    }
14295
14296    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14297            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14298        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14299
14300        final PackageParser.Package oldPackage;
14301        final String pkgName = pkg.packageName;
14302        final int[] allUsers;
14303        final int[] installedUsers;
14304
14305        synchronized(mPackages) {
14306            oldPackage = mPackages.get(pkgName);
14307            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14308
14309            // don't allow upgrade to target a release SDK from a pre-release SDK
14310            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14311                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14312            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14313                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14314            if (oldTargetsPreRelease
14315                    && !newTargetsPreRelease
14316                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14317                Slog.w(TAG, "Can't install package targeting released sdk");
14318                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14319                return;
14320            }
14321
14322            // don't allow an upgrade from full to ephemeral
14323            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14324            if (isEphemeral && !oldIsEphemeral) {
14325                // can't downgrade from full to ephemeral
14326                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14327                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14328                return;
14329            }
14330
14331            // verify signatures are valid
14332            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14333            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14334                if (!checkUpgradeKeySetLP(ps, pkg)) {
14335                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14336                            "New package not signed by keys specified by upgrade-keysets: "
14337                                    + pkgName);
14338                    return;
14339                }
14340            } else {
14341                // default to original signature matching
14342                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14343                        != PackageManager.SIGNATURE_MATCH) {
14344                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14345                            "New package has a different signature: " + pkgName);
14346                    return;
14347                }
14348            }
14349
14350            // don't allow a system upgrade unless the upgrade hash matches
14351            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14352                byte[] digestBytes = null;
14353                try {
14354                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14355                    updateDigest(digest, new File(pkg.baseCodePath));
14356                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14357                        for (String path : pkg.splitCodePaths) {
14358                            updateDigest(digest, new File(path));
14359                        }
14360                    }
14361                    digestBytes = digest.digest();
14362                } catch (NoSuchAlgorithmException | IOException e) {
14363                    res.setError(INSTALL_FAILED_INVALID_APK,
14364                            "Could not compute hash: " + pkgName);
14365                    return;
14366                }
14367                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14368                    res.setError(INSTALL_FAILED_INVALID_APK,
14369                            "New package fails restrict-update check: " + pkgName);
14370                    return;
14371                }
14372                // retain upgrade restriction
14373                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14374            }
14375
14376            // Check for shared user id changes
14377            String invalidPackageName =
14378                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14379            if (invalidPackageName != null) {
14380                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14381                        "Package " + invalidPackageName + " tried to change user "
14382                                + oldPackage.mSharedUserId);
14383                return;
14384            }
14385
14386            // In case of rollback, remember per-user/profile install state
14387            allUsers = sUserManager.getUserIds();
14388            installedUsers = ps.queryInstalledUsers(allUsers, true);
14389        }
14390
14391        // Update what is removed
14392        res.removedInfo = new PackageRemovedInfo();
14393        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14394        res.removedInfo.removedPackage = oldPackage.packageName;
14395        res.removedInfo.isUpdate = true;
14396        res.removedInfo.origUsers = installedUsers;
14397        final int childCount = (oldPackage.childPackages != null)
14398                ? oldPackage.childPackages.size() : 0;
14399        for (int i = 0; i < childCount; i++) {
14400            boolean childPackageUpdated = false;
14401            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14402            if (res.addedChildPackages != null) {
14403                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14404                if (childRes != null) {
14405                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14406                    childRes.removedInfo.removedPackage = childPkg.packageName;
14407                    childRes.removedInfo.isUpdate = true;
14408                    childPackageUpdated = true;
14409                }
14410            }
14411            if (!childPackageUpdated) {
14412                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14413                childRemovedRes.removedPackage = childPkg.packageName;
14414                childRemovedRes.isUpdate = false;
14415                childRemovedRes.dataRemoved = true;
14416                synchronized (mPackages) {
14417                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14418                    if (childPs != null) {
14419                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14420                    }
14421                }
14422                if (res.removedInfo.removedChildPackages == null) {
14423                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14424                }
14425                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14426            }
14427        }
14428
14429        boolean sysPkg = (isSystemApp(oldPackage));
14430        if (sysPkg) {
14431            // Set the system/privileged flags as needed
14432            final boolean privileged =
14433                    (oldPackage.applicationInfo.privateFlags
14434                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14435            final int systemPolicyFlags = policyFlags
14436                    | PackageParser.PARSE_IS_SYSTEM
14437                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14438
14439            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14440                    user, allUsers, installerPackageName, res);
14441        } else {
14442            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14443                    user, allUsers, installerPackageName, res);
14444        }
14445    }
14446
14447    public List<String> getPreviousCodePaths(String packageName) {
14448        final PackageSetting ps = mSettings.mPackages.get(packageName);
14449        final List<String> result = new ArrayList<String>();
14450        if (ps != null && ps.oldCodePaths != null) {
14451            result.addAll(ps.oldCodePaths);
14452        }
14453        return result;
14454    }
14455
14456    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14457            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14458            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14459        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14460                + deletedPackage);
14461
14462        String pkgName = deletedPackage.packageName;
14463        boolean deletedPkg = true;
14464        boolean addedPkg = false;
14465        boolean updatedSettings = false;
14466        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14467        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14468                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14469
14470        final long origUpdateTime = (pkg.mExtras != null)
14471                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14472
14473        // First delete the existing package while retaining the data directory
14474        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14475                res.removedInfo, true, pkg)) {
14476            // If the existing package wasn't successfully deleted
14477            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14478            deletedPkg = false;
14479        } else {
14480            // Successfully deleted the old package; proceed with replace.
14481
14482            // If deleted package lived in a container, give users a chance to
14483            // relinquish resources before killing.
14484            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14485                if (DEBUG_INSTALL) {
14486                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14487                }
14488                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14489                final ArrayList<String> pkgList = new ArrayList<String>(1);
14490                pkgList.add(deletedPackage.applicationInfo.packageName);
14491                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14492            }
14493
14494            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14495                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14496            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14497
14498            try {
14499                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14500                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14501                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14502
14503                // Update the in-memory copy of the previous code paths.
14504                PackageSetting ps = mSettings.mPackages.get(pkgName);
14505                if (!killApp) {
14506                    if (ps.oldCodePaths == null) {
14507                        ps.oldCodePaths = new ArraySet<>();
14508                    }
14509                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14510                    if (deletedPackage.splitCodePaths != null) {
14511                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14512                    }
14513                } else {
14514                    ps.oldCodePaths = null;
14515                }
14516                if (ps.childPackageNames != null) {
14517                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14518                        final String childPkgName = ps.childPackageNames.get(i);
14519                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14520                        childPs.oldCodePaths = ps.oldCodePaths;
14521                    }
14522                }
14523                prepareAppDataAfterInstallLIF(newPackage);
14524                addedPkg = true;
14525            } catch (PackageManagerException e) {
14526                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14527            }
14528        }
14529
14530        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14531            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14532
14533            // Revert all internal state mutations and added folders for the failed install
14534            if (addedPkg) {
14535                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14536                        res.removedInfo, true, null);
14537            }
14538
14539            // Restore the old package
14540            if (deletedPkg) {
14541                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14542                File restoreFile = new File(deletedPackage.codePath);
14543                // Parse old package
14544                boolean oldExternal = isExternal(deletedPackage);
14545                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14546                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14547                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14548                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14549                try {
14550                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14551                            null);
14552                } catch (PackageManagerException e) {
14553                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14554                            + e.getMessage());
14555                    return;
14556                }
14557
14558                synchronized (mPackages) {
14559                    // Ensure the installer package name up to date
14560                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14561
14562                    // Update permissions for restored package
14563                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14564
14565                    mSettings.writeLPr();
14566                }
14567
14568                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14569            }
14570        } else {
14571            synchronized (mPackages) {
14572                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14573                if (ps != null) {
14574                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14575                    if (res.removedInfo.removedChildPackages != null) {
14576                        final int childCount = res.removedInfo.removedChildPackages.size();
14577                        // Iterate in reverse as we may modify the collection
14578                        for (int i = childCount - 1; i >= 0; i--) {
14579                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14580                            if (res.addedChildPackages.containsKey(childPackageName)) {
14581                                res.removedInfo.removedChildPackages.removeAt(i);
14582                            } else {
14583                                PackageRemovedInfo childInfo = res.removedInfo
14584                                        .removedChildPackages.valueAt(i);
14585                                childInfo.removedForAllUsers = mPackages.get(
14586                                        childInfo.removedPackage) == null;
14587                            }
14588                        }
14589                    }
14590                }
14591            }
14592        }
14593    }
14594
14595    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14596            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14597            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14598        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14599                + ", old=" + deletedPackage);
14600
14601        final boolean disabledSystem;
14602
14603        // Remove existing system package
14604        removePackageLI(deletedPackage, true);
14605
14606        synchronized (mPackages) {
14607            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14608        }
14609        if (!disabledSystem) {
14610            // We didn't need to disable the .apk as a current system package,
14611            // which means we are replacing another update that is already
14612            // installed.  We need to make sure to delete the older one's .apk.
14613            res.removedInfo.args = createInstallArgsForExisting(0,
14614                    deletedPackage.applicationInfo.getCodePath(),
14615                    deletedPackage.applicationInfo.getResourcePath(),
14616                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14617        } else {
14618            res.removedInfo.args = null;
14619        }
14620
14621        // Successfully disabled the old package. Now proceed with re-installation
14622        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14623                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14624        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14625
14626        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14627        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14628                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14629
14630        PackageParser.Package newPackage = null;
14631        try {
14632            // Add the package to the internal data structures
14633            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14634
14635            // Set the update and install times
14636            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14637            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14638                    System.currentTimeMillis());
14639
14640            // Update the package dynamic state if succeeded
14641            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14642                // Now that the install succeeded make sure we remove data
14643                // directories for any child package the update removed.
14644                final int deletedChildCount = (deletedPackage.childPackages != null)
14645                        ? deletedPackage.childPackages.size() : 0;
14646                final int newChildCount = (newPackage.childPackages != null)
14647                        ? newPackage.childPackages.size() : 0;
14648                for (int i = 0; i < deletedChildCount; i++) {
14649                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14650                    boolean childPackageDeleted = true;
14651                    for (int j = 0; j < newChildCount; j++) {
14652                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14653                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14654                            childPackageDeleted = false;
14655                            break;
14656                        }
14657                    }
14658                    if (childPackageDeleted) {
14659                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14660                                deletedChildPkg.packageName);
14661                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14662                            PackageRemovedInfo removedChildRes = res.removedInfo
14663                                    .removedChildPackages.get(deletedChildPkg.packageName);
14664                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14665                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14666                        }
14667                    }
14668                }
14669
14670                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14671                prepareAppDataAfterInstallLIF(newPackage);
14672            }
14673        } catch (PackageManagerException e) {
14674            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14675            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14676        }
14677
14678        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14679            // Re installation failed. Restore old information
14680            // Remove new pkg information
14681            if (newPackage != null) {
14682                removeInstalledPackageLI(newPackage, true);
14683            }
14684            // Add back the old system package
14685            try {
14686                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14687            } catch (PackageManagerException e) {
14688                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14689            }
14690
14691            synchronized (mPackages) {
14692                if (disabledSystem) {
14693                    enableSystemPackageLPw(deletedPackage);
14694                }
14695
14696                // Ensure the installer package name up to date
14697                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14698
14699                // Update permissions for restored package
14700                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14701
14702                mSettings.writeLPr();
14703            }
14704
14705            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14706                    + " after failed upgrade");
14707        }
14708    }
14709
14710    /**
14711     * Checks whether the parent or any of the child packages have a change shared
14712     * user. For a package to be a valid update the shred users of the parent and
14713     * the children should match. We may later support changing child shared users.
14714     * @param oldPkg The updated package.
14715     * @param newPkg The update package.
14716     * @return The shared user that change between the versions.
14717     */
14718    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14719            PackageParser.Package newPkg) {
14720        // Check parent shared user
14721        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14722            return newPkg.packageName;
14723        }
14724        // Check child shared users
14725        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14726        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14727        for (int i = 0; i < newChildCount; i++) {
14728            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14729            // If this child was present, did it have the same shared user?
14730            for (int j = 0; j < oldChildCount; j++) {
14731                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14732                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14733                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14734                    return newChildPkg.packageName;
14735                }
14736            }
14737        }
14738        return null;
14739    }
14740
14741    private void removeNativeBinariesLI(PackageSetting ps) {
14742        // Remove the lib path for the parent package
14743        if (ps != null) {
14744            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14745            // Remove the lib path for the child packages
14746            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14747            for (int i = 0; i < childCount; i++) {
14748                PackageSetting childPs = null;
14749                synchronized (mPackages) {
14750                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14751                }
14752                if (childPs != null) {
14753                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14754                            .legacyNativeLibraryPathString);
14755                }
14756            }
14757        }
14758    }
14759
14760    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14761        // Enable the parent package
14762        mSettings.enableSystemPackageLPw(pkg.packageName);
14763        // Enable the child packages
14764        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14765        for (int i = 0; i < childCount; i++) {
14766            PackageParser.Package childPkg = pkg.childPackages.get(i);
14767            mSettings.enableSystemPackageLPw(childPkg.packageName);
14768        }
14769    }
14770
14771    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14772            PackageParser.Package newPkg) {
14773        // Disable the parent package (parent always replaced)
14774        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14775        // Disable the child packages
14776        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14777        for (int i = 0; i < childCount; i++) {
14778            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14779            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14780            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14781        }
14782        return disabled;
14783    }
14784
14785    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14786            String installerPackageName) {
14787        // Enable the parent package
14788        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14789        // Enable the child packages
14790        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14791        for (int i = 0; i < childCount; i++) {
14792            PackageParser.Package childPkg = pkg.childPackages.get(i);
14793            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14794        }
14795    }
14796
14797    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14798        // Collect all used permissions in the UID
14799        ArraySet<String> usedPermissions = new ArraySet<>();
14800        final int packageCount = su.packages.size();
14801        for (int i = 0; i < packageCount; i++) {
14802            PackageSetting ps = su.packages.valueAt(i);
14803            if (ps.pkg == null) {
14804                continue;
14805            }
14806            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14807            for (int j = 0; j < requestedPermCount; j++) {
14808                String permission = ps.pkg.requestedPermissions.get(j);
14809                BasePermission bp = mSettings.mPermissions.get(permission);
14810                if (bp != null) {
14811                    usedPermissions.add(permission);
14812                }
14813            }
14814        }
14815
14816        PermissionsState permissionsState = su.getPermissionsState();
14817        // Prune install permissions
14818        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14819        final int installPermCount = installPermStates.size();
14820        for (int i = installPermCount - 1; i >= 0;  i--) {
14821            PermissionState permissionState = installPermStates.get(i);
14822            if (!usedPermissions.contains(permissionState.getName())) {
14823                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14824                if (bp != null) {
14825                    permissionsState.revokeInstallPermission(bp);
14826                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14827                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14828                }
14829            }
14830        }
14831
14832        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14833
14834        // Prune runtime permissions
14835        for (int userId : allUserIds) {
14836            List<PermissionState> runtimePermStates = permissionsState
14837                    .getRuntimePermissionStates(userId);
14838            final int runtimePermCount = runtimePermStates.size();
14839            for (int i = runtimePermCount - 1; i >= 0; i--) {
14840                PermissionState permissionState = runtimePermStates.get(i);
14841                if (!usedPermissions.contains(permissionState.getName())) {
14842                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14843                    if (bp != null) {
14844                        permissionsState.revokeRuntimePermission(bp, userId);
14845                        permissionsState.updatePermissionFlags(bp, userId,
14846                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14847                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14848                                runtimePermissionChangedUserIds, userId);
14849                    }
14850                }
14851            }
14852        }
14853
14854        return runtimePermissionChangedUserIds;
14855    }
14856
14857    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14858            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14859        // Update the parent package setting
14860        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14861                res, user);
14862        // Update the child packages setting
14863        final int childCount = (newPackage.childPackages != null)
14864                ? newPackage.childPackages.size() : 0;
14865        for (int i = 0; i < childCount; i++) {
14866            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14867            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14868            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14869                    childRes.origUsers, childRes, user);
14870        }
14871    }
14872
14873    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14874            String installerPackageName, int[] allUsers, int[] installedForUsers,
14875            PackageInstalledInfo res, UserHandle user) {
14876        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14877
14878        String pkgName = newPackage.packageName;
14879        synchronized (mPackages) {
14880            //write settings. the installStatus will be incomplete at this stage.
14881            //note that the new package setting would have already been
14882            //added to mPackages. It hasn't been persisted yet.
14883            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14884            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14885            mSettings.writeLPr();
14886            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14887        }
14888
14889        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14890        synchronized (mPackages) {
14891            updatePermissionsLPw(newPackage.packageName, newPackage,
14892                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14893                            ? UPDATE_PERMISSIONS_ALL : 0));
14894            // For system-bundled packages, we assume that installing an upgraded version
14895            // of the package implies that the user actually wants to run that new code,
14896            // so we enable the package.
14897            PackageSetting ps = mSettings.mPackages.get(pkgName);
14898            final int userId = user.getIdentifier();
14899            if (ps != null) {
14900                if (isSystemApp(newPackage)) {
14901                    if (DEBUG_INSTALL) {
14902                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14903                    }
14904                    // Enable system package for requested users
14905                    if (res.origUsers != null) {
14906                        for (int origUserId : res.origUsers) {
14907                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14908                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14909                                        origUserId, installerPackageName);
14910                            }
14911                        }
14912                    }
14913                    // Also convey the prior install/uninstall state
14914                    if (allUsers != null && installedForUsers != null) {
14915                        for (int currentUserId : allUsers) {
14916                            final boolean installed = ArrayUtils.contains(
14917                                    installedForUsers, currentUserId);
14918                            if (DEBUG_INSTALL) {
14919                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14920                            }
14921                            ps.setInstalled(installed, currentUserId);
14922                        }
14923                        // these install state changes will be persisted in the
14924                        // upcoming call to mSettings.writeLPr().
14925                    }
14926                }
14927                // It's implied that when a user requests installation, they want the app to be
14928                // installed and enabled.
14929                if (userId != UserHandle.USER_ALL) {
14930                    ps.setInstalled(true, userId);
14931                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14932                }
14933            }
14934            res.name = pkgName;
14935            res.uid = newPackage.applicationInfo.uid;
14936            res.pkg = newPackage;
14937            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14938            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14939            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14940            //to update install status
14941            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14942            mSettings.writeLPr();
14943            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14944        }
14945
14946        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14947    }
14948
14949    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14950        try {
14951            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14952            installPackageLI(args, res);
14953        } finally {
14954            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14955        }
14956    }
14957
14958    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14959        final int installFlags = args.installFlags;
14960        final String installerPackageName = args.installerPackageName;
14961        final String volumeUuid = args.volumeUuid;
14962        final File tmpPackageFile = new File(args.getCodePath());
14963        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14964        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14965                || (args.volumeUuid != null));
14966        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14967        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14968        boolean replace = false;
14969        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14970        if (args.move != null) {
14971            // moving a complete application; perform an initial scan on the new install location
14972            scanFlags |= SCAN_INITIAL;
14973        }
14974        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14975            scanFlags |= SCAN_DONT_KILL_APP;
14976        }
14977
14978        // Result object to be returned
14979        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14980
14981        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14982
14983        // Sanity check
14984        if (ephemeral && (forwardLocked || onExternal)) {
14985            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14986                    + " external=" + onExternal);
14987            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14988            return;
14989        }
14990
14991        // Retrieve PackageSettings and parse package
14992        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14993                | PackageParser.PARSE_ENFORCE_CODE
14994                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14995                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14996                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14997                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14998        PackageParser pp = new PackageParser();
14999        pp.setSeparateProcesses(mSeparateProcesses);
15000        pp.setDisplayMetrics(mMetrics);
15001
15002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15003        final PackageParser.Package pkg;
15004        try {
15005            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15006        } catch (PackageParserException e) {
15007            res.setError("Failed parse during installPackageLI", e);
15008            return;
15009        } finally {
15010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15011        }
15012
15013        // If we are installing a clustered package add results for the children
15014        if (pkg.childPackages != null) {
15015            synchronized (mPackages) {
15016                final int childCount = pkg.childPackages.size();
15017                for (int i = 0; i < childCount; i++) {
15018                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15019                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15020                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15021                    childRes.pkg = childPkg;
15022                    childRes.name = childPkg.packageName;
15023                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15024                    if (childPs != null) {
15025                        childRes.origUsers = childPs.queryInstalledUsers(
15026                                sUserManager.getUserIds(), true);
15027                    }
15028                    if ((mPackages.containsKey(childPkg.packageName))) {
15029                        childRes.removedInfo = new PackageRemovedInfo();
15030                        childRes.removedInfo.removedPackage = childPkg.packageName;
15031                    }
15032                    if (res.addedChildPackages == null) {
15033                        res.addedChildPackages = new ArrayMap<>();
15034                    }
15035                    res.addedChildPackages.put(childPkg.packageName, childRes);
15036                }
15037            }
15038        }
15039
15040        // If package doesn't declare API override, mark that we have an install
15041        // time CPU ABI override.
15042        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15043            pkg.cpuAbiOverride = args.abiOverride;
15044        }
15045
15046        String pkgName = res.name = pkg.packageName;
15047        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15048            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15049                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15050                return;
15051            }
15052        }
15053
15054        try {
15055            // either use what we've been given or parse directly from the APK
15056            if (args.certificates != null) {
15057                try {
15058                    PackageParser.populateCertificates(pkg, args.certificates);
15059                } catch (PackageParserException e) {
15060                    // there was something wrong with the certificates we were given;
15061                    // try to pull them from the APK
15062                    PackageParser.collectCertificates(pkg, parseFlags);
15063                }
15064            } else {
15065                PackageParser.collectCertificates(pkg, parseFlags);
15066            }
15067        } catch (PackageParserException e) {
15068            res.setError("Failed collect during installPackageLI", e);
15069            return;
15070        }
15071
15072        // Get rid of all references to package scan path via parser.
15073        pp = null;
15074        String oldCodePath = null;
15075        boolean systemApp = false;
15076        synchronized (mPackages) {
15077            // Check if installing already existing package
15078            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15079                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15080                if (pkg.mOriginalPackages != null
15081                        && pkg.mOriginalPackages.contains(oldName)
15082                        && mPackages.containsKey(oldName)) {
15083                    // This package is derived from an original package,
15084                    // and this device has been updating from that original
15085                    // name.  We must continue using the original name, so
15086                    // rename the new package here.
15087                    pkg.setPackageName(oldName);
15088                    pkgName = pkg.packageName;
15089                    replace = true;
15090                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15091                            + oldName + " pkgName=" + pkgName);
15092                } else if (mPackages.containsKey(pkgName)) {
15093                    // This package, under its official name, already exists
15094                    // on the device; we should replace it.
15095                    replace = true;
15096                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15097                }
15098
15099                // Child packages are installed through the parent package
15100                if (pkg.parentPackage != null) {
15101                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15102                            "Package " + pkg.packageName + " is child of package "
15103                                    + pkg.parentPackage.parentPackage + ". Child packages "
15104                                    + "can be updated only through the parent package.");
15105                    return;
15106                }
15107
15108                if (replace) {
15109                    // Prevent apps opting out from runtime permissions
15110                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15111                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15112                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15113                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15114                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15115                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15116                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15117                                        + " doesn't support runtime permissions but the old"
15118                                        + " target SDK " + oldTargetSdk + " does.");
15119                        return;
15120                    }
15121
15122                    // Prevent installing of child packages
15123                    if (oldPackage.parentPackage != null) {
15124                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15125                                "Package " + pkg.packageName + " is child of package "
15126                                        + oldPackage.parentPackage + ". Child packages "
15127                                        + "can be updated only through the parent package.");
15128                        return;
15129                    }
15130                }
15131            }
15132
15133            PackageSetting ps = mSettings.mPackages.get(pkgName);
15134            if (ps != null) {
15135                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15136
15137                // Quick sanity check that we're signed correctly if updating;
15138                // we'll check this again later when scanning, but we want to
15139                // bail early here before tripping over redefined permissions.
15140                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15141                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15142                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15143                                + pkg.packageName + " upgrade keys do not match the "
15144                                + "previously installed version");
15145                        return;
15146                    }
15147                } else {
15148                    try {
15149                        verifySignaturesLP(ps, pkg);
15150                    } catch (PackageManagerException e) {
15151                        res.setError(e.error, e.getMessage());
15152                        return;
15153                    }
15154                }
15155
15156                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15157                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15158                    systemApp = (ps.pkg.applicationInfo.flags &
15159                            ApplicationInfo.FLAG_SYSTEM) != 0;
15160                }
15161                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15162            }
15163
15164            // Check whether the newly-scanned package wants to define an already-defined perm
15165            int N = pkg.permissions.size();
15166            for (int i = N-1; i >= 0; i--) {
15167                PackageParser.Permission perm = pkg.permissions.get(i);
15168                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15169                if (bp != null) {
15170                    // If the defining package is signed with our cert, it's okay.  This
15171                    // also includes the "updating the same package" case, of course.
15172                    // "updating same package" could also involve key-rotation.
15173                    final boolean sigsOk;
15174                    if (bp.sourcePackage.equals(pkg.packageName)
15175                            && (bp.packageSetting instanceof PackageSetting)
15176                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15177                                    scanFlags))) {
15178                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15179                    } else {
15180                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15181                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15182                    }
15183                    if (!sigsOk) {
15184                        // If the owning package is the system itself, we log but allow
15185                        // install to proceed; we fail the install on all other permission
15186                        // redefinitions.
15187                        if (!bp.sourcePackage.equals("android")) {
15188                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15189                                    + pkg.packageName + " attempting to redeclare permission "
15190                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15191                            res.origPermission = perm.info.name;
15192                            res.origPackage = bp.sourcePackage;
15193                            return;
15194                        } else {
15195                            Slog.w(TAG, "Package " + pkg.packageName
15196                                    + " attempting to redeclare system permission "
15197                                    + perm.info.name + "; ignoring new declaration");
15198                            pkg.permissions.remove(i);
15199                        }
15200                    }
15201                }
15202            }
15203        }
15204
15205        if (systemApp) {
15206            if (onExternal) {
15207                // Abort update; system app can't be replaced with app on sdcard
15208                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15209                        "Cannot install updates to system apps on sdcard");
15210                return;
15211            } else if (ephemeral) {
15212                // Abort update; system app can't be replaced with an ephemeral app
15213                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15214                        "Cannot update a system app with an ephemeral app");
15215                return;
15216            }
15217        }
15218
15219        if (args.move != null) {
15220            // We did an in-place move, so dex is ready to roll
15221            scanFlags |= SCAN_NO_DEX;
15222            scanFlags |= SCAN_MOVE;
15223
15224            synchronized (mPackages) {
15225                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15226                if (ps == null) {
15227                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15228                            "Missing settings for moved package " + pkgName);
15229                }
15230
15231                // We moved the entire application as-is, so bring over the
15232                // previously derived ABI information.
15233                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15234                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15235            }
15236
15237        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15238            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15239            scanFlags |= SCAN_NO_DEX;
15240
15241            try {
15242                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15243                    args.abiOverride : pkg.cpuAbiOverride);
15244                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15245                        true /* extract libs */);
15246            } catch (PackageManagerException pme) {
15247                Slog.e(TAG, "Error deriving application ABI", pme);
15248                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15249                return;
15250            }
15251
15252            // Shared libraries for the package need to be updated.
15253            synchronized (mPackages) {
15254                try {
15255                    updateSharedLibrariesLPw(pkg, null);
15256                } catch (PackageManagerException e) {
15257                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15258                }
15259            }
15260            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15261            // Do not run PackageDexOptimizer through the local performDexOpt
15262            // method because `pkg` may not be in `mPackages` yet.
15263            //
15264            // Also, don't fail application installs if the dexopt step fails.
15265            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15266                    null /* instructionSets */, false /* checkProfiles */,
15267                    getCompilerFilterForReason(REASON_INSTALL),
15268                    getOrCreateCompilerPackageStats(pkg));
15269            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15270
15271            // Notify BackgroundDexOptService that the package has been changed.
15272            // If this is an update of a package which used to fail to compile,
15273            // BDOS will remove it from its blacklist.
15274            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15275        }
15276
15277        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15278            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15279            return;
15280        }
15281
15282        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15283
15284        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15285                "installPackageLI")) {
15286            if (replace) {
15287                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15288                        installerPackageName, res);
15289            } else {
15290                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15291                        args.user, installerPackageName, volumeUuid, res);
15292            }
15293        }
15294        synchronized (mPackages) {
15295            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15296            if (ps != null) {
15297                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15298            }
15299
15300            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15301            for (int i = 0; i < childCount; i++) {
15302                PackageParser.Package childPkg = pkg.childPackages.get(i);
15303                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15304                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15305                if (childPs != null) {
15306                    childRes.newUsers = childPs.queryInstalledUsers(
15307                            sUserManager.getUserIds(), true);
15308                }
15309            }
15310        }
15311    }
15312
15313    private void startIntentFilterVerifications(int userId, boolean replacing,
15314            PackageParser.Package pkg) {
15315        if (mIntentFilterVerifierComponent == null) {
15316            Slog.w(TAG, "No IntentFilter verification will not be done as "
15317                    + "there is no IntentFilterVerifier available!");
15318            return;
15319        }
15320
15321        final int verifierUid = getPackageUid(
15322                mIntentFilterVerifierComponent.getPackageName(),
15323                MATCH_DEBUG_TRIAGED_MISSING,
15324                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15325
15326        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15327        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15328        mHandler.sendMessage(msg);
15329
15330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15331        for (int i = 0; i < childCount; i++) {
15332            PackageParser.Package childPkg = pkg.childPackages.get(i);
15333            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15334            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15335            mHandler.sendMessage(msg);
15336        }
15337    }
15338
15339    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15340            PackageParser.Package pkg) {
15341        int size = pkg.activities.size();
15342        if (size == 0) {
15343            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15344                    "No activity, so no need to verify any IntentFilter!");
15345            return;
15346        }
15347
15348        final boolean hasDomainURLs = hasDomainURLs(pkg);
15349        if (!hasDomainURLs) {
15350            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15351                    "No domain URLs, so no need to verify any IntentFilter!");
15352            return;
15353        }
15354
15355        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15356                + " if any IntentFilter from the " + size
15357                + " Activities needs verification ...");
15358
15359        int count = 0;
15360        final String packageName = pkg.packageName;
15361
15362        synchronized (mPackages) {
15363            // If this is a new install and we see that we've already run verification for this
15364            // package, we have nothing to do: it means the state was restored from backup.
15365            if (!replacing) {
15366                IntentFilterVerificationInfo ivi =
15367                        mSettings.getIntentFilterVerificationLPr(packageName);
15368                if (ivi != null) {
15369                    if (DEBUG_DOMAIN_VERIFICATION) {
15370                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15371                                + ivi.getStatusString());
15372                    }
15373                    return;
15374                }
15375            }
15376
15377            // If any filters need to be verified, then all need to be.
15378            boolean needToVerify = false;
15379            for (PackageParser.Activity a : pkg.activities) {
15380                for (ActivityIntentInfo filter : a.intents) {
15381                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15382                        if (DEBUG_DOMAIN_VERIFICATION) {
15383                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15384                        }
15385                        needToVerify = true;
15386                        break;
15387                    }
15388                }
15389            }
15390
15391            if (needToVerify) {
15392                final int verificationId = mIntentFilterVerificationToken++;
15393                for (PackageParser.Activity a : pkg.activities) {
15394                    for (ActivityIntentInfo filter : a.intents) {
15395                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15396                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15397                                    "Verification needed for IntentFilter:" + filter.toString());
15398                            mIntentFilterVerifier.addOneIntentFilterVerification(
15399                                    verifierUid, userId, verificationId, filter, packageName);
15400                            count++;
15401                        }
15402                    }
15403                }
15404            }
15405        }
15406
15407        if (count > 0) {
15408            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15409                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15410                    +  " for userId:" + userId);
15411            mIntentFilterVerifier.startVerifications(userId);
15412        } else {
15413            if (DEBUG_DOMAIN_VERIFICATION) {
15414                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15415            }
15416        }
15417    }
15418
15419    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15420        final ComponentName cn  = filter.activity.getComponentName();
15421        final String packageName = cn.getPackageName();
15422
15423        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15424                packageName);
15425        if (ivi == null) {
15426            return true;
15427        }
15428        int status = ivi.getStatus();
15429        switch (status) {
15430            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15431            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15432                return true;
15433
15434            default:
15435                // Nothing to do
15436                return false;
15437        }
15438    }
15439
15440    private static boolean isMultiArch(ApplicationInfo info) {
15441        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15442    }
15443
15444    private static boolean isExternal(PackageParser.Package pkg) {
15445        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15446    }
15447
15448    private static boolean isExternal(PackageSetting ps) {
15449        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15450    }
15451
15452    private static boolean isEphemeral(PackageParser.Package pkg) {
15453        return pkg.applicationInfo.isEphemeralApp();
15454    }
15455
15456    private static boolean isEphemeral(PackageSetting ps) {
15457        return ps.pkg != null && isEphemeral(ps.pkg);
15458    }
15459
15460    private static boolean isSystemApp(PackageParser.Package pkg) {
15461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15462    }
15463
15464    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15465        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15466    }
15467
15468    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15469        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15470    }
15471
15472    private static boolean isSystemApp(PackageSetting ps) {
15473        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15474    }
15475
15476    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15477        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15478    }
15479
15480    private int packageFlagsToInstallFlags(PackageSetting ps) {
15481        int installFlags = 0;
15482        if (isEphemeral(ps)) {
15483            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15484        }
15485        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15486            // This existing package was an external ASEC install when we have
15487            // the external flag without a UUID
15488            installFlags |= PackageManager.INSTALL_EXTERNAL;
15489        }
15490        if (ps.isForwardLocked()) {
15491            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15492        }
15493        return installFlags;
15494    }
15495
15496    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15497        if (isExternal(pkg)) {
15498            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15499                return StorageManager.UUID_PRIMARY_PHYSICAL;
15500            } else {
15501                return pkg.volumeUuid;
15502            }
15503        } else {
15504            return StorageManager.UUID_PRIVATE_INTERNAL;
15505        }
15506    }
15507
15508    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15509        if (isExternal(pkg)) {
15510            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15511                return mSettings.getExternalVersion();
15512            } else {
15513                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15514            }
15515        } else {
15516            return mSettings.getInternalVersion();
15517        }
15518    }
15519
15520    private void deleteTempPackageFiles() {
15521        final FilenameFilter filter = new FilenameFilter() {
15522            public boolean accept(File dir, String name) {
15523                return name.startsWith("vmdl") && name.endsWith(".tmp");
15524            }
15525        };
15526        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15527            file.delete();
15528        }
15529    }
15530
15531    @Override
15532    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15533            int flags) {
15534        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15535                flags);
15536    }
15537
15538    @Override
15539    public void deletePackage(final String packageName,
15540            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15541        mContext.enforceCallingOrSelfPermission(
15542                android.Manifest.permission.DELETE_PACKAGES, null);
15543        Preconditions.checkNotNull(packageName);
15544        Preconditions.checkNotNull(observer);
15545        final int uid = Binder.getCallingUid();
15546        if (!isOrphaned(packageName)
15547                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15548            try {
15549                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15550                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15551                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15552                observer.onUserActionRequired(intent);
15553            } catch (RemoteException re) {
15554            }
15555            return;
15556        }
15557        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15558        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15559        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15560            mContext.enforceCallingOrSelfPermission(
15561                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15562                    "deletePackage for user " + userId);
15563        }
15564
15565        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15566            try {
15567                observer.onPackageDeleted(packageName,
15568                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15569            } catch (RemoteException re) {
15570            }
15571            return;
15572        }
15573
15574        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15575            try {
15576                observer.onPackageDeleted(packageName,
15577                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15578            } catch (RemoteException re) {
15579            }
15580            return;
15581        }
15582
15583        if (DEBUG_REMOVE) {
15584            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15585                    + " deleteAllUsers: " + deleteAllUsers );
15586        }
15587        // Queue up an async operation since the package deletion may take a little while.
15588        mHandler.post(new Runnable() {
15589            public void run() {
15590                mHandler.removeCallbacks(this);
15591                int returnCode;
15592                if (!deleteAllUsers) {
15593                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15594                } else {
15595                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15596                    // If nobody is blocking uninstall, proceed with delete for all users
15597                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15598                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15599                    } else {
15600                        // Otherwise uninstall individually for users with blockUninstalls=false
15601                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15602                        for (int userId : users) {
15603                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15604                                returnCode = deletePackageX(packageName, userId, userFlags);
15605                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15606                                    Slog.w(TAG, "Package delete failed for user " + userId
15607                                            + ", returnCode " + returnCode);
15608                                }
15609                            }
15610                        }
15611                        // The app has only been marked uninstalled for certain users.
15612                        // We still need to report that delete was blocked
15613                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15614                    }
15615                }
15616                try {
15617                    observer.onPackageDeleted(packageName, returnCode, null);
15618                } catch (RemoteException e) {
15619                    Log.i(TAG, "Observer no longer exists.");
15620                } //end catch
15621            } //end run
15622        });
15623    }
15624
15625    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15626        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15627              || callingUid == Process.SYSTEM_UID) {
15628            return true;
15629        }
15630        final int callingUserId = UserHandle.getUserId(callingUid);
15631        // If the caller installed the pkgName, then allow it to silently uninstall.
15632        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15633            return true;
15634        }
15635
15636        // Allow package verifier to silently uninstall.
15637        if (mRequiredVerifierPackage != null &&
15638                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15639            return true;
15640        }
15641
15642        // Allow package uninstaller to silently uninstall.
15643        if (mRequiredUninstallerPackage != null &&
15644                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15645            return true;
15646        }
15647
15648        // Allow storage manager to silently uninstall.
15649        if (mStorageManagerPackage != null &&
15650                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15651            return true;
15652        }
15653        return false;
15654    }
15655
15656    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15657        int[] result = EMPTY_INT_ARRAY;
15658        for (int userId : userIds) {
15659            if (getBlockUninstallForUser(packageName, userId)) {
15660                result = ArrayUtils.appendInt(result, userId);
15661            }
15662        }
15663        return result;
15664    }
15665
15666    @Override
15667    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15668        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15669    }
15670
15671    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15672        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15673                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15674        try {
15675            if (dpm != null) {
15676                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15677                        /* callingUserOnly =*/ false);
15678                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15679                        : deviceOwnerComponentName.getPackageName();
15680                // Does the package contains the device owner?
15681                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15682                // this check is probably not needed, since DO should be registered as a device
15683                // admin on some user too. (Original bug for this: b/17657954)
15684                if (packageName.equals(deviceOwnerPackageName)) {
15685                    return true;
15686                }
15687                // Does it contain a device admin for any user?
15688                int[] users;
15689                if (userId == UserHandle.USER_ALL) {
15690                    users = sUserManager.getUserIds();
15691                } else {
15692                    users = new int[]{userId};
15693                }
15694                for (int i = 0; i < users.length; ++i) {
15695                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15696                        return true;
15697                    }
15698                }
15699            }
15700        } catch (RemoteException e) {
15701        }
15702        return false;
15703    }
15704
15705    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15706        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15707    }
15708
15709    /**
15710     *  This method is an internal method that could be get invoked either
15711     *  to delete an installed package or to clean up a failed installation.
15712     *  After deleting an installed package, a broadcast is sent to notify any
15713     *  listeners that the package has been removed. For cleaning up a failed
15714     *  installation, the broadcast is not necessary since the package's
15715     *  installation wouldn't have sent the initial broadcast either
15716     *  The key steps in deleting a package are
15717     *  deleting the package information in internal structures like mPackages,
15718     *  deleting the packages base directories through installd
15719     *  updating mSettings to reflect current status
15720     *  persisting settings for later use
15721     *  sending a broadcast if necessary
15722     */
15723    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15724        final PackageRemovedInfo info = new PackageRemovedInfo();
15725        final boolean res;
15726
15727        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15728                ? UserHandle.USER_ALL : userId;
15729
15730        if (isPackageDeviceAdmin(packageName, removeUser)) {
15731            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15732            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15733        }
15734
15735        PackageSetting uninstalledPs = null;
15736
15737        // for the uninstall-updates case and restricted profiles, remember the per-
15738        // user handle installed state
15739        int[] allUsers;
15740        synchronized (mPackages) {
15741            uninstalledPs = mSettings.mPackages.get(packageName);
15742            if (uninstalledPs == null) {
15743                Slog.w(TAG, "Not removing non-existent package " + packageName);
15744                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15745            }
15746            allUsers = sUserManager.getUserIds();
15747            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15748        }
15749
15750        final int freezeUser;
15751        if (isUpdatedSystemApp(uninstalledPs)
15752                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15753            // We're downgrading a system app, which will apply to all users, so
15754            // freeze them all during the downgrade
15755            freezeUser = UserHandle.USER_ALL;
15756        } else {
15757            freezeUser = removeUser;
15758        }
15759
15760        synchronized (mInstallLock) {
15761            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15762            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15763                    deleteFlags, "deletePackageX")) {
15764                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15765                        deleteFlags | REMOVE_CHATTY, info, true, null);
15766            }
15767            synchronized (mPackages) {
15768                if (res) {
15769                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15770                }
15771            }
15772        }
15773
15774        if (res) {
15775            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15776            info.sendPackageRemovedBroadcasts(killApp);
15777            info.sendSystemPackageUpdatedBroadcasts();
15778            info.sendSystemPackageAppearedBroadcasts();
15779        }
15780        // Force a gc here.
15781        Runtime.getRuntime().gc();
15782        // Delete the resources here after sending the broadcast to let
15783        // other processes clean up before deleting resources.
15784        if (info.args != null) {
15785            synchronized (mInstallLock) {
15786                info.args.doPostDeleteLI(true);
15787            }
15788        }
15789
15790        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15791    }
15792
15793    class PackageRemovedInfo {
15794        String removedPackage;
15795        int uid = -1;
15796        int removedAppId = -1;
15797        int[] origUsers;
15798        int[] removedUsers = null;
15799        boolean isRemovedPackageSystemUpdate = false;
15800        boolean isUpdate;
15801        boolean dataRemoved;
15802        boolean removedForAllUsers;
15803        // Clean up resources deleted packages.
15804        InstallArgs args = null;
15805        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15806        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15807
15808        void sendPackageRemovedBroadcasts(boolean killApp) {
15809            sendPackageRemovedBroadcastInternal(killApp);
15810            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15811            for (int i = 0; i < childCount; i++) {
15812                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15813                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15814            }
15815        }
15816
15817        void sendSystemPackageUpdatedBroadcasts() {
15818            if (isRemovedPackageSystemUpdate) {
15819                sendSystemPackageUpdatedBroadcastsInternal();
15820                final int childCount = (removedChildPackages != null)
15821                        ? removedChildPackages.size() : 0;
15822                for (int i = 0; i < childCount; i++) {
15823                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15824                    if (childInfo.isRemovedPackageSystemUpdate) {
15825                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15826                    }
15827                }
15828            }
15829        }
15830
15831        void sendSystemPackageAppearedBroadcasts() {
15832            final int packageCount = (appearedChildPackages != null)
15833                    ? appearedChildPackages.size() : 0;
15834            for (int i = 0; i < packageCount; i++) {
15835                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15836                for (int userId : installedInfo.newUsers) {
15837                    sendPackageAddedForUser(installedInfo.name, true,
15838                            UserHandle.getAppId(installedInfo.uid), userId);
15839                }
15840            }
15841        }
15842
15843        private void sendSystemPackageUpdatedBroadcastsInternal() {
15844            Bundle extras = new Bundle(2);
15845            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15846            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15847            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15848                    extras, 0, null, null, null);
15849            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15850                    extras, 0, null, null, null);
15851            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15852                    null, 0, removedPackage, null, null);
15853        }
15854
15855        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15856            Bundle extras = new Bundle(2);
15857            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15858            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15859            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15860            if (isUpdate || isRemovedPackageSystemUpdate) {
15861                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15862            }
15863            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15864            if (removedPackage != null) {
15865                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15866                        extras, 0, null, null, removedUsers);
15867                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15868                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15869                            removedPackage, extras, 0, null, null, removedUsers);
15870                }
15871            }
15872            if (removedAppId >= 0) {
15873                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15874                        removedUsers);
15875            }
15876        }
15877    }
15878
15879    /*
15880     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15881     * flag is not set, the data directory is removed as well.
15882     * make sure this flag is set for partially installed apps. If not its meaningless to
15883     * delete a partially installed application.
15884     */
15885    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15886            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15887        String packageName = ps.name;
15888        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15889        // Retrieve object to delete permissions for shared user later on
15890        final PackageParser.Package deletedPkg;
15891        final PackageSetting deletedPs;
15892        // reader
15893        synchronized (mPackages) {
15894            deletedPkg = mPackages.get(packageName);
15895            deletedPs = mSettings.mPackages.get(packageName);
15896            if (outInfo != null) {
15897                outInfo.removedPackage = packageName;
15898                outInfo.removedUsers = deletedPs != null
15899                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15900                        : null;
15901            }
15902        }
15903
15904        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15905
15906        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15907            final PackageParser.Package resolvedPkg;
15908            if (deletedPkg != null) {
15909                resolvedPkg = deletedPkg;
15910            } else {
15911                // We don't have a parsed package when it lives on an ejected
15912                // adopted storage device, so fake something together
15913                resolvedPkg = new PackageParser.Package(ps.name);
15914                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15915            }
15916            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15917                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15918            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15919            if (outInfo != null) {
15920                outInfo.dataRemoved = true;
15921            }
15922            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15923        }
15924
15925        // writer
15926        synchronized (mPackages) {
15927            if (deletedPs != null) {
15928                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15929                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15930                    clearDefaultBrowserIfNeeded(packageName);
15931                    if (outInfo != null) {
15932                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15933                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15934                    }
15935                    updatePermissionsLPw(deletedPs.name, null, 0);
15936                    if (deletedPs.sharedUser != null) {
15937                        // Remove permissions associated with package. Since runtime
15938                        // permissions are per user we have to kill the removed package
15939                        // or packages running under the shared user of the removed
15940                        // package if revoking the permissions requested only by the removed
15941                        // package is successful and this causes a change in gids.
15942                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15943                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15944                                    userId);
15945                            if (userIdToKill == UserHandle.USER_ALL
15946                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15947                                // If gids changed for this user, kill all affected packages.
15948                                mHandler.post(new Runnable() {
15949                                    @Override
15950                                    public void run() {
15951                                        // This has to happen with no lock held.
15952                                        killApplication(deletedPs.name, deletedPs.appId,
15953                                                KILL_APP_REASON_GIDS_CHANGED);
15954                                    }
15955                                });
15956                                break;
15957                            }
15958                        }
15959                    }
15960                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15961                }
15962                // make sure to preserve per-user disabled state if this removal was just
15963                // a downgrade of a system app to the factory package
15964                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15965                    if (DEBUG_REMOVE) {
15966                        Slog.d(TAG, "Propagating install state across downgrade");
15967                    }
15968                    for (int userId : allUserHandles) {
15969                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15970                        if (DEBUG_REMOVE) {
15971                            Slog.d(TAG, "    user " + userId + " => " + installed);
15972                        }
15973                        ps.setInstalled(installed, userId);
15974                    }
15975                }
15976            }
15977            // can downgrade to reader
15978            if (writeSettings) {
15979                // Save settings now
15980                mSettings.writeLPr();
15981            }
15982        }
15983        if (outInfo != null) {
15984            // A user ID was deleted here. Go through all users and remove it
15985            // from KeyStore.
15986            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15987        }
15988    }
15989
15990    static boolean locationIsPrivileged(File path) {
15991        try {
15992            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15993                    .getCanonicalPath();
15994            return path.getCanonicalPath().startsWith(privilegedAppDir);
15995        } catch (IOException e) {
15996            Slog.e(TAG, "Unable to access code path " + path);
15997        }
15998        return false;
15999    }
16000
16001    /*
16002     * Tries to delete system package.
16003     */
16004    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16005            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16006            boolean writeSettings) {
16007        if (deletedPs.parentPackageName != null) {
16008            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16009            return false;
16010        }
16011
16012        final boolean applyUserRestrictions
16013                = (allUserHandles != null) && (outInfo.origUsers != null);
16014        final PackageSetting disabledPs;
16015        // Confirm if the system package has been updated
16016        // An updated system app can be deleted. This will also have to restore
16017        // the system pkg from system partition
16018        // reader
16019        synchronized (mPackages) {
16020            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16021        }
16022
16023        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16024                + " disabledPs=" + disabledPs);
16025
16026        if (disabledPs == null) {
16027            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16028            return false;
16029        } else if (DEBUG_REMOVE) {
16030            Slog.d(TAG, "Deleting system pkg from data partition");
16031        }
16032
16033        if (DEBUG_REMOVE) {
16034            if (applyUserRestrictions) {
16035                Slog.d(TAG, "Remembering install states:");
16036                for (int userId : allUserHandles) {
16037                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16038                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16039                }
16040            }
16041        }
16042
16043        // Delete the updated package
16044        outInfo.isRemovedPackageSystemUpdate = true;
16045        if (outInfo.removedChildPackages != null) {
16046            final int childCount = (deletedPs.childPackageNames != null)
16047                    ? deletedPs.childPackageNames.size() : 0;
16048            for (int i = 0; i < childCount; i++) {
16049                String childPackageName = deletedPs.childPackageNames.get(i);
16050                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16051                        .contains(childPackageName)) {
16052                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16053                            childPackageName);
16054                    if (childInfo != null) {
16055                        childInfo.isRemovedPackageSystemUpdate = true;
16056                    }
16057                }
16058            }
16059        }
16060
16061        if (disabledPs.versionCode < deletedPs.versionCode) {
16062            // Delete data for downgrades
16063            flags &= ~PackageManager.DELETE_KEEP_DATA;
16064        } else {
16065            // Preserve data by setting flag
16066            flags |= PackageManager.DELETE_KEEP_DATA;
16067        }
16068
16069        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16070                outInfo, writeSettings, disabledPs.pkg);
16071        if (!ret) {
16072            return false;
16073        }
16074
16075        // writer
16076        synchronized (mPackages) {
16077            // Reinstate the old system package
16078            enableSystemPackageLPw(disabledPs.pkg);
16079            // Remove any native libraries from the upgraded package.
16080            removeNativeBinariesLI(deletedPs);
16081        }
16082
16083        // Install the system package
16084        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16085        int parseFlags = mDefParseFlags
16086                | PackageParser.PARSE_MUST_BE_APK
16087                | PackageParser.PARSE_IS_SYSTEM
16088                | PackageParser.PARSE_IS_SYSTEM_DIR;
16089        if (locationIsPrivileged(disabledPs.codePath)) {
16090            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16091        }
16092
16093        final PackageParser.Package newPkg;
16094        try {
16095            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16096        } catch (PackageManagerException e) {
16097            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16098                    + e.getMessage());
16099            return false;
16100        }
16101        try {
16102            // update shared libraries for the newly re-installed system package
16103            updateSharedLibrariesLPw(newPkg, null);
16104        } catch (PackageManagerException e) {
16105            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16106        }
16107
16108        prepareAppDataAfterInstallLIF(newPkg);
16109
16110        // writer
16111        synchronized (mPackages) {
16112            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16113
16114            // Propagate the permissions state as we do not want to drop on the floor
16115            // runtime permissions. The update permissions method below will take
16116            // care of removing obsolete permissions and grant install permissions.
16117            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16118            updatePermissionsLPw(newPkg.packageName, newPkg,
16119                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16120
16121            if (applyUserRestrictions) {
16122                if (DEBUG_REMOVE) {
16123                    Slog.d(TAG, "Propagating install state across reinstall");
16124                }
16125                for (int userId : allUserHandles) {
16126                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16127                    if (DEBUG_REMOVE) {
16128                        Slog.d(TAG, "    user " + userId + " => " + installed);
16129                    }
16130                    ps.setInstalled(installed, userId);
16131
16132                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16133                }
16134                // Regardless of writeSettings we need to ensure that this restriction
16135                // state propagation is persisted
16136                mSettings.writeAllUsersPackageRestrictionsLPr();
16137            }
16138            // can downgrade to reader here
16139            if (writeSettings) {
16140                mSettings.writeLPr();
16141            }
16142        }
16143        return true;
16144    }
16145
16146    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16147            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16148            PackageRemovedInfo outInfo, boolean writeSettings,
16149            PackageParser.Package replacingPackage) {
16150        synchronized (mPackages) {
16151            if (outInfo != null) {
16152                outInfo.uid = ps.appId;
16153            }
16154
16155            if (outInfo != null && outInfo.removedChildPackages != null) {
16156                final int childCount = (ps.childPackageNames != null)
16157                        ? ps.childPackageNames.size() : 0;
16158                for (int i = 0; i < childCount; i++) {
16159                    String childPackageName = ps.childPackageNames.get(i);
16160                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16161                    if (childPs == null) {
16162                        return false;
16163                    }
16164                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16165                            childPackageName);
16166                    if (childInfo != null) {
16167                        childInfo.uid = childPs.appId;
16168                    }
16169                }
16170            }
16171        }
16172
16173        // Delete package data from internal structures and also remove data if flag is set
16174        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16175
16176        // Delete the child packages data
16177        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16178        for (int i = 0; i < childCount; i++) {
16179            PackageSetting childPs;
16180            synchronized (mPackages) {
16181                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16182            }
16183            if (childPs != null) {
16184                PackageRemovedInfo childOutInfo = (outInfo != null
16185                        && outInfo.removedChildPackages != null)
16186                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16187                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16188                        && (replacingPackage != null
16189                        && !replacingPackage.hasChildPackage(childPs.name))
16190                        ? flags & ~DELETE_KEEP_DATA : flags;
16191                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16192                        deleteFlags, writeSettings);
16193            }
16194        }
16195
16196        // Delete application code and resources only for parent packages
16197        if (ps.parentPackageName == null) {
16198            if (deleteCodeAndResources && (outInfo != null)) {
16199                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16200                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16201                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16202            }
16203        }
16204
16205        return true;
16206    }
16207
16208    @Override
16209    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16210            int userId) {
16211        mContext.enforceCallingOrSelfPermission(
16212                android.Manifest.permission.DELETE_PACKAGES, null);
16213        synchronized (mPackages) {
16214            PackageSetting ps = mSettings.mPackages.get(packageName);
16215            if (ps == null) {
16216                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16217                return false;
16218            }
16219            if (!ps.getInstalled(userId)) {
16220                // Can't block uninstall for an app that is not installed or enabled.
16221                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16222                return false;
16223            }
16224            ps.setBlockUninstall(blockUninstall, userId);
16225            mSettings.writePackageRestrictionsLPr(userId);
16226        }
16227        return true;
16228    }
16229
16230    @Override
16231    public boolean getBlockUninstallForUser(String packageName, int userId) {
16232        synchronized (mPackages) {
16233            PackageSetting ps = mSettings.mPackages.get(packageName);
16234            if (ps == null) {
16235                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16236                return false;
16237            }
16238            return ps.getBlockUninstall(userId);
16239        }
16240    }
16241
16242    @Override
16243    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16244        int callingUid = Binder.getCallingUid();
16245        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16246            throw new SecurityException(
16247                    "setRequiredForSystemUser can only be run by the system or root");
16248        }
16249        synchronized (mPackages) {
16250            PackageSetting ps = mSettings.mPackages.get(packageName);
16251            if (ps == null) {
16252                Log.w(TAG, "Package doesn't exist: " + packageName);
16253                return false;
16254            }
16255            if (systemUserApp) {
16256                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16257            } else {
16258                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16259            }
16260            mSettings.writeLPr();
16261        }
16262        return true;
16263    }
16264
16265    /*
16266     * This method handles package deletion in general
16267     */
16268    private boolean deletePackageLIF(String packageName, UserHandle user,
16269            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16270            PackageRemovedInfo outInfo, boolean writeSettings,
16271            PackageParser.Package replacingPackage) {
16272        if (packageName == null) {
16273            Slog.w(TAG, "Attempt to delete null packageName.");
16274            return false;
16275        }
16276
16277        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16278
16279        PackageSetting ps;
16280
16281        synchronized (mPackages) {
16282            ps = mSettings.mPackages.get(packageName);
16283            if (ps == null) {
16284                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16285                return false;
16286            }
16287
16288            if (ps.parentPackageName != null && (!isSystemApp(ps)
16289                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16290                if (DEBUG_REMOVE) {
16291                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16292                            + ((user == null) ? UserHandle.USER_ALL : user));
16293                }
16294                final int removedUserId = (user != null) ? user.getIdentifier()
16295                        : UserHandle.USER_ALL;
16296                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16297                    return false;
16298                }
16299                markPackageUninstalledForUserLPw(ps, user);
16300                scheduleWritePackageRestrictionsLocked(user);
16301                return true;
16302            }
16303        }
16304
16305        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16306                && user.getIdentifier() != UserHandle.USER_ALL)) {
16307            // The caller is asking that the package only be deleted for a single
16308            // user.  To do this, we just mark its uninstalled state and delete
16309            // its data. If this is a system app, we only allow this to happen if
16310            // they have set the special DELETE_SYSTEM_APP which requests different
16311            // semantics than normal for uninstalling system apps.
16312            markPackageUninstalledForUserLPw(ps, user);
16313
16314            if (!isSystemApp(ps)) {
16315                // Do not uninstall the APK if an app should be cached
16316                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16317                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16318                    // Other user still have this package installed, so all
16319                    // we need to do is clear this user's data and save that
16320                    // it is uninstalled.
16321                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16322                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16323                        return false;
16324                    }
16325                    scheduleWritePackageRestrictionsLocked(user);
16326                    return true;
16327                } else {
16328                    // We need to set it back to 'installed' so the uninstall
16329                    // broadcasts will be sent correctly.
16330                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16331                    ps.setInstalled(true, user.getIdentifier());
16332                }
16333            } else {
16334                // This is a system app, so we assume that the
16335                // other users still have this package installed, so all
16336                // we need to do is clear this user's data and save that
16337                // it is uninstalled.
16338                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16339                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16340                    return false;
16341                }
16342                scheduleWritePackageRestrictionsLocked(user);
16343                return true;
16344            }
16345        }
16346
16347        // If we are deleting a composite package for all users, keep track
16348        // of result for each child.
16349        if (ps.childPackageNames != null && outInfo != null) {
16350            synchronized (mPackages) {
16351                final int childCount = ps.childPackageNames.size();
16352                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16353                for (int i = 0; i < childCount; i++) {
16354                    String childPackageName = ps.childPackageNames.get(i);
16355                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16356                    childInfo.removedPackage = childPackageName;
16357                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16358                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16359                    if (childPs != null) {
16360                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16361                    }
16362                }
16363            }
16364        }
16365
16366        boolean ret = false;
16367        if (isSystemApp(ps)) {
16368            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16369            // When an updated system application is deleted we delete the existing resources
16370            // as well and fall back to existing code in system partition
16371            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16372        } else {
16373            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16374            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16375                    outInfo, writeSettings, replacingPackage);
16376        }
16377
16378        // Take a note whether we deleted the package for all users
16379        if (outInfo != null) {
16380            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16381            if (outInfo.removedChildPackages != null) {
16382                synchronized (mPackages) {
16383                    final int childCount = outInfo.removedChildPackages.size();
16384                    for (int i = 0; i < childCount; i++) {
16385                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16386                        if (childInfo != null) {
16387                            childInfo.removedForAllUsers = mPackages.get(
16388                                    childInfo.removedPackage) == null;
16389                        }
16390                    }
16391                }
16392            }
16393            // If we uninstalled an update to a system app there may be some
16394            // child packages that appeared as they are declared in the system
16395            // app but were not declared in the update.
16396            if (isSystemApp(ps)) {
16397                synchronized (mPackages) {
16398                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16399                    final int childCount = (updatedPs.childPackageNames != null)
16400                            ? updatedPs.childPackageNames.size() : 0;
16401                    for (int i = 0; i < childCount; i++) {
16402                        String childPackageName = updatedPs.childPackageNames.get(i);
16403                        if (outInfo.removedChildPackages == null
16404                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16405                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16406                            if (childPs == null) {
16407                                continue;
16408                            }
16409                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16410                            installRes.name = childPackageName;
16411                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16412                            installRes.pkg = mPackages.get(childPackageName);
16413                            installRes.uid = childPs.pkg.applicationInfo.uid;
16414                            if (outInfo.appearedChildPackages == null) {
16415                                outInfo.appearedChildPackages = new ArrayMap<>();
16416                            }
16417                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16418                        }
16419                    }
16420                }
16421            }
16422        }
16423
16424        return ret;
16425    }
16426
16427    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16428        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16429                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16430        for (int nextUserId : userIds) {
16431            if (DEBUG_REMOVE) {
16432                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16433            }
16434            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16435                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16436                    false /*hidden*/, false /*suspended*/, null, null, null,
16437                    false /*blockUninstall*/,
16438                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16439        }
16440    }
16441
16442    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16443            PackageRemovedInfo outInfo) {
16444        final PackageParser.Package pkg;
16445        synchronized (mPackages) {
16446            pkg = mPackages.get(ps.name);
16447        }
16448
16449        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16450                : new int[] {userId};
16451        for (int nextUserId : userIds) {
16452            if (DEBUG_REMOVE) {
16453                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16454                        + nextUserId);
16455            }
16456
16457            destroyAppDataLIF(pkg, userId,
16458                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16459            destroyAppProfilesLIF(pkg, userId);
16460            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16461            schedulePackageCleaning(ps.name, nextUserId, false);
16462            synchronized (mPackages) {
16463                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16464                    scheduleWritePackageRestrictionsLocked(nextUserId);
16465                }
16466                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16467            }
16468        }
16469
16470        if (outInfo != null) {
16471            outInfo.removedPackage = ps.name;
16472            outInfo.removedAppId = ps.appId;
16473            outInfo.removedUsers = userIds;
16474        }
16475
16476        return true;
16477    }
16478
16479    private final class ClearStorageConnection implements ServiceConnection {
16480        IMediaContainerService mContainerService;
16481
16482        @Override
16483        public void onServiceConnected(ComponentName name, IBinder service) {
16484            synchronized (this) {
16485                mContainerService = IMediaContainerService.Stub.asInterface(service);
16486                notifyAll();
16487            }
16488        }
16489
16490        @Override
16491        public void onServiceDisconnected(ComponentName name) {
16492        }
16493    }
16494
16495    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16496        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16497
16498        final boolean mounted;
16499        if (Environment.isExternalStorageEmulated()) {
16500            mounted = true;
16501        } else {
16502            final String status = Environment.getExternalStorageState();
16503
16504            mounted = status.equals(Environment.MEDIA_MOUNTED)
16505                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16506        }
16507
16508        if (!mounted) {
16509            return;
16510        }
16511
16512        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16513        int[] users;
16514        if (userId == UserHandle.USER_ALL) {
16515            users = sUserManager.getUserIds();
16516        } else {
16517            users = new int[] { userId };
16518        }
16519        final ClearStorageConnection conn = new ClearStorageConnection();
16520        if (mContext.bindServiceAsUser(
16521                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16522            try {
16523                for (int curUser : users) {
16524                    long timeout = SystemClock.uptimeMillis() + 5000;
16525                    synchronized (conn) {
16526                        long now;
16527                        while (conn.mContainerService == null &&
16528                                (now = SystemClock.uptimeMillis()) < timeout) {
16529                            try {
16530                                conn.wait(timeout - now);
16531                            } catch (InterruptedException e) {
16532                            }
16533                        }
16534                    }
16535                    if (conn.mContainerService == null) {
16536                        return;
16537                    }
16538
16539                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16540                    clearDirectory(conn.mContainerService,
16541                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16542                    if (allData) {
16543                        clearDirectory(conn.mContainerService,
16544                                userEnv.buildExternalStorageAppDataDirs(packageName));
16545                        clearDirectory(conn.mContainerService,
16546                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16547                    }
16548                }
16549            } finally {
16550                mContext.unbindService(conn);
16551            }
16552        }
16553    }
16554
16555    @Override
16556    public void clearApplicationProfileData(String packageName) {
16557        enforceSystemOrRoot("Only the system can clear all profile data");
16558
16559        final PackageParser.Package pkg;
16560        synchronized (mPackages) {
16561            pkg = mPackages.get(packageName);
16562        }
16563
16564        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16565            synchronized (mInstallLock) {
16566                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16567                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16568                        true /* removeBaseMarker */);
16569            }
16570        }
16571    }
16572
16573    @Override
16574    public void clearApplicationUserData(final String packageName,
16575            final IPackageDataObserver observer, final int userId) {
16576        mContext.enforceCallingOrSelfPermission(
16577                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16578
16579        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16580                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16581
16582        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16583            throw new SecurityException("Cannot clear data for a protected package: "
16584                    + packageName);
16585        }
16586        // Queue up an async operation since the package deletion may take a little while.
16587        mHandler.post(new Runnable() {
16588            public void run() {
16589                mHandler.removeCallbacks(this);
16590                final boolean succeeded;
16591                try (PackageFreezer freezer = freezePackage(packageName,
16592                        "clearApplicationUserData")) {
16593                    synchronized (mInstallLock) {
16594                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16595                    }
16596                    clearExternalStorageDataSync(packageName, userId, true);
16597                }
16598                if (succeeded) {
16599                    // invoke DeviceStorageMonitor's update method to clear any notifications
16600                    DeviceStorageMonitorInternal dsm = LocalServices
16601                            .getService(DeviceStorageMonitorInternal.class);
16602                    if (dsm != null) {
16603                        dsm.checkMemory();
16604                    }
16605                }
16606                if(observer != null) {
16607                    try {
16608                        observer.onRemoveCompleted(packageName, succeeded);
16609                    } catch (RemoteException e) {
16610                        Log.i(TAG, "Observer no longer exists.");
16611                    }
16612                } //end if observer
16613            } //end run
16614        });
16615    }
16616
16617    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16618        if (packageName == null) {
16619            Slog.w(TAG, "Attempt to delete null packageName.");
16620            return false;
16621        }
16622
16623        // Try finding details about the requested package
16624        PackageParser.Package pkg;
16625        synchronized (mPackages) {
16626            pkg = mPackages.get(packageName);
16627            if (pkg == null) {
16628                final PackageSetting ps = mSettings.mPackages.get(packageName);
16629                if (ps != null) {
16630                    pkg = ps.pkg;
16631                }
16632            }
16633
16634            if (pkg == null) {
16635                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16636                return false;
16637            }
16638
16639            PackageSetting ps = (PackageSetting) pkg.mExtras;
16640            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16641        }
16642
16643        clearAppDataLIF(pkg, userId,
16644                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16645
16646        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16647        removeKeystoreDataIfNeeded(userId, appId);
16648
16649        UserManagerInternal umInternal = getUserManagerInternal();
16650        final int flags;
16651        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16652            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16653        } else if (umInternal.isUserRunning(userId)) {
16654            flags = StorageManager.FLAG_STORAGE_DE;
16655        } else {
16656            flags = 0;
16657        }
16658        prepareAppDataContentsLIF(pkg, userId, flags);
16659
16660        return true;
16661    }
16662
16663    /**
16664     * Reverts user permission state changes (permissions and flags) in
16665     * all packages for a given user.
16666     *
16667     * @param userId The device user for which to do a reset.
16668     */
16669    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16670        final int packageCount = mPackages.size();
16671        for (int i = 0; i < packageCount; i++) {
16672            PackageParser.Package pkg = mPackages.valueAt(i);
16673            PackageSetting ps = (PackageSetting) pkg.mExtras;
16674            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16675        }
16676    }
16677
16678    private void resetNetworkPolicies(int userId) {
16679        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16680    }
16681
16682    /**
16683     * Reverts user permission state changes (permissions and flags).
16684     *
16685     * @param ps The package for which to reset.
16686     * @param userId The device user for which to do a reset.
16687     */
16688    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16689            final PackageSetting ps, final int userId) {
16690        if (ps.pkg == null) {
16691            return;
16692        }
16693
16694        // These are flags that can change base on user actions.
16695        final int userSettableMask = FLAG_PERMISSION_USER_SET
16696                | FLAG_PERMISSION_USER_FIXED
16697                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16698                | FLAG_PERMISSION_REVIEW_REQUIRED;
16699
16700        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16701                | FLAG_PERMISSION_POLICY_FIXED;
16702
16703        boolean writeInstallPermissions = false;
16704        boolean writeRuntimePermissions = false;
16705
16706        final int permissionCount = ps.pkg.requestedPermissions.size();
16707        for (int i = 0; i < permissionCount; i++) {
16708            String permission = ps.pkg.requestedPermissions.get(i);
16709
16710            BasePermission bp = mSettings.mPermissions.get(permission);
16711            if (bp == null) {
16712                continue;
16713            }
16714
16715            // If shared user we just reset the state to which only this app contributed.
16716            if (ps.sharedUser != null) {
16717                boolean used = false;
16718                final int packageCount = ps.sharedUser.packages.size();
16719                for (int j = 0; j < packageCount; j++) {
16720                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16721                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16722                            && pkg.pkg.requestedPermissions.contains(permission)) {
16723                        used = true;
16724                        break;
16725                    }
16726                }
16727                if (used) {
16728                    continue;
16729                }
16730            }
16731
16732            PermissionsState permissionsState = ps.getPermissionsState();
16733
16734            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16735
16736            // Always clear the user settable flags.
16737            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16738                    bp.name) != null;
16739            // If permission review is enabled and this is a legacy app, mark the
16740            // permission as requiring a review as this is the initial state.
16741            int flags = 0;
16742            if (mPermissionReviewRequired
16743                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16744                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16745            }
16746            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16747                if (hasInstallState) {
16748                    writeInstallPermissions = true;
16749                } else {
16750                    writeRuntimePermissions = true;
16751                }
16752            }
16753
16754            // Below is only runtime permission handling.
16755            if (!bp.isRuntime()) {
16756                continue;
16757            }
16758
16759            // Never clobber system or policy.
16760            if ((oldFlags & policyOrSystemFlags) != 0) {
16761                continue;
16762            }
16763
16764            // If this permission was granted by default, make sure it is.
16765            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16766                if (permissionsState.grantRuntimePermission(bp, userId)
16767                        != PERMISSION_OPERATION_FAILURE) {
16768                    writeRuntimePermissions = true;
16769                }
16770            // If permission review is enabled the permissions for a legacy apps
16771            // are represented as constantly granted runtime ones, so don't revoke.
16772            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16773                // Otherwise, reset the permission.
16774                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16775                switch (revokeResult) {
16776                    case PERMISSION_OPERATION_SUCCESS:
16777                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16778                        writeRuntimePermissions = true;
16779                        final int appId = ps.appId;
16780                        mHandler.post(new Runnable() {
16781                            @Override
16782                            public void run() {
16783                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16784                            }
16785                        });
16786                    } break;
16787                }
16788            }
16789        }
16790
16791        // Synchronously write as we are taking permissions away.
16792        if (writeRuntimePermissions) {
16793            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16794        }
16795
16796        // Synchronously write as we are taking permissions away.
16797        if (writeInstallPermissions) {
16798            mSettings.writeLPr();
16799        }
16800    }
16801
16802    /**
16803     * Remove entries from the keystore daemon. Will only remove it if the
16804     * {@code appId} is valid.
16805     */
16806    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16807        if (appId < 0) {
16808            return;
16809        }
16810
16811        final KeyStore keyStore = KeyStore.getInstance();
16812        if (keyStore != null) {
16813            if (userId == UserHandle.USER_ALL) {
16814                for (final int individual : sUserManager.getUserIds()) {
16815                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16816                }
16817            } else {
16818                keyStore.clearUid(UserHandle.getUid(userId, appId));
16819            }
16820        } else {
16821            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16822        }
16823    }
16824
16825    @Override
16826    public void deleteApplicationCacheFiles(final String packageName,
16827            final IPackageDataObserver observer) {
16828        final int userId = UserHandle.getCallingUserId();
16829        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16830    }
16831
16832    @Override
16833    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16834            final IPackageDataObserver observer) {
16835        mContext.enforceCallingOrSelfPermission(
16836                android.Manifest.permission.DELETE_CACHE_FILES, null);
16837        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16838                /* requireFullPermission= */ true, /* checkShell= */ false,
16839                "delete application cache files");
16840
16841        final PackageParser.Package pkg;
16842        synchronized (mPackages) {
16843            pkg = mPackages.get(packageName);
16844        }
16845
16846        // Queue up an async operation since the package deletion may take a little while.
16847        mHandler.post(new Runnable() {
16848            public void run() {
16849                synchronized (mInstallLock) {
16850                    final int flags = StorageManager.FLAG_STORAGE_DE
16851                            | StorageManager.FLAG_STORAGE_CE;
16852                    // We're only clearing cache files, so we don't care if the
16853                    // app is unfrozen and still able to run
16854                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16855                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16856                }
16857                clearExternalStorageDataSync(packageName, userId, false);
16858                if (observer != null) {
16859                    try {
16860                        observer.onRemoveCompleted(packageName, true);
16861                    } catch (RemoteException e) {
16862                        Log.i(TAG, "Observer no longer exists.");
16863                    }
16864                }
16865            }
16866        });
16867    }
16868
16869    @Override
16870    public void getPackageSizeInfo(final String packageName, int userHandle,
16871            final IPackageStatsObserver observer) {
16872        mContext.enforceCallingOrSelfPermission(
16873                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16874        if (packageName == null) {
16875            throw new IllegalArgumentException("Attempt to get size of null packageName");
16876        }
16877
16878        PackageStats stats = new PackageStats(packageName, userHandle);
16879
16880        /*
16881         * Queue up an async operation since the package measurement may take a
16882         * little while.
16883         */
16884        Message msg = mHandler.obtainMessage(INIT_COPY);
16885        msg.obj = new MeasureParams(stats, observer);
16886        mHandler.sendMessage(msg);
16887    }
16888
16889    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16890        final PackageSetting ps;
16891        synchronized (mPackages) {
16892            ps = mSettings.mPackages.get(packageName);
16893            if (ps == null) {
16894                Slog.w(TAG, "Failed to find settings for " + packageName);
16895                return false;
16896            }
16897        }
16898        try {
16899            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16900                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16901                    ps.getCeDataInode(userId), ps.codePathString, stats);
16902        } catch (InstallerException e) {
16903            Slog.w(TAG, String.valueOf(e));
16904            return false;
16905        }
16906
16907        // For now, ignore code size of packages on system partition
16908        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16909            stats.codeSize = 0;
16910        }
16911
16912        return true;
16913    }
16914
16915    private int getUidTargetSdkVersionLockedLPr(int uid) {
16916        Object obj = mSettings.getUserIdLPr(uid);
16917        if (obj instanceof SharedUserSetting) {
16918            final SharedUserSetting sus = (SharedUserSetting) obj;
16919            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16920            final Iterator<PackageSetting> it = sus.packages.iterator();
16921            while (it.hasNext()) {
16922                final PackageSetting ps = it.next();
16923                if (ps.pkg != null) {
16924                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16925                    if (v < vers) vers = v;
16926                }
16927            }
16928            return vers;
16929        } else if (obj instanceof PackageSetting) {
16930            final PackageSetting ps = (PackageSetting) obj;
16931            if (ps.pkg != null) {
16932                return ps.pkg.applicationInfo.targetSdkVersion;
16933            }
16934        }
16935        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16936    }
16937
16938    @Override
16939    public void addPreferredActivity(IntentFilter filter, int match,
16940            ComponentName[] set, ComponentName activity, int userId) {
16941        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16942                "Adding preferred");
16943    }
16944
16945    private void addPreferredActivityInternal(IntentFilter filter, int match,
16946            ComponentName[] set, ComponentName activity, boolean always, int userId,
16947            String opname) {
16948        // writer
16949        int callingUid = Binder.getCallingUid();
16950        enforceCrossUserPermission(callingUid, userId,
16951                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16952        if (filter.countActions() == 0) {
16953            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16954            return;
16955        }
16956        synchronized (mPackages) {
16957            if (mContext.checkCallingOrSelfPermission(
16958                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16959                    != PackageManager.PERMISSION_GRANTED) {
16960                if (getUidTargetSdkVersionLockedLPr(callingUid)
16961                        < Build.VERSION_CODES.FROYO) {
16962                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16963                            + callingUid);
16964                    return;
16965                }
16966                mContext.enforceCallingOrSelfPermission(
16967                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16968            }
16969
16970            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16971            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16972                    + userId + ":");
16973            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16974            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16975            scheduleWritePackageRestrictionsLocked(userId);
16976            postPreferredActivityChangedBroadcast(userId);
16977        }
16978    }
16979
16980    private void postPreferredActivityChangedBroadcast(int userId) {
16981        mHandler.post(() -> {
16982            final IActivityManager am = ActivityManagerNative.getDefault();
16983            if (am == null) {
16984                return;
16985            }
16986
16987            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16988            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16989            try {
16990                am.broadcastIntent(null, intent, null, null,
16991                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16992                        null, false, false, userId);
16993            } catch (RemoteException e) {
16994            }
16995        });
16996    }
16997
16998    @Override
16999    public void replacePreferredActivity(IntentFilter filter, int match,
17000            ComponentName[] set, ComponentName activity, int userId) {
17001        if (filter.countActions() != 1) {
17002            throw new IllegalArgumentException(
17003                    "replacePreferredActivity expects filter to have only 1 action.");
17004        }
17005        if (filter.countDataAuthorities() != 0
17006                || filter.countDataPaths() != 0
17007                || filter.countDataSchemes() > 1
17008                || filter.countDataTypes() != 0) {
17009            throw new IllegalArgumentException(
17010                    "replacePreferredActivity expects filter to have no data authorities, " +
17011                    "paths, or types; and at most one scheme.");
17012        }
17013
17014        final int callingUid = Binder.getCallingUid();
17015        enforceCrossUserPermission(callingUid, userId,
17016                true /* requireFullPermission */, false /* checkShell */,
17017                "replace preferred activity");
17018        synchronized (mPackages) {
17019            if (mContext.checkCallingOrSelfPermission(
17020                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17021                    != PackageManager.PERMISSION_GRANTED) {
17022                if (getUidTargetSdkVersionLockedLPr(callingUid)
17023                        < Build.VERSION_CODES.FROYO) {
17024                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17025                            + Binder.getCallingUid());
17026                    return;
17027                }
17028                mContext.enforceCallingOrSelfPermission(
17029                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17030            }
17031
17032            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17033            if (pir != null) {
17034                // Get all of the existing entries that exactly match this filter.
17035                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17036                if (existing != null && existing.size() == 1) {
17037                    PreferredActivity cur = existing.get(0);
17038                    if (DEBUG_PREFERRED) {
17039                        Slog.i(TAG, "Checking replace of preferred:");
17040                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17041                        if (!cur.mPref.mAlways) {
17042                            Slog.i(TAG, "  -- CUR; not mAlways!");
17043                        } else {
17044                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17045                            Slog.i(TAG, "  -- CUR: mSet="
17046                                    + Arrays.toString(cur.mPref.mSetComponents));
17047                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17048                            Slog.i(TAG, "  -- NEW: mMatch="
17049                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17050                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17051                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17052                        }
17053                    }
17054                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17055                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17056                            && cur.mPref.sameSet(set)) {
17057                        // Setting the preferred activity to what it happens to be already
17058                        if (DEBUG_PREFERRED) {
17059                            Slog.i(TAG, "Replacing with same preferred activity "
17060                                    + cur.mPref.mShortComponent + " for user "
17061                                    + userId + ":");
17062                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17063                        }
17064                        return;
17065                    }
17066                }
17067
17068                if (existing != null) {
17069                    if (DEBUG_PREFERRED) {
17070                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17071                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17072                    }
17073                    for (int i = 0; i < existing.size(); i++) {
17074                        PreferredActivity pa = existing.get(i);
17075                        if (DEBUG_PREFERRED) {
17076                            Slog.i(TAG, "Removing existing preferred activity "
17077                                    + pa.mPref.mComponent + ":");
17078                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17079                        }
17080                        pir.removeFilter(pa);
17081                    }
17082                }
17083            }
17084            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17085                    "Replacing preferred");
17086        }
17087    }
17088
17089    @Override
17090    public void clearPackagePreferredActivities(String packageName) {
17091        final int uid = Binder.getCallingUid();
17092        // writer
17093        synchronized (mPackages) {
17094            PackageParser.Package pkg = mPackages.get(packageName);
17095            if (pkg == null || pkg.applicationInfo.uid != uid) {
17096                if (mContext.checkCallingOrSelfPermission(
17097                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17098                        != PackageManager.PERMISSION_GRANTED) {
17099                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17100                            < Build.VERSION_CODES.FROYO) {
17101                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17102                                + Binder.getCallingUid());
17103                        return;
17104                    }
17105                    mContext.enforceCallingOrSelfPermission(
17106                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17107                }
17108            }
17109
17110            int user = UserHandle.getCallingUserId();
17111            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17112                scheduleWritePackageRestrictionsLocked(user);
17113            }
17114        }
17115    }
17116
17117    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17118    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17119        ArrayList<PreferredActivity> removed = null;
17120        boolean changed = false;
17121        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17122            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17123            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17124            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17125                continue;
17126            }
17127            Iterator<PreferredActivity> it = pir.filterIterator();
17128            while (it.hasNext()) {
17129                PreferredActivity pa = it.next();
17130                // Mark entry for removal only if it matches the package name
17131                // and the entry is of type "always".
17132                if (packageName == null ||
17133                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17134                                && pa.mPref.mAlways)) {
17135                    if (removed == null) {
17136                        removed = new ArrayList<PreferredActivity>();
17137                    }
17138                    removed.add(pa);
17139                }
17140            }
17141            if (removed != null) {
17142                for (int j=0; j<removed.size(); j++) {
17143                    PreferredActivity pa = removed.get(j);
17144                    pir.removeFilter(pa);
17145                }
17146                changed = true;
17147            }
17148        }
17149        if (changed) {
17150            postPreferredActivityChangedBroadcast(userId);
17151        }
17152        return changed;
17153    }
17154
17155    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17156    private void clearIntentFilterVerificationsLPw(int userId) {
17157        final int packageCount = mPackages.size();
17158        for (int i = 0; i < packageCount; i++) {
17159            PackageParser.Package pkg = mPackages.valueAt(i);
17160            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17161        }
17162    }
17163
17164    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17165    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17166        if (userId == UserHandle.USER_ALL) {
17167            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17168                    sUserManager.getUserIds())) {
17169                for (int oneUserId : sUserManager.getUserIds()) {
17170                    scheduleWritePackageRestrictionsLocked(oneUserId);
17171                }
17172            }
17173        } else {
17174            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17175                scheduleWritePackageRestrictionsLocked(userId);
17176            }
17177        }
17178    }
17179
17180    void clearDefaultBrowserIfNeeded(String packageName) {
17181        for (int oneUserId : sUserManager.getUserIds()) {
17182            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17183            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17184            if (packageName.equals(defaultBrowserPackageName)) {
17185                setDefaultBrowserPackageName(null, oneUserId);
17186            }
17187        }
17188    }
17189
17190    @Override
17191    public void resetApplicationPreferences(int userId) {
17192        mContext.enforceCallingOrSelfPermission(
17193                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17194        final long identity = Binder.clearCallingIdentity();
17195        // writer
17196        try {
17197            synchronized (mPackages) {
17198                clearPackagePreferredActivitiesLPw(null, userId);
17199                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17200                // TODO: We have to reset the default SMS and Phone. This requires
17201                // significant refactoring to keep all default apps in the package
17202                // manager (cleaner but more work) or have the services provide
17203                // callbacks to the package manager to request a default app reset.
17204                applyFactoryDefaultBrowserLPw(userId);
17205                clearIntentFilterVerificationsLPw(userId);
17206                primeDomainVerificationsLPw(userId);
17207                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17208                scheduleWritePackageRestrictionsLocked(userId);
17209            }
17210            resetNetworkPolicies(userId);
17211        } finally {
17212            Binder.restoreCallingIdentity(identity);
17213        }
17214    }
17215
17216    @Override
17217    public int getPreferredActivities(List<IntentFilter> outFilters,
17218            List<ComponentName> outActivities, String packageName) {
17219
17220        int num = 0;
17221        final int userId = UserHandle.getCallingUserId();
17222        // reader
17223        synchronized (mPackages) {
17224            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17225            if (pir != null) {
17226                final Iterator<PreferredActivity> it = pir.filterIterator();
17227                while (it.hasNext()) {
17228                    final PreferredActivity pa = it.next();
17229                    if (packageName == null
17230                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17231                                    && pa.mPref.mAlways)) {
17232                        if (outFilters != null) {
17233                            outFilters.add(new IntentFilter(pa));
17234                        }
17235                        if (outActivities != null) {
17236                            outActivities.add(pa.mPref.mComponent);
17237                        }
17238                    }
17239                }
17240            }
17241        }
17242
17243        return num;
17244    }
17245
17246    @Override
17247    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17248            int userId) {
17249        int callingUid = Binder.getCallingUid();
17250        if (callingUid != Process.SYSTEM_UID) {
17251            throw new SecurityException(
17252                    "addPersistentPreferredActivity can only be run by the system");
17253        }
17254        if (filter.countActions() == 0) {
17255            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17256            return;
17257        }
17258        synchronized (mPackages) {
17259            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17260                    ":");
17261            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17262            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17263                    new PersistentPreferredActivity(filter, activity));
17264            scheduleWritePackageRestrictionsLocked(userId);
17265            postPreferredActivityChangedBroadcast(userId);
17266        }
17267    }
17268
17269    @Override
17270    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17271        int callingUid = Binder.getCallingUid();
17272        if (callingUid != Process.SYSTEM_UID) {
17273            throw new SecurityException(
17274                    "clearPackagePersistentPreferredActivities can only be run by the system");
17275        }
17276        ArrayList<PersistentPreferredActivity> removed = null;
17277        boolean changed = false;
17278        synchronized (mPackages) {
17279            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17280                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17281                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17282                        .valueAt(i);
17283                if (userId != thisUserId) {
17284                    continue;
17285                }
17286                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17287                while (it.hasNext()) {
17288                    PersistentPreferredActivity ppa = it.next();
17289                    // Mark entry for removal only if it matches the package name.
17290                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17291                        if (removed == null) {
17292                            removed = new ArrayList<PersistentPreferredActivity>();
17293                        }
17294                        removed.add(ppa);
17295                    }
17296                }
17297                if (removed != null) {
17298                    for (int j=0; j<removed.size(); j++) {
17299                        PersistentPreferredActivity ppa = removed.get(j);
17300                        ppir.removeFilter(ppa);
17301                    }
17302                    changed = true;
17303                }
17304            }
17305
17306            if (changed) {
17307                scheduleWritePackageRestrictionsLocked(userId);
17308                postPreferredActivityChangedBroadcast(userId);
17309            }
17310        }
17311    }
17312
17313    /**
17314     * Common machinery for picking apart a restored XML blob and passing
17315     * it to a caller-supplied functor to be applied to the running system.
17316     */
17317    private void restoreFromXml(XmlPullParser parser, int userId,
17318            String expectedStartTag, BlobXmlRestorer functor)
17319            throws IOException, XmlPullParserException {
17320        int type;
17321        while ((type = parser.next()) != XmlPullParser.START_TAG
17322                && type != XmlPullParser.END_DOCUMENT) {
17323        }
17324        if (type != XmlPullParser.START_TAG) {
17325            // oops didn't find a start tag?!
17326            if (DEBUG_BACKUP) {
17327                Slog.e(TAG, "Didn't find start tag during restore");
17328            }
17329            return;
17330        }
17331Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17332        // this is supposed to be TAG_PREFERRED_BACKUP
17333        if (!expectedStartTag.equals(parser.getName())) {
17334            if (DEBUG_BACKUP) {
17335                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17336            }
17337            return;
17338        }
17339
17340        // skip interfering stuff, then we're aligned with the backing implementation
17341        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17342Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17343        functor.apply(parser, userId);
17344    }
17345
17346    private interface BlobXmlRestorer {
17347        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17348    }
17349
17350    /**
17351     * Non-Binder method, support for the backup/restore mechanism: write the
17352     * full set of preferred activities in its canonical XML format.  Returns the
17353     * XML output as a byte array, or null if there is none.
17354     */
17355    @Override
17356    public byte[] getPreferredActivityBackup(int userId) {
17357        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17358            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17359        }
17360
17361        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17362        try {
17363            final XmlSerializer serializer = new FastXmlSerializer();
17364            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17365            serializer.startDocument(null, true);
17366            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17367
17368            synchronized (mPackages) {
17369                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17370            }
17371
17372            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17373            serializer.endDocument();
17374            serializer.flush();
17375        } catch (Exception e) {
17376            if (DEBUG_BACKUP) {
17377                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17378            }
17379            return null;
17380        }
17381
17382        return dataStream.toByteArray();
17383    }
17384
17385    @Override
17386    public void restorePreferredActivities(byte[] backup, int userId) {
17387        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17388            throw new SecurityException("Only the system may call restorePreferredActivities()");
17389        }
17390
17391        try {
17392            final XmlPullParser parser = Xml.newPullParser();
17393            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17394            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17395                    new BlobXmlRestorer() {
17396                        @Override
17397                        public void apply(XmlPullParser parser, int userId)
17398                                throws XmlPullParserException, IOException {
17399                            synchronized (mPackages) {
17400                                mSettings.readPreferredActivitiesLPw(parser, userId);
17401                            }
17402                        }
17403                    } );
17404        } catch (Exception e) {
17405            if (DEBUG_BACKUP) {
17406                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17407            }
17408        }
17409    }
17410
17411    /**
17412     * Non-Binder method, support for the backup/restore mechanism: write the
17413     * default browser (etc) settings in its canonical XML format.  Returns the default
17414     * browser XML representation as a byte array, or null if there is none.
17415     */
17416    @Override
17417    public byte[] getDefaultAppsBackup(int userId) {
17418        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17419            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17420        }
17421
17422        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17423        try {
17424            final XmlSerializer serializer = new FastXmlSerializer();
17425            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17426            serializer.startDocument(null, true);
17427            serializer.startTag(null, TAG_DEFAULT_APPS);
17428
17429            synchronized (mPackages) {
17430                mSettings.writeDefaultAppsLPr(serializer, userId);
17431            }
17432
17433            serializer.endTag(null, TAG_DEFAULT_APPS);
17434            serializer.endDocument();
17435            serializer.flush();
17436        } catch (Exception e) {
17437            if (DEBUG_BACKUP) {
17438                Slog.e(TAG, "Unable to write default apps for backup", e);
17439            }
17440            return null;
17441        }
17442
17443        return dataStream.toByteArray();
17444    }
17445
17446    @Override
17447    public void restoreDefaultApps(byte[] backup, int userId) {
17448        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17449            throw new SecurityException("Only the system may call restoreDefaultApps()");
17450        }
17451
17452        try {
17453            final XmlPullParser parser = Xml.newPullParser();
17454            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17455            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17456                    new BlobXmlRestorer() {
17457                        @Override
17458                        public void apply(XmlPullParser parser, int userId)
17459                                throws XmlPullParserException, IOException {
17460                            synchronized (mPackages) {
17461                                mSettings.readDefaultAppsLPw(parser, userId);
17462                            }
17463                        }
17464                    } );
17465        } catch (Exception e) {
17466            if (DEBUG_BACKUP) {
17467                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17468            }
17469        }
17470    }
17471
17472    @Override
17473    public byte[] getIntentFilterVerificationBackup(int userId) {
17474        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17475            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17476        }
17477
17478        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17479        try {
17480            final XmlSerializer serializer = new FastXmlSerializer();
17481            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17482            serializer.startDocument(null, true);
17483            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17484
17485            synchronized (mPackages) {
17486                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17487            }
17488
17489            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17490            serializer.endDocument();
17491            serializer.flush();
17492        } catch (Exception e) {
17493            if (DEBUG_BACKUP) {
17494                Slog.e(TAG, "Unable to write default apps for backup", e);
17495            }
17496            return null;
17497        }
17498
17499        return dataStream.toByteArray();
17500    }
17501
17502    @Override
17503    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17504        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17505            throw new SecurityException("Only the system may call restorePreferredActivities()");
17506        }
17507
17508        try {
17509            final XmlPullParser parser = Xml.newPullParser();
17510            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17511            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17512                    new BlobXmlRestorer() {
17513                        @Override
17514                        public void apply(XmlPullParser parser, int userId)
17515                                throws XmlPullParserException, IOException {
17516                            synchronized (mPackages) {
17517                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17518                                mSettings.writeLPr();
17519                            }
17520                        }
17521                    } );
17522        } catch (Exception e) {
17523            if (DEBUG_BACKUP) {
17524                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17525            }
17526        }
17527    }
17528
17529    @Override
17530    public byte[] getPermissionGrantBackup(int userId) {
17531        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17532            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17533        }
17534
17535        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17536        try {
17537            final XmlSerializer serializer = new FastXmlSerializer();
17538            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17539            serializer.startDocument(null, true);
17540            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17541
17542            synchronized (mPackages) {
17543                serializeRuntimePermissionGrantsLPr(serializer, userId);
17544            }
17545
17546            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17547            serializer.endDocument();
17548            serializer.flush();
17549        } catch (Exception e) {
17550            if (DEBUG_BACKUP) {
17551                Slog.e(TAG, "Unable to write default apps for backup", e);
17552            }
17553            return null;
17554        }
17555
17556        return dataStream.toByteArray();
17557    }
17558
17559    @Override
17560    public void restorePermissionGrants(byte[] backup, int userId) {
17561        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17562            throw new SecurityException("Only the system may call restorePermissionGrants()");
17563        }
17564
17565        try {
17566            final XmlPullParser parser = Xml.newPullParser();
17567            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17568            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17569                    new BlobXmlRestorer() {
17570                        @Override
17571                        public void apply(XmlPullParser parser, int userId)
17572                                throws XmlPullParserException, IOException {
17573                            synchronized (mPackages) {
17574                                processRestoredPermissionGrantsLPr(parser, userId);
17575                            }
17576                        }
17577                    } );
17578        } catch (Exception e) {
17579            if (DEBUG_BACKUP) {
17580                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17581            }
17582        }
17583    }
17584
17585    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17586            throws IOException {
17587        serializer.startTag(null, TAG_ALL_GRANTS);
17588
17589        final int N = mSettings.mPackages.size();
17590        for (int i = 0; i < N; i++) {
17591            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17592            boolean pkgGrantsKnown = false;
17593
17594            PermissionsState packagePerms = ps.getPermissionsState();
17595
17596            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17597                final int grantFlags = state.getFlags();
17598                // only look at grants that are not system/policy fixed
17599                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17600                    final boolean isGranted = state.isGranted();
17601                    // And only back up the user-twiddled state bits
17602                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17603                        final String packageName = mSettings.mPackages.keyAt(i);
17604                        if (!pkgGrantsKnown) {
17605                            serializer.startTag(null, TAG_GRANT);
17606                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17607                            pkgGrantsKnown = true;
17608                        }
17609
17610                        final boolean userSet =
17611                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17612                        final boolean userFixed =
17613                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17614                        final boolean revoke =
17615                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17616
17617                        serializer.startTag(null, TAG_PERMISSION);
17618                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17619                        if (isGranted) {
17620                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17621                        }
17622                        if (userSet) {
17623                            serializer.attribute(null, ATTR_USER_SET, "true");
17624                        }
17625                        if (userFixed) {
17626                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17627                        }
17628                        if (revoke) {
17629                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17630                        }
17631                        serializer.endTag(null, TAG_PERMISSION);
17632                    }
17633                }
17634            }
17635
17636            if (pkgGrantsKnown) {
17637                serializer.endTag(null, TAG_GRANT);
17638            }
17639        }
17640
17641        serializer.endTag(null, TAG_ALL_GRANTS);
17642    }
17643
17644    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17645            throws XmlPullParserException, IOException {
17646        String pkgName = null;
17647        int outerDepth = parser.getDepth();
17648        int type;
17649        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17650                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17651            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17652                continue;
17653            }
17654
17655            final String tagName = parser.getName();
17656            if (tagName.equals(TAG_GRANT)) {
17657                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17658                if (DEBUG_BACKUP) {
17659                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17660                }
17661            } else if (tagName.equals(TAG_PERMISSION)) {
17662
17663                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17664                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17665
17666                int newFlagSet = 0;
17667                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17668                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17669                }
17670                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17671                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17672                }
17673                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17674                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17675                }
17676                if (DEBUG_BACKUP) {
17677                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17678                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17679                }
17680                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17681                if (ps != null) {
17682                    // Already installed so we apply the grant immediately
17683                    if (DEBUG_BACKUP) {
17684                        Slog.v(TAG, "        + already installed; applying");
17685                    }
17686                    PermissionsState perms = ps.getPermissionsState();
17687                    BasePermission bp = mSettings.mPermissions.get(permName);
17688                    if (bp != null) {
17689                        if (isGranted) {
17690                            perms.grantRuntimePermission(bp, userId);
17691                        }
17692                        if (newFlagSet != 0) {
17693                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17694                        }
17695                    }
17696                } else {
17697                    // Need to wait for post-restore install to apply the grant
17698                    if (DEBUG_BACKUP) {
17699                        Slog.v(TAG, "        - not yet installed; saving for later");
17700                    }
17701                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17702                            isGranted, newFlagSet, userId);
17703                }
17704            } else {
17705                PackageManagerService.reportSettingsProblem(Log.WARN,
17706                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17707                XmlUtils.skipCurrentTag(parser);
17708            }
17709        }
17710
17711        scheduleWriteSettingsLocked();
17712        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17713    }
17714
17715    @Override
17716    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17717            int sourceUserId, int targetUserId, int flags) {
17718        mContext.enforceCallingOrSelfPermission(
17719                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17720        int callingUid = Binder.getCallingUid();
17721        enforceOwnerRights(ownerPackage, callingUid);
17722        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17723        if (intentFilter.countActions() == 0) {
17724            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17725            return;
17726        }
17727        synchronized (mPackages) {
17728            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17729                    ownerPackage, targetUserId, flags);
17730            CrossProfileIntentResolver resolver =
17731                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17732            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17733            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17734            if (existing != null) {
17735                int size = existing.size();
17736                for (int i = 0; i < size; i++) {
17737                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17738                        return;
17739                    }
17740                }
17741            }
17742            resolver.addFilter(newFilter);
17743            scheduleWritePackageRestrictionsLocked(sourceUserId);
17744        }
17745    }
17746
17747    @Override
17748    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17749        mContext.enforceCallingOrSelfPermission(
17750                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17751        int callingUid = Binder.getCallingUid();
17752        enforceOwnerRights(ownerPackage, callingUid);
17753        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17754        synchronized (mPackages) {
17755            CrossProfileIntentResolver resolver =
17756                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17757            ArraySet<CrossProfileIntentFilter> set =
17758                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17759            for (CrossProfileIntentFilter filter : set) {
17760                if (filter.getOwnerPackage().equals(ownerPackage)) {
17761                    resolver.removeFilter(filter);
17762                }
17763            }
17764            scheduleWritePackageRestrictionsLocked(sourceUserId);
17765        }
17766    }
17767
17768    // Enforcing that callingUid is owning pkg on userId
17769    private void enforceOwnerRights(String pkg, int callingUid) {
17770        // The system owns everything.
17771        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17772            return;
17773        }
17774        int callingUserId = UserHandle.getUserId(callingUid);
17775        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17776        if (pi == null) {
17777            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17778                    + callingUserId);
17779        }
17780        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17781            throw new SecurityException("Calling uid " + callingUid
17782                    + " does not own package " + pkg);
17783        }
17784    }
17785
17786    @Override
17787    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17788        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17789    }
17790
17791    private Intent getHomeIntent() {
17792        Intent intent = new Intent(Intent.ACTION_MAIN);
17793        intent.addCategory(Intent.CATEGORY_HOME);
17794        intent.addCategory(Intent.CATEGORY_DEFAULT);
17795        return intent;
17796    }
17797
17798    private IntentFilter getHomeFilter() {
17799        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17800        filter.addCategory(Intent.CATEGORY_HOME);
17801        filter.addCategory(Intent.CATEGORY_DEFAULT);
17802        return filter;
17803    }
17804
17805    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17806            int userId) {
17807        Intent intent  = getHomeIntent();
17808        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17809                PackageManager.GET_META_DATA, userId);
17810        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17811                true, false, false, userId);
17812
17813        allHomeCandidates.clear();
17814        if (list != null) {
17815            for (ResolveInfo ri : list) {
17816                allHomeCandidates.add(ri);
17817            }
17818        }
17819        return (preferred == null || preferred.activityInfo == null)
17820                ? null
17821                : new ComponentName(preferred.activityInfo.packageName,
17822                        preferred.activityInfo.name);
17823    }
17824
17825    @Override
17826    public void setHomeActivity(ComponentName comp, int userId) {
17827        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17828        getHomeActivitiesAsUser(homeActivities, userId);
17829
17830        boolean found = false;
17831
17832        final int size = homeActivities.size();
17833        final ComponentName[] set = new ComponentName[size];
17834        for (int i = 0; i < size; i++) {
17835            final ResolveInfo candidate = homeActivities.get(i);
17836            final ActivityInfo info = candidate.activityInfo;
17837            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17838            set[i] = activityName;
17839            if (!found && activityName.equals(comp)) {
17840                found = true;
17841            }
17842        }
17843        if (!found) {
17844            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17845                    + userId);
17846        }
17847        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17848                set, comp, userId);
17849    }
17850
17851    private @Nullable String getSetupWizardPackageName() {
17852        final Intent intent = new Intent(Intent.ACTION_MAIN);
17853        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17854
17855        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17856                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17857                        | MATCH_DISABLED_COMPONENTS,
17858                UserHandle.myUserId());
17859        if (matches.size() == 1) {
17860            return matches.get(0).getComponentInfo().packageName;
17861        } else {
17862            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17863                    + ": matches=" + matches);
17864            return null;
17865        }
17866    }
17867
17868    private @Nullable String getStorageManagerPackageName() {
17869        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17870
17871        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17872                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17873                        | MATCH_DISABLED_COMPONENTS,
17874                UserHandle.myUserId());
17875        if (matches.size() == 1) {
17876            return matches.get(0).getComponentInfo().packageName;
17877        } else {
17878            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17879                    + matches.size() + ": matches=" + matches);
17880            return null;
17881        }
17882    }
17883
17884    @Override
17885    public void setApplicationEnabledSetting(String appPackageName,
17886            int newState, int flags, int userId, String callingPackage) {
17887        if (!sUserManager.exists(userId)) return;
17888        if (callingPackage == null) {
17889            callingPackage = Integer.toString(Binder.getCallingUid());
17890        }
17891        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17892    }
17893
17894    @Override
17895    public void setComponentEnabledSetting(ComponentName componentName,
17896            int newState, int flags, int userId) {
17897        if (!sUserManager.exists(userId)) return;
17898        setEnabledSetting(componentName.getPackageName(),
17899                componentName.getClassName(), newState, flags, userId, null);
17900    }
17901
17902    private void setEnabledSetting(final String packageName, String className, int newState,
17903            final int flags, int userId, String callingPackage) {
17904        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17905              || newState == COMPONENT_ENABLED_STATE_ENABLED
17906              || newState == COMPONENT_ENABLED_STATE_DISABLED
17907              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17908              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17909            throw new IllegalArgumentException("Invalid new component state: "
17910                    + newState);
17911        }
17912        PackageSetting pkgSetting;
17913        final int uid = Binder.getCallingUid();
17914        final int permission;
17915        if (uid == Process.SYSTEM_UID) {
17916            permission = PackageManager.PERMISSION_GRANTED;
17917        } else {
17918            permission = mContext.checkCallingOrSelfPermission(
17919                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17920        }
17921        enforceCrossUserPermission(uid, userId,
17922                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17923        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17924        boolean sendNow = false;
17925        boolean isApp = (className == null);
17926        String componentName = isApp ? packageName : className;
17927        int packageUid = -1;
17928        ArrayList<String> components;
17929
17930        // writer
17931        synchronized (mPackages) {
17932            pkgSetting = mSettings.mPackages.get(packageName);
17933            if (pkgSetting == null) {
17934                if (className == null) {
17935                    throw new IllegalArgumentException("Unknown package: " + packageName);
17936                }
17937                throw new IllegalArgumentException(
17938                        "Unknown component: " + packageName + "/" + className);
17939            }
17940        }
17941
17942        // Limit who can change which apps
17943        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17944            // Don't allow apps that don't have permission to modify other apps
17945            if (!allowedByPermission) {
17946                throw new SecurityException(
17947                        "Permission Denial: attempt to change component state from pid="
17948                        + Binder.getCallingPid()
17949                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17950            }
17951            // Don't allow changing protected packages.
17952            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17953                throw new SecurityException("Cannot disable a protected package: " + packageName);
17954            }
17955        }
17956
17957        synchronized (mPackages) {
17958            if (uid == Process.SHELL_UID) {
17959                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17960                int oldState = pkgSetting.getEnabled(userId);
17961                if (className == null
17962                    &&
17963                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17964                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17965                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17966                    &&
17967                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17968                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17969                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17970                    // ok
17971                } else {
17972                    throw new SecurityException(
17973                            "Shell cannot change component state for " + packageName + "/"
17974                            + className + " to " + newState);
17975                }
17976            }
17977            if (className == null) {
17978                // We're dealing with an application/package level state change
17979                if (pkgSetting.getEnabled(userId) == newState) {
17980                    // Nothing to do
17981                    return;
17982                }
17983                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17984                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17985                    // Don't care about who enables an app.
17986                    callingPackage = null;
17987                }
17988                pkgSetting.setEnabled(newState, userId, callingPackage);
17989                // pkgSetting.pkg.mSetEnabled = newState;
17990            } else {
17991                // We're dealing with a component level state change
17992                // First, verify that this is a valid class name.
17993                PackageParser.Package pkg = pkgSetting.pkg;
17994                if (pkg == null || !pkg.hasComponentClassName(className)) {
17995                    if (pkg != null &&
17996                            pkg.applicationInfo.targetSdkVersion >=
17997                                    Build.VERSION_CODES.JELLY_BEAN) {
17998                        throw new IllegalArgumentException("Component class " + className
17999                                + " does not exist in " + packageName);
18000                    } else {
18001                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18002                                + className + " does not exist in " + packageName);
18003                    }
18004                }
18005                switch (newState) {
18006                case COMPONENT_ENABLED_STATE_ENABLED:
18007                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18008                        return;
18009                    }
18010                    break;
18011                case COMPONENT_ENABLED_STATE_DISABLED:
18012                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18013                        return;
18014                    }
18015                    break;
18016                case COMPONENT_ENABLED_STATE_DEFAULT:
18017                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18018                        return;
18019                    }
18020                    break;
18021                default:
18022                    Slog.e(TAG, "Invalid new component state: " + newState);
18023                    return;
18024                }
18025            }
18026            scheduleWritePackageRestrictionsLocked(userId);
18027            components = mPendingBroadcasts.get(userId, packageName);
18028            final boolean newPackage = components == null;
18029            if (newPackage) {
18030                components = new ArrayList<String>();
18031            }
18032            if (!components.contains(componentName)) {
18033                components.add(componentName);
18034            }
18035            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18036                sendNow = true;
18037                // Purge entry from pending broadcast list if another one exists already
18038                // since we are sending one right away.
18039                mPendingBroadcasts.remove(userId, packageName);
18040            } else {
18041                if (newPackage) {
18042                    mPendingBroadcasts.put(userId, packageName, components);
18043                }
18044                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18045                    // Schedule a message
18046                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18047                }
18048            }
18049        }
18050
18051        long callingId = Binder.clearCallingIdentity();
18052        try {
18053            if (sendNow) {
18054                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18055                sendPackageChangedBroadcast(packageName,
18056                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18057            }
18058        } finally {
18059            Binder.restoreCallingIdentity(callingId);
18060        }
18061    }
18062
18063    @Override
18064    public void flushPackageRestrictionsAsUser(int userId) {
18065        if (!sUserManager.exists(userId)) {
18066            return;
18067        }
18068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18069                false /* checkShell */, "flushPackageRestrictions");
18070        synchronized (mPackages) {
18071            mSettings.writePackageRestrictionsLPr(userId);
18072            mDirtyUsers.remove(userId);
18073            if (mDirtyUsers.isEmpty()) {
18074                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18075            }
18076        }
18077    }
18078
18079    private void sendPackageChangedBroadcast(String packageName,
18080            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18081        if (DEBUG_INSTALL)
18082            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18083                    + componentNames);
18084        Bundle extras = new Bundle(4);
18085        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18086        String nameList[] = new String[componentNames.size()];
18087        componentNames.toArray(nameList);
18088        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18089        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18090        extras.putInt(Intent.EXTRA_UID, packageUid);
18091        // If this is not reporting a change of the overall package, then only send it
18092        // to registered receivers.  We don't want to launch a swath of apps for every
18093        // little component state change.
18094        final int flags = !componentNames.contains(packageName)
18095                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18096        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18097                new int[] {UserHandle.getUserId(packageUid)});
18098    }
18099
18100    @Override
18101    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18102        if (!sUserManager.exists(userId)) return;
18103        final int uid = Binder.getCallingUid();
18104        final int permission = mContext.checkCallingOrSelfPermission(
18105                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18106        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18107        enforceCrossUserPermission(uid, userId,
18108                true /* requireFullPermission */, true /* checkShell */, "stop package");
18109        // writer
18110        synchronized (mPackages) {
18111            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18112                    allowedByPermission, uid, userId)) {
18113                scheduleWritePackageRestrictionsLocked(userId);
18114            }
18115        }
18116    }
18117
18118    @Override
18119    public String getInstallerPackageName(String packageName) {
18120        // reader
18121        synchronized (mPackages) {
18122            return mSettings.getInstallerPackageNameLPr(packageName);
18123        }
18124    }
18125
18126    public boolean isOrphaned(String packageName) {
18127        // reader
18128        synchronized (mPackages) {
18129            return mSettings.isOrphaned(packageName);
18130        }
18131    }
18132
18133    @Override
18134    public int getApplicationEnabledSetting(String packageName, int userId) {
18135        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18136        int uid = Binder.getCallingUid();
18137        enforceCrossUserPermission(uid, userId,
18138                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18139        // reader
18140        synchronized (mPackages) {
18141            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18142        }
18143    }
18144
18145    @Override
18146    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18147        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18148        int uid = Binder.getCallingUid();
18149        enforceCrossUserPermission(uid, userId,
18150                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18151        // reader
18152        synchronized (mPackages) {
18153            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18154        }
18155    }
18156
18157    @Override
18158    public void enterSafeMode() {
18159        enforceSystemOrRoot("Only the system can request entering safe mode");
18160
18161        if (!mSystemReady) {
18162            mSafeMode = true;
18163        }
18164    }
18165
18166    @Override
18167    public void systemReady() {
18168        mSystemReady = true;
18169
18170        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18171        // disabled after already being started.
18172        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18173                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18174
18175        // Read the compatibilty setting when the system is ready.
18176        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18177                mContext.getContentResolver(),
18178                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18179        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18180        if (DEBUG_SETTINGS) {
18181            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18182        }
18183
18184        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18185
18186        synchronized (mPackages) {
18187            // Verify that all of the preferred activity components actually
18188            // exist.  It is possible for applications to be updated and at
18189            // that point remove a previously declared activity component that
18190            // had been set as a preferred activity.  We try to clean this up
18191            // the next time we encounter that preferred activity, but it is
18192            // possible for the user flow to never be able to return to that
18193            // situation so here we do a sanity check to make sure we haven't
18194            // left any junk around.
18195            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18196            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18197                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18198                removed.clear();
18199                for (PreferredActivity pa : pir.filterSet()) {
18200                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18201                        removed.add(pa);
18202                    }
18203                }
18204                if (removed.size() > 0) {
18205                    for (int r=0; r<removed.size(); r++) {
18206                        PreferredActivity pa = removed.get(r);
18207                        Slog.w(TAG, "Removing dangling preferred activity: "
18208                                + pa.mPref.mComponent);
18209                        pir.removeFilter(pa);
18210                    }
18211                    mSettings.writePackageRestrictionsLPr(
18212                            mSettings.mPreferredActivities.keyAt(i));
18213                }
18214            }
18215
18216            for (int userId : UserManagerService.getInstance().getUserIds()) {
18217                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18218                    grantPermissionsUserIds = ArrayUtils.appendInt(
18219                            grantPermissionsUserIds, userId);
18220                }
18221            }
18222        }
18223        sUserManager.systemReady();
18224
18225        // If we upgraded grant all default permissions before kicking off.
18226        for (int userId : grantPermissionsUserIds) {
18227            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18228        }
18229
18230        // If we did not grant default permissions, we preload from this the
18231        // default permission exceptions lazily to ensure we don't hit the
18232        // disk on a new user creation.
18233        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18234            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18235        }
18236
18237        // Kick off any messages waiting for system ready
18238        if (mPostSystemReadyMessages != null) {
18239            for (Message msg : mPostSystemReadyMessages) {
18240                msg.sendToTarget();
18241            }
18242            mPostSystemReadyMessages = null;
18243        }
18244
18245        // Watch for external volumes that come and go over time
18246        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18247        storage.registerListener(mStorageListener);
18248
18249        mInstallerService.systemReady();
18250        mPackageDexOptimizer.systemReady();
18251
18252        MountServiceInternal mountServiceInternal = LocalServices.getService(
18253                MountServiceInternal.class);
18254        mountServiceInternal.addExternalStoragePolicy(
18255                new MountServiceInternal.ExternalStorageMountPolicy() {
18256            @Override
18257            public int getMountMode(int uid, String packageName) {
18258                if (Process.isIsolated(uid)) {
18259                    return Zygote.MOUNT_EXTERNAL_NONE;
18260                }
18261                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18262                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18263                }
18264                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18265                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18266                }
18267                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18268                    return Zygote.MOUNT_EXTERNAL_READ;
18269                }
18270                return Zygote.MOUNT_EXTERNAL_WRITE;
18271            }
18272
18273            @Override
18274            public boolean hasExternalStorage(int uid, String packageName) {
18275                return true;
18276            }
18277        });
18278
18279        // Now that we're mostly running, clean up stale users and apps
18280        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18281        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18282    }
18283
18284    @Override
18285    public boolean isSafeMode() {
18286        return mSafeMode;
18287    }
18288
18289    @Override
18290    public boolean hasSystemUidErrors() {
18291        return mHasSystemUidErrors;
18292    }
18293
18294    static String arrayToString(int[] array) {
18295        StringBuffer buf = new StringBuffer(128);
18296        buf.append('[');
18297        if (array != null) {
18298            for (int i=0; i<array.length; i++) {
18299                if (i > 0) buf.append(", ");
18300                buf.append(array[i]);
18301            }
18302        }
18303        buf.append(']');
18304        return buf.toString();
18305    }
18306
18307    static class DumpState {
18308        public static final int DUMP_LIBS = 1 << 0;
18309        public static final int DUMP_FEATURES = 1 << 1;
18310        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18311        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18312        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18313        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18314        public static final int DUMP_PERMISSIONS = 1 << 6;
18315        public static final int DUMP_PACKAGES = 1 << 7;
18316        public static final int DUMP_SHARED_USERS = 1 << 8;
18317        public static final int DUMP_MESSAGES = 1 << 9;
18318        public static final int DUMP_PROVIDERS = 1 << 10;
18319        public static final int DUMP_VERIFIERS = 1 << 11;
18320        public static final int DUMP_PREFERRED = 1 << 12;
18321        public static final int DUMP_PREFERRED_XML = 1 << 13;
18322        public static final int DUMP_KEYSETS = 1 << 14;
18323        public static final int DUMP_VERSION = 1 << 15;
18324        public static final int DUMP_INSTALLS = 1 << 16;
18325        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18326        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18327        public static final int DUMP_FROZEN = 1 << 19;
18328        public static final int DUMP_DEXOPT = 1 << 20;
18329        public static final int DUMP_COMPILER_STATS = 1 << 21;
18330
18331        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18332
18333        private int mTypes;
18334
18335        private int mOptions;
18336
18337        private boolean mTitlePrinted;
18338
18339        private SharedUserSetting mSharedUser;
18340
18341        public boolean isDumping(int type) {
18342            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18343                return true;
18344            }
18345
18346            return (mTypes & type) != 0;
18347        }
18348
18349        public void setDump(int type) {
18350            mTypes |= type;
18351        }
18352
18353        public boolean isOptionEnabled(int option) {
18354            return (mOptions & option) != 0;
18355        }
18356
18357        public void setOptionEnabled(int option) {
18358            mOptions |= option;
18359        }
18360
18361        public boolean onTitlePrinted() {
18362            final boolean printed = mTitlePrinted;
18363            mTitlePrinted = true;
18364            return printed;
18365        }
18366
18367        public boolean getTitlePrinted() {
18368            return mTitlePrinted;
18369        }
18370
18371        public void setTitlePrinted(boolean enabled) {
18372            mTitlePrinted = enabled;
18373        }
18374
18375        public SharedUserSetting getSharedUser() {
18376            return mSharedUser;
18377        }
18378
18379        public void setSharedUser(SharedUserSetting user) {
18380            mSharedUser = user;
18381        }
18382    }
18383
18384    @Override
18385    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18386            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18387        (new PackageManagerShellCommand(this)).exec(
18388                this, in, out, err, args, resultReceiver);
18389    }
18390
18391    @Override
18392    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18393        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18394                != PackageManager.PERMISSION_GRANTED) {
18395            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18396                    + Binder.getCallingPid()
18397                    + ", uid=" + Binder.getCallingUid()
18398                    + " without permission "
18399                    + android.Manifest.permission.DUMP);
18400            return;
18401        }
18402
18403        DumpState dumpState = new DumpState();
18404        boolean fullPreferred = false;
18405        boolean checkin = false;
18406
18407        String packageName = null;
18408        ArraySet<String> permissionNames = null;
18409
18410        int opti = 0;
18411        while (opti < args.length) {
18412            String opt = args[opti];
18413            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18414                break;
18415            }
18416            opti++;
18417
18418            if ("-a".equals(opt)) {
18419                // Right now we only know how to print all.
18420            } else if ("-h".equals(opt)) {
18421                pw.println("Package manager dump options:");
18422                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18423                pw.println("    --checkin: dump for a checkin");
18424                pw.println("    -f: print details of intent filters");
18425                pw.println("    -h: print this help");
18426                pw.println("  cmd may be one of:");
18427                pw.println("    l[ibraries]: list known shared libraries");
18428                pw.println("    f[eatures]: list device features");
18429                pw.println("    k[eysets]: print known keysets");
18430                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18431                pw.println("    perm[issions]: dump permissions");
18432                pw.println("    permission [name ...]: dump declaration and use of given permission");
18433                pw.println("    pref[erred]: print preferred package settings");
18434                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18435                pw.println("    prov[iders]: dump content providers");
18436                pw.println("    p[ackages]: dump installed packages");
18437                pw.println("    s[hared-users]: dump shared user IDs");
18438                pw.println("    m[essages]: print collected runtime messages");
18439                pw.println("    v[erifiers]: print package verifier info");
18440                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18441                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18442                pw.println("    version: print database version info");
18443                pw.println("    write: write current settings now");
18444                pw.println("    installs: details about install sessions");
18445                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18446                pw.println("    dexopt: dump dexopt state");
18447                pw.println("    compiler-stats: dump compiler statistics");
18448                pw.println("    <package.name>: info about given package");
18449                return;
18450            } else if ("--checkin".equals(opt)) {
18451                checkin = true;
18452            } else if ("-f".equals(opt)) {
18453                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18454            } else {
18455                pw.println("Unknown argument: " + opt + "; use -h for help");
18456            }
18457        }
18458
18459        // Is the caller requesting to dump a particular piece of data?
18460        if (opti < args.length) {
18461            String cmd = args[opti];
18462            opti++;
18463            // Is this a package name?
18464            if ("android".equals(cmd) || cmd.contains(".")) {
18465                packageName = cmd;
18466                // When dumping a single package, we always dump all of its
18467                // filter information since the amount of data will be reasonable.
18468                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18469            } else if ("check-permission".equals(cmd)) {
18470                if (opti >= args.length) {
18471                    pw.println("Error: check-permission missing permission argument");
18472                    return;
18473                }
18474                String perm = args[opti];
18475                opti++;
18476                if (opti >= args.length) {
18477                    pw.println("Error: check-permission missing package argument");
18478                    return;
18479                }
18480                String pkg = args[opti];
18481                opti++;
18482                int user = UserHandle.getUserId(Binder.getCallingUid());
18483                if (opti < args.length) {
18484                    try {
18485                        user = Integer.parseInt(args[opti]);
18486                    } catch (NumberFormatException e) {
18487                        pw.println("Error: check-permission user argument is not a number: "
18488                                + args[opti]);
18489                        return;
18490                    }
18491                }
18492                pw.println(checkPermission(perm, pkg, user));
18493                return;
18494            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18495                dumpState.setDump(DumpState.DUMP_LIBS);
18496            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18497                dumpState.setDump(DumpState.DUMP_FEATURES);
18498            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18499                if (opti >= args.length) {
18500                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18501                            | DumpState.DUMP_SERVICE_RESOLVERS
18502                            | DumpState.DUMP_RECEIVER_RESOLVERS
18503                            | DumpState.DUMP_CONTENT_RESOLVERS);
18504                } else {
18505                    while (opti < args.length) {
18506                        String name = args[opti];
18507                        if ("a".equals(name) || "activity".equals(name)) {
18508                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18509                        } else if ("s".equals(name) || "service".equals(name)) {
18510                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18511                        } else if ("r".equals(name) || "receiver".equals(name)) {
18512                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18513                        } else if ("c".equals(name) || "content".equals(name)) {
18514                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18515                        } else {
18516                            pw.println("Error: unknown resolver table type: " + name);
18517                            return;
18518                        }
18519                        opti++;
18520                    }
18521                }
18522            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18523                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18524            } else if ("permission".equals(cmd)) {
18525                if (opti >= args.length) {
18526                    pw.println("Error: permission requires permission name");
18527                    return;
18528                }
18529                permissionNames = new ArraySet<>();
18530                while (opti < args.length) {
18531                    permissionNames.add(args[opti]);
18532                    opti++;
18533                }
18534                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18535                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18536            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18537                dumpState.setDump(DumpState.DUMP_PREFERRED);
18538            } else if ("preferred-xml".equals(cmd)) {
18539                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18540                if (opti < args.length && "--full".equals(args[opti])) {
18541                    fullPreferred = true;
18542                    opti++;
18543                }
18544            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18545                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18546            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18547                dumpState.setDump(DumpState.DUMP_PACKAGES);
18548            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18549                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18550            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18551                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18552            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18553                dumpState.setDump(DumpState.DUMP_MESSAGES);
18554            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18555                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18556            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18557                    || "intent-filter-verifiers".equals(cmd)) {
18558                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18559            } else if ("version".equals(cmd)) {
18560                dumpState.setDump(DumpState.DUMP_VERSION);
18561            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18562                dumpState.setDump(DumpState.DUMP_KEYSETS);
18563            } else if ("installs".equals(cmd)) {
18564                dumpState.setDump(DumpState.DUMP_INSTALLS);
18565            } else if ("frozen".equals(cmd)) {
18566                dumpState.setDump(DumpState.DUMP_FROZEN);
18567            } else if ("dexopt".equals(cmd)) {
18568                dumpState.setDump(DumpState.DUMP_DEXOPT);
18569            } else if ("compiler-stats".equals(cmd)) {
18570                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18571            } else if ("write".equals(cmd)) {
18572                synchronized (mPackages) {
18573                    mSettings.writeLPr();
18574                    pw.println("Settings written.");
18575                    return;
18576                }
18577            }
18578        }
18579
18580        if (checkin) {
18581            pw.println("vers,1");
18582        }
18583
18584        // reader
18585        synchronized (mPackages) {
18586            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18587                if (!checkin) {
18588                    if (dumpState.onTitlePrinted())
18589                        pw.println();
18590                    pw.println("Database versions:");
18591                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18592                }
18593            }
18594
18595            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18596                if (!checkin) {
18597                    if (dumpState.onTitlePrinted())
18598                        pw.println();
18599                    pw.println("Verifiers:");
18600                    pw.print("  Required: ");
18601                    pw.print(mRequiredVerifierPackage);
18602                    pw.print(" (uid=");
18603                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18604                            UserHandle.USER_SYSTEM));
18605                    pw.println(")");
18606                } else if (mRequiredVerifierPackage != null) {
18607                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18608                    pw.print(",");
18609                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18610                            UserHandle.USER_SYSTEM));
18611                }
18612            }
18613
18614            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18615                    packageName == null) {
18616                if (mIntentFilterVerifierComponent != null) {
18617                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18618                    if (!checkin) {
18619                        if (dumpState.onTitlePrinted())
18620                            pw.println();
18621                        pw.println("Intent Filter Verifier:");
18622                        pw.print("  Using: ");
18623                        pw.print(verifierPackageName);
18624                        pw.print(" (uid=");
18625                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18626                                UserHandle.USER_SYSTEM));
18627                        pw.println(")");
18628                    } else if (verifierPackageName != null) {
18629                        pw.print("ifv,"); pw.print(verifierPackageName);
18630                        pw.print(",");
18631                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18632                                UserHandle.USER_SYSTEM));
18633                    }
18634                } else {
18635                    pw.println();
18636                    pw.println("No Intent Filter Verifier available!");
18637                }
18638            }
18639
18640            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18641                boolean printedHeader = false;
18642                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18643                while (it.hasNext()) {
18644                    String name = it.next();
18645                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18646                    if (!checkin) {
18647                        if (!printedHeader) {
18648                            if (dumpState.onTitlePrinted())
18649                                pw.println();
18650                            pw.println("Libraries:");
18651                            printedHeader = true;
18652                        }
18653                        pw.print("  ");
18654                    } else {
18655                        pw.print("lib,");
18656                    }
18657                    pw.print(name);
18658                    if (!checkin) {
18659                        pw.print(" -> ");
18660                    }
18661                    if (ent.path != null) {
18662                        if (!checkin) {
18663                            pw.print("(jar) ");
18664                            pw.print(ent.path);
18665                        } else {
18666                            pw.print(",jar,");
18667                            pw.print(ent.path);
18668                        }
18669                    } else {
18670                        if (!checkin) {
18671                            pw.print("(apk) ");
18672                            pw.print(ent.apk);
18673                        } else {
18674                            pw.print(",apk,");
18675                            pw.print(ent.apk);
18676                        }
18677                    }
18678                    pw.println();
18679                }
18680            }
18681
18682            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18683                if (dumpState.onTitlePrinted())
18684                    pw.println();
18685                if (!checkin) {
18686                    pw.println("Features:");
18687                }
18688
18689                for (FeatureInfo feat : mAvailableFeatures.values()) {
18690                    if (checkin) {
18691                        pw.print("feat,");
18692                        pw.print(feat.name);
18693                        pw.print(",");
18694                        pw.println(feat.version);
18695                    } else {
18696                        pw.print("  ");
18697                        pw.print(feat.name);
18698                        if (feat.version > 0) {
18699                            pw.print(" version=");
18700                            pw.print(feat.version);
18701                        }
18702                        pw.println();
18703                    }
18704                }
18705            }
18706
18707            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18708                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18709                        : "Activity Resolver Table:", "  ", packageName,
18710                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18711                    dumpState.setTitlePrinted(true);
18712                }
18713            }
18714            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18715                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18716                        : "Receiver Resolver Table:", "  ", packageName,
18717                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18718                    dumpState.setTitlePrinted(true);
18719                }
18720            }
18721            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18722                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18723                        : "Service Resolver Table:", "  ", packageName,
18724                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18725                    dumpState.setTitlePrinted(true);
18726                }
18727            }
18728            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18729                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18730                        : "Provider Resolver Table:", "  ", packageName,
18731                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18732                    dumpState.setTitlePrinted(true);
18733                }
18734            }
18735
18736            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18737                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18738                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18739                    int user = mSettings.mPreferredActivities.keyAt(i);
18740                    if (pir.dump(pw,
18741                            dumpState.getTitlePrinted()
18742                                ? "\nPreferred Activities User " + user + ":"
18743                                : "Preferred Activities User " + user + ":", "  ",
18744                            packageName, true, false)) {
18745                        dumpState.setTitlePrinted(true);
18746                    }
18747                }
18748            }
18749
18750            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18751                pw.flush();
18752                FileOutputStream fout = new FileOutputStream(fd);
18753                BufferedOutputStream str = new BufferedOutputStream(fout);
18754                XmlSerializer serializer = new FastXmlSerializer();
18755                try {
18756                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18757                    serializer.startDocument(null, true);
18758                    serializer.setFeature(
18759                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18760                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18761                    serializer.endDocument();
18762                    serializer.flush();
18763                } catch (IllegalArgumentException e) {
18764                    pw.println("Failed writing: " + e);
18765                } catch (IllegalStateException e) {
18766                    pw.println("Failed writing: " + e);
18767                } catch (IOException e) {
18768                    pw.println("Failed writing: " + e);
18769                }
18770            }
18771
18772            if (!checkin
18773                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18774                    && packageName == null) {
18775                pw.println();
18776                int count = mSettings.mPackages.size();
18777                if (count == 0) {
18778                    pw.println("No applications!");
18779                    pw.println();
18780                } else {
18781                    final String prefix = "  ";
18782                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18783                    if (allPackageSettings.size() == 0) {
18784                        pw.println("No domain preferred apps!");
18785                        pw.println();
18786                    } else {
18787                        pw.println("App verification status:");
18788                        pw.println();
18789                        count = 0;
18790                        for (PackageSetting ps : allPackageSettings) {
18791                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18792                            if (ivi == null || ivi.getPackageName() == null) continue;
18793                            pw.println(prefix + "Package: " + ivi.getPackageName());
18794                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18795                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18796                            pw.println();
18797                            count++;
18798                        }
18799                        if (count == 0) {
18800                            pw.println(prefix + "No app verification established.");
18801                            pw.println();
18802                        }
18803                        for (int userId : sUserManager.getUserIds()) {
18804                            pw.println("App linkages for user " + userId + ":");
18805                            pw.println();
18806                            count = 0;
18807                            for (PackageSetting ps : allPackageSettings) {
18808                                final long status = ps.getDomainVerificationStatusForUser(userId);
18809                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18810                                    continue;
18811                                }
18812                                pw.println(prefix + "Package: " + ps.name);
18813                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18814                                String statusStr = IntentFilterVerificationInfo.
18815                                        getStatusStringFromValue(status);
18816                                pw.println(prefix + "Status:  " + statusStr);
18817                                pw.println();
18818                                count++;
18819                            }
18820                            if (count == 0) {
18821                                pw.println(prefix + "No configured app linkages.");
18822                                pw.println();
18823                            }
18824                        }
18825                    }
18826                }
18827            }
18828
18829            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18830                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18831                if (packageName == null && permissionNames == null) {
18832                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18833                        if (iperm == 0) {
18834                            if (dumpState.onTitlePrinted())
18835                                pw.println();
18836                            pw.println("AppOp Permissions:");
18837                        }
18838                        pw.print("  AppOp Permission ");
18839                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18840                        pw.println(":");
18841                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18842                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18843                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18844                        }
18845                    }
18846                }
18847            }
18848
18849            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18850                boolean printedSomething = false;
18851                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18852                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18853                        continue;
18854                    }
18855                    if (!printedSomething) {
18856                        if (dumpState.onTitlePrinted())
18857                            pw.println();
18858                        pw.println("Registered ContentProviders:");
18859                        printedSomething = true;
18860                    }
18861                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18862                    pw.print("    "); pw.println(p.toString());
18863                }
18864                printedSomething = false;
18865                for (Map.Entry<String, PackageParser.Provider> entry :
18866                        mProvidersByAuthority.entrySet()) {
18867                    PackageParser.Provider p = entry.getValue();
18868                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18869                        continue;
18870                    }
18871                    if (!printedSomething) {
18872                        if (dumpState.onTitlePrinted())
18873                            pw.println();
18874                        pw.println("ContentProvider Authorities:");
18875                        printedSomething = true;
18876                    }
18877                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18878                    pw.print("    "); pw.println(p.toString());
18879                    if (p.info != null && p.info.applicationInfo != null) {
18880                        final String appInfo = p.info.applicationInfo.toString();
18881                        pw.print("      applicationInfo="); pw.println(appInfo);
18882                    }
18883                }
18884            }
18885
18886            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18887                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18888            }
18889
18890            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18891                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18892            }
18893
18894            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18895                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18896            }
18897
18898            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18899                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18900            }
18901
18902            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18903                // XXX should handle packageName != null by dumping only install data that
18904                // the given package is involved with.
18905                if (dumpState.onTitlePrinted()) pw.println();
18906                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18907            }
18908
18909            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18910                // XXX should handle packageName != null by dumping only install data that
18911                // the given package is involved with.
18912                if (dumpState.onTitlePrinted()) pw.println();
18913
18914                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18915                ipw.println();
18916                ipw.println("Frozen packages:");
18917                ipw.increaseIndent();
18918                if (mFrozenPackages.size() == 0) {
18919                    ipw.println("(none)");
18920                } else {
18921                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18922                        ipw.println(mFrozenPackages.valueAt(i));
18923                    }
18924                }
18925                ipw.decreaseIndent();
18926            }
18927
18928            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18929                if (dumpState.onTitlePrinted()) pw.println();
18930                dumpDexoptStateLPr(pw, packageName);
18931            }
18932
18933            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18934                if (dumpState.onTitlePrinted()) pw.println();
18935                dumpCompilerStatsLPr(pw, packageName);
18936            }
18937
18938            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18939                if (dumpState.onTitlePrinted()) pw.println();
18940                mSettings.dumpReadMessagesLPr(pw, dumpState);
18941
18942                pw.println();
18943                pw.println("Package warning messages:");
18944                BufferedReader in = null;
18945                String line = null;
18946                try {
18947                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18948                    while ((line = in.readLine()) != null) {
18949                        if (line.contains("ignored: updated version")) continue;
18950                        pw.println(line);
18951                    }
18952                } catch (IOException ignored) {
18953                } finally {
18954                    IoUtils.closeQuietly(in);
18955                }
18956            }
18957
18958            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18959                BufferedReader in = null;
18960                String line = null;
18961                try {
18962                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18963                    while ((line = in.readLine()) != null) {
18964                        if (line.contains("ignored: updated version")) continue;
18965                        pw.print("msg,");
18966                        pw.println(line);
18967                    }
18968                } catch (IOException ignored) {
18969                } finally {
18970                    IoUtils.closeQuietly(in);
18971                }
18972            }
18973        }
18974    }
18975
18976    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18977        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18978        ipw.println();
18979        ipw.println("Dexopt state:");
18980        ipw.increaseIndent();
18981        Collection<PackageParser.Package> packages = null;
18982        if (packageName != null) {
18983            PackageParser.Package targetPackage = mPackages.get(packageName);
18984            if (targetPackage != null) {
18985                packages = Collections.singletonList(targetPackage);
18986            } else {
18987                ipw.println("Unable to find package: " + packageName);
18988                return;
18989            }
18990        } else {
18991            packages = mPackages.values();
18992        }
18993
18994        for (PackageParser.Package pkg : packages) {
18995            ipw.println("[" + pkg.packageName + "]");
18996            ipw.increaseIndent();
18997            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18998            ipw.decreaseIndent();
18999        }
19000    }
19001
19002    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19003        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19004        ipw.println();
19005        ipw.println("Compiler stats:");
19006        ipw.increaseIndent();
19007        Collection<PackageParser.Package> packages = null;
19008        if (packageName != null) {
19009            PackageParser.Package targetPackage = mPackages.get(packageName);
19010            if (targetPackage != null) {
19011                packages = Collections.singletonList(targetPackage);
19012            } else {
19013                ipw.println("Unable to find package: " + packageName);
19014                return;
19015            }
19016        } else {
19017            packages = mPackages.values();
19018        }
19019
19020        for (PackageParser.Package pkg : packages) {
19021            ipw.println("[" + pkg.packageName + "]");
19022            ipw.increaseIndent();
19023
19024            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19025            if (stats == null) {
19026                ipw.println("(No recorded stats)");
19027            } else {
19028                stats.dump(ipw);
19029            }
19030            ipw.decreaseIndent();
19031        }
19032    }
19033
19034    private String dumpDomainString(String packageName) {
19035        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19036                .getList();
19037        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19038
19039        ArraySet<String> result = new ArraySet<>();
19040        if (iviList.size() > 0) {
19041            for (IntentFilterVerificationInfo ivi : iviList) {
19042                for (String host : ivi.getDomains()) {
19043                    result.add(host);
19044                }
19045            }
19046        }
19047        if (filters != null && filters.size() > 0) {
19048            for (IntentFilter filter : filters) {
19049                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19050                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19051                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19052                    result.addAll(filter.getHostsList());
19053                }
19054            }
19055        }
19056
19057        StringBuilder sb = new StringBuilder(result.size() * 16);
19058        for (String domain : result) {
19059            if (sb.length() > 0) sb.append(" ");
19060            sb.append(domain);
19061        }
19062        return sb.toString();
19063    }
19064
19065    // ------- apps on sdcard specific code -------
19066    static final boolean DEBUG_SD_INSTALL = false;
19067
19068    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19069
19070    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19071
19072    private boolean mMediaMounted = false;
19073
19074    static String getEncryptKey() {
19075        try {
19076            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19077                    SD_ENCRYPTION_KEYSTORE_NAME);
19078            if (sdEncKey == null) {
19079                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19080                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19081                if (sdEncKey == null) {
19082                    Slog.e(TAG, "Failed to create encryption keys");
19083                    return null;
19084                }
19085            }
19086            return sdEncKey;
19087        } catch (NoSuchAlgorithmException nsae) {
19088            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19089            return null;
19090        } catch (IOException ioe) {
19091            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19092            return null;
19093        }
19094    }
19095
19096    /*
19097     * Update media status on PackageManager.
19098     */
19099    @Override
19100    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19101        int callingUid = Binder.getCallingUid();
19102        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19103            throw new SecurityException("Media status can only be updated by the system");
19104        }
19105        // reader; this apparently protects mMediaMounted, but should probably
19106        // be a different lock in that case.
19107        synchronized (mPackages) {
19108            Log.i(TAG, "Updating external media status from "
19109                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19110                    + (mediaStatus ? "mounted" : "unmounted"));
19111            if (DEBUG_SD_INSTALL)
19112                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19113                        + ", mMediaMounted=" + mMediaMounted);
19114            if (mediaStatus == mMediaMounted) {
19115                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19116                        : 0, -1);
19117                mHandler.sendMessage(msg);
19118                return;
19119            }
19120            mMediaMounted = mediaStatus;
19121        }
19122        // Queue up an async operation since the package installation may take a
19123        // little while.
19124        mHandler.post(new Runnable() {
19125            public void run() {
19126                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19127            }
19128        });
19129    }
19130
19131    /**
19132     * Called by MountService when the initial ASECs to scan are available.
19133     * Should block until all the ASEC containers are finished being scanned.
19134     */
19135    public void scanAvailableAsecs() {
19136        updateExternalMediaStatusInner(true, false, false);
19137    }
19138
19139    /*
19140     * Collect information of applications on external media, map them against
19141     * existing containers and update information based on current mount status.
19142     * Please note that we always have to report status if reportStatus has been
19143     * set to true especially when unloading packages.
19144     */
19145    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19146            boolean externalStorage) {
19147        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19148        int[] uidArr = EmptyArray.INT;
19149
19150        final String[] list = PackageHelper.getSecureContainerList();
19151        if (ArrayUtils.isEmpty(list)) {
19152            Log.i(TAG, "No secure containers found");
19153        } else {
19154            // Process list of secure containers and categorize them
19155            // as active or stale based on their package internal state.
19156
19157            // reader
19158            synchronized (mPackages) {
19159                for (String cid : list) {
19160                    // Leave stages untouched for now; installer service owns them
19161                    if (PackageInstallerService.isStageName(cid)) continue;
19162
19163                    if (DEBUG_SD_INSTALL)
19164                        Log.i(TAG, "Processing container " + cid);
19165                    String pkgName = getAsecPackageName(cid);
19166                    if (pkgName == null) {
19167                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19168                        continue;
19169                    }
19170                    if (DEBUG_SD_INSTALL)
19171                        Log.i(TAG, "Looking for pkg : " + pkgName);
19172
19173                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19174                    if (ps == null) {
19175                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19176                        continue;
19177                    }
19178
19179                    /*
19180                     * Skip packages that are not external if we're unmounting
19181                     * external storage.
19182                     */
19183                    if (externalStorage && !isMounted && !isExternal(ps)) {
19184                        continue;
19185                    }
19186
19187                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19188                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19189                    // The package status is changed only if the code path
19190                    // matches between settings and the container id.
19191                    if (ps.codePathString != null
19192                            && ps.codePathString.startsWith(args.getCodePath())) {
19193                        if (DEBUG_SD_INSTALL) {
19194                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19195                                    + " at code path: " + ps.codePathString);
19196                        }
19197
19198                        // We do have a valid package installed on sdcard
19199                        processCids.put(args, ps.codePathString);
19200                        final int uid = ps.appId;
19201                        if (uid != -1) {
19202                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19203                        }
19204                    } else {
19205                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19206                                + ps.codePathString);
19207                    }
19208                }
19209            }
19210
19211            Arrays.sort(uidArr);
19212        }
19213
19214        // Process packages with valid entries.
19215        if (isMounted) {
19216            if (DEBUG_SD_INSTALL)
19217                Log.i(TAG, "Loading packages");
19218            loadMediaPackages(processCids, uidArr, externalStorage);
19219            startCleaningPackages();
19220            mInstallerService.onSecureContainersAvailable();
19221        } else {
19222            if (DEBUG_SD_INSTALL)
19223                Log.i(TAG, "Unloading packages");
19224            unloadMediaPackages(processCids, uidArr, reportStatus);
19225        }
19226    }
19227
19228    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19229            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19230        final int size = infos.size();
19231        final String[] packageNames = new String[size];
19232        final int[] packageUids = new int[size];
19233        for (int i = 0; i < size; i++) {
19234            final ApplicationInfo info = infos.get(i);
19235            packageNames[i] = info.packageName;
19236            packageUids[i] = info.uid;
19237        }
19238        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19239                finishedReceiver);
19240    }
19241
19242    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19243            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19244        sendResourcesChangedBroadcast(mediaStatus, replacing,
19245                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19246    }
19247
19248    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19249            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19250        int size = pkgList.length;
19251        if (size > 0) {
19252            // Send broadcasts here
19253            Bundle extras = new Bundle();
19254            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19255            if (uidArr != null) {
19256                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19257            }
19258            if (replacing) {
19259                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19260            }
19261            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19262                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19263            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19264        }
19265    }
19266
19267   /*
19268     * Look at potentially valid container ids from processCids If package
19269     * information doesn't match the one on record or package scanning fails,
19270     * the cid is added to list of removeCids. We currently don't delete stale
19271     * containers.
19272     */
19273    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19274            boolean externalStorage) {
19275        ArrayList<String> pkgList = new ArrayList<String>();
19276        Set<AsecInstallArgs> keys = processCids.keySet();
19277
19278        for (AsecInstallArgs args : keys) {
19279            String codePath = processCids.get(args);
19280            if (DEBUG_SD_INSTALL)
19281                Log.i(TAG, "Loading container : " + args.cid);
19282            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19283            try {
19284                // Make sure there are no container errors first.
19285                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19286                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19287                            + " when installing from sdcard");
19288                    continue;
19289                }
19290                // Check code path here.
19291                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19292                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19293                            + " does not match one in settings " + codePath);
19294                    continue;
19295                }
19296                // Parse package
19297                int parseFlags = mDefParseFlags;
19298                if (args.isExternalAsec()) {
19299                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19300                }
19301                if (args.isFwdLocked()) {
19302                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19303                }
19304
19305                synchronized (mInstallLock) {
19306                    PackageParser.Package pkg = null;
19307                    try {
19308                        // Sadly we don't know the package name yet to freeze it
19309                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19310                                SCAN_IGNORE_FROZEN, 0, null);
19311                    } catch (PackageManagerException e) {
19312                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19313                    }
19314                    // Scan the package
19315                    if (pkg != null) {
19316                        /*
19317                         * TODO why is the lock being held? doPostInstall is
19318                         * called in other places without the lock. This needs
19319                         * to be straightened out.
19320                         */
19321                        // writer
19322                        synchronized (mPackages) {
19323                            retCode = PackageManager.INSTALL_SUCCEEDED;
19324                            pkgList.add(pkg.packageName);
19325                            // Post process args
19326                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19327                                    pkg.applicationInfo.uid);
19328                        }
19329                    } else {
19330                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19331                    }
19332                }
19333
19334            } finally {
19335                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19336                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19337                }
19338            }
19339        }
19340        // writer
19341        synchronized (mPackages) {
19342            // If the platform SDK has changed since the last time we booted,
19343            // we need to re-grant app permission to catch any new ones that
19344            // appear. This is really a hack, and means that apps can in some
19345            // cases get permissions that the user didn't initially explicitly
19346            // allow... it would be nice to have some better way to handle
19347            // this situation.
19348            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19349                    : mSettings.getInternalVersion();
19350            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19351                    : StorageManager.UUID_PRIVATE_INTERNAL;
19352
19353            int updateFlags = UPDATE_PERMISSIONS_ALL;
19354            if (ver.sdkVersion != mSdkVersion) {
19355                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19356                        + mSdkVersion + "; regranting permissions for external");
19357                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19358            }
19359            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19360
19361            // Yay, everything is now upgraded
19362            ver.forceCurrent();
19363
19364            // can downgrade to reader
19365            // Persist settings
19366            mSettings.writeLPr();
19367        }
19368        // Send a broadcast to let everyone know we are done processing
19369        if (pkgList.size() > 0) {
19370            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19371        }
19372    }
19373
19374   /*
19375     * Utility method to unload a list of specified containers
19376     */
19377    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19378        // Just unmount all valid containers.
19379        for (AsecInstallArgs arg : cidArgs) {
19380            synchronized (mInstallLock) {
19381                arg.doPostDeleteLI(false);
19382           }
19383       }
19384   }
19385
19386    /*
19387     * Unload packages mounted on external media. This involves deleting package
19388     * data from internal structures, sending broadcasts about disabled packages,
19389     * gc'ing to free up references, unmounting all secure containers
19390     * corresponding to packages on external media, and posting a
19391     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19392     * that we always have to post this message if status has been requested no
19393     * matter what.
19394     */
19395    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19396            final boolean reportStatus) {
19397        if (DEBUG_SD_INSTALL)
19398            Log.i(TAG, "unloading media packages");
19399        ArrayList<String> pkgList = new ArrayList<String>();
19400        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19401        final Set<AsecInstallArgs> keys = processCids.keySet();
19402        for (AsecInstallArgs args : keys) {
19403            String pkgName = args.getPackageName();
19404            if (DEBUG_SD_INSTALL)
19405                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19406            // Delete package internally
19407            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19408            synchronized (mInstallLock) {
19409                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19410                final boolean res;
19411                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19412                        "unloadMediaPackages")) {
19413                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19414                            null);
19415                }
19416                if (res) {
19417                    pkgList.add(pkgName);
19418                } else {
19419                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19420                    failedList.add(args);
19421                }
19422            }
19423        }
19424
19425        // reader
19426        synchronized (mPackages) {
19427            // We didn't update the settings after removing each package;
19428            // write them now for all packages.
19429            mSettings.writeLPr();
19430        }
19431
19432        // We have to absolutely send UPDATED_MEDIA_STATUS only
19433        // after confirming that all the receivers processed the ordered
19434        // broadcast when packages get disabled, force a gc to clean things up.
19435        // and unload all the containers.
19436        if (pkgList.size() > 0) {
19437            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19438                    new IIntentReceiver.Stub() {
19439                public void performReceive(Intent intent, int resultCode, String data,
19440                        Bundle extras, boolean ordered, boolean sticky,
19441                        int sendingUser) throws RemoteException {
19442                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19443                            reportStatus ? 1 : 0, 1, keys);
19444                    mHandler.sendMessage(msg);
19445                }
19446            });
19447        } else {
19448            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19449                    keys);
19450            mHandler.sendMessage(msg);
19451        }
19452    }
19453
19454    private void loadPrivatePackages(final VolumeInfo vol) {
19455        mHandler.post(new Runnable() {
19456            @Override
19457            public void run() {
19458                loadPrivatePackagesInner(vol);
19459            }
19460        });
19461    }
19462
19463    private void loadPrivatePackagesInner(VolumeInfo vol) {
19464        final String volumeUuid = vol.fsUuid;
19465        if (TextUtils.isEmpty(volumeUuid)) {
19466            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19467            return;
19468        }
19469
19470        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19471        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19472        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19473
19474        final VersionInfo ver;
19475        final List<PackageSetting> packages;
19476        synchronized (mPackages) {
19477            ver = mSettings.findOrCreateVersion(volumeUuid);
19478            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19479        }
19480
19481        for (PackageSetting ps : packages) {
19482            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19483            synchronized (mInstallLock) {
19484                final PackageParser.Package pkg;
19485                try {
19486                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19487                    loaded.add(pkg.applicationInfo);
19488
19489                } catch (PackageManagerException e) {
19490                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19491                }
19492
19493                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19494                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19495                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19496                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19497                }
19498            }
19499        }
19500
19501        // Reconcile app data for all started/unlocked users
19502        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19503        final UserManager um = mContext.getSystemService(UserManager.class);
19504        UserManagerInternal umInternal = getUserManagerInternal();
19505        for (UserInfo user : um.getUsers()) {
19506            final int flags;
19507            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19508                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19509            } else if (umInternal.isUserRunning(user.id)) {
19510                flags = StorageManager.FLAG_STORAGE_DE;
19511            } else {
19512                continue;
19513            }
19514
19515            try {
19516                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19517                synchronized (mInstallLock) {
19518                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19519                }
19520            } catch (IllegalStateException e) {
19521                // Device was probably ejected, and we'll process that event momentarily
19522                Slog.w(TAG, "Failed to prepare storage: " + e);
19523            }
19524        }
19525
19526        synchronized (mPackages) {
19527            int updateFlags = UPDATE_PERMISSIONS_ALL;
19528            if (ver.sdkVersion != mSdkVersion) {
19529                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19530                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19531                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19532            }
19533            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19534
19535            // Yay, everything is now upgraded
19536            ver.forceCurrent();
19537
19538            mSettings.writeLPr();
19539        }
19540
19541        for (PackageFreezer freezer : freezers) {
19542            freezer.close();
19543        }
19544
19545        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19546        sendResourcesChangedBroadcast(true, false, loaded, null);
19547    }
19548
19549    private void unloadPrivatePackages(final VolumeInfo vol) {
19550        mHandler.post(new Runnable() {
19551            @Override
19552            public void run() {
19553                unloadPrivatePackagesInner(vol);
19554            }
19555        });
19556    }
19557
19558    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19559        final String volumeUuid = vol.fsUuid;
19560        if (TextUtils.isEmpty(volumeUuid)) {
19561            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19562            return;
19563        }
19564
19565        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19566        synchronized (mInstallLock) {
19567        synchronized (mPackages) {
19568            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19569            for (PackageSetting ps : packages) {
19570                if (ps.pkg == null) continue;
19571
19572                final ApplicationInfo info = ps.pkg.applicationInfo;
19573                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19574                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19575
19576                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19577                        "unloadPrivatePackagesInner")) {
19578                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19579                            false, null)) {
19580                        unloaded.add(info);
19581                    } else {
19582                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19583                    }
19584                }
19585
19586                // Try very hard to release any references to this package
19587                // so we don't risk the system server being killed due to
19588                // open FDs
19589                AttributeCache.instance().removePackage(ps.name);
19590            }
19591
19592            mSettings.writeLPr();
19593        }
19594        }
19595
19596        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19597        sendResourcesChangedBroadcast(false, false, unloaded, null);
19598
19599        // Try very hard to release any references to this path so we don't risk
19600        // the system server being killed due to open FDs
19601        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19602
19603        for (int i = 0; i < 3; i++) {
19604            System.gc();
19605            System.runFinalization();
19606        }
19607    }
19608
19609    /**
19610     * Prepare storage areas for given user on all mounted devices.
19611     */
19612    void prepareUserData(int userId, int userSerial, int flags) {
19613        synchronized (mInstallLock) {
19614            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19615            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19616                final String volumeUuid = vol.getFsUuid();
19617                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19618            }
19619        }
19620    }
19621
19622    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19623            boolean allowRecover) {
19624        // Prepare storage and verify that serial numbers are consistent; if
19625        // there's a mismatch we need to destroy to avoid leaking data
19626        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19627        try {
19628            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19629
19630            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19631                UserManagerService.enforceSerialNumber(
19632                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19633                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19634                    UserManagerService.enforceSerialNumber(
19635                            Environment.getDataSystemDeDirectory(userId), userSerial);
19636                }
19637            }
19638            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19639                UserManagerService.enforceSerialNumber(
19640                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19641                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19642                    UserManagerService.enforceSerialNumber(
19643                            Environment.getDataSystemCeDirectory(userId), userSerial);
19644                }
19645            }
19646
19647            synchronized (mInstallLock) {
19648                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19649            }
19650        } catch (Exception e) {
19651            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19652                    + " because we failed to prepare: " + e);
19653            destroyUserDataLI(volumeUuid, userId,
19654                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19655
19656            if (allowRecover) {
19657                // Try one last time; if we fail again we're really in trouble
19658                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19659            }
19660        }
19661    }
19662
19663    /**
19664     * Destroy storage areas for given user on all mounted devices.
19665     */
19666    void destroyUserData(int userId, int flags) {
19667        synchronized (mInstallLock) {
19668            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19669            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19670                final String volumeUuid = vol.getFsUuid();
19671                destroyUserDataLI(volumeUuid, userId, flags);
19672            }
19673        }
19674    }
19675
19676    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19677        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19678        try {
19679            // Clean up app data, profile data, and media data
19680            mInstaller.destroyUserData(volumeUuid, userId, flags);
19681
19682            // Clean up system data
19683            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19684                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19685                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19686                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19687                }
19688                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19689                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19690                }
19691            }
19692
19693            // Data with special labels is now gone, so finish the job
19694            storage.destroyUserStorage(volumeUuid, userId, flags);
19695
19696        } catch (Exception e) {
19697            logCriticalInfo(Log.WARN,
19698                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19699        }
19700    }
19701
19702    /**
19703     * Examine all users present on given mounted volume, and destroy data
19704     * belonging to users that are no longer valid, or whose user ID has been
19705     * recycled.
19706     */
19707    private void reconcileUsers(String volumeUuid) {
19708        final List<File> files = new ArrayList<>();
19709        Collections.addAll(files, FileUtils
19710                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19711        Collections.addAll(files, FileUtils
19712                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19713        Collections.addAll(files, FileUtils
19714                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19715        Collections.addAll(files, FileUtils
19716                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19717        for (File file : files) {
19718            if (!file.isDirectory()) continue;
19719
19720            final int userId;
19721            final UserInfo info;
19722            try {
19723                userId = Integer.parseInt(file.getName());
19724                info = sUserManager.getUserInfo(userId);
19725            } catch (NumberFormatException e) {
19726                Slog.w(TAG, "Invalid user directory " + file);
19727                continue;
19728            }
19729
19730            boolean destroyUser = false;
19731            if (info == null) {
19732                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19733                        + " because no matching user was found");
19734                destroyUser = true;
19735            } else if (!mOnlyCore) {
19736                try {
19737                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19738                } catch (IOException e) {
19739                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19740                            + " because we failed to enforce serial number: " + e);
19741                    destroyUser = true;
19742                }
19743            }
19744
19745            if (destroyUser) {
19746                synchronized (mInstallLock) {
19747                    destroyUserDataLI(volumeUuid, userId,
19748                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19749                }
19750            }
19751        }
19752    }
19753
19754    private void assertPackageKnown(String volumeUuid, String packageName)
19755            throws PackageManagerException {
19756        synchronized (mPackages) {
19757            final PackageSetting ps = mSettings.mPackages.get(packageName);
19758            if (ps == null) {
19759                throw new PackageManagerException("Package " + packageName + " is unknown");
19760            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19761                throw new PackageManagerException(
19762                        "Package " + packageName + " found on unknown volume " + volumeUuid
19763                                + "; expected volume " + ps.volumeUuid);
19764            }
19765        }
19766    }
19767
19768    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19769            throws PackageManagerException {
19770        synchronized (mPackages) {
19771            final PackageSetting ps = mSettings.mPackages.get(packageName);
19772            if (ps == null) {
19773                throw new PackageManagerException("Package " + packageName + " is unknown");
19774            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19775                throw new PackageManagerException(
19776                        "Package " + packageName + " found on unknown volume " + volumeUuid
19777                                + "; expected volume " + ps.volumeUuid);
19778            } else if (!ps.getInstalled(userId)) {
19779                throw new PackageManagerException(
19780                        "Package " + packageName + " not installed for user " + userId);
19781            }
19782        }
19783    }
19784
19785    /**
19786     * Examine all apps present on given mounted volume, and destroy apps that
19787     * aren't expected, either due to uninstallation or reinstallation on
19788     * another volume.
19789     */
19790    private void reconcileApps(String volumeUuid) {
19791        final File[] files = FileUtils
19792                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19793        for (File file : files) {
19794            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19795                    && !PackageInstallerService.isStageName(file.getName());
19796            if (!isPackage) {
19797                // Ignore entries which are not packages
19798                continue;
19799            }
19800
19801            try {
19802                final PackageLite pkg = PackageParser.parsePackageLite(file,
19803                        PackageParser.PARSE_MUST_BE_APK);
19804                assertPackageKnown(volumeUuid, pkg.packageName);
19805
19806            } catch (PackageParserException | PackageManagerException e) {
19807                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19808                synchronized (mInstallLock) {
19809                    removeCodePathLI(file);
19810                }
19811            }
19812        }
19813    }
19814
19815    /**
19816     * Reconcile all app data for the given user.
19817     * <p>
19818     * Verifies that directories exist and that ownership and labeling is
19819     * correct for all installed apps on all mounted volumes.
19820     */
19821    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19822        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19823        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19824            final String volumeUuid = vol.getFsUuid();
19825            synchronized (mInstallLock) {
19826                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19827            }
19828        }
19829    }
19830
19831    /**
19832     * Reconcile all app data on given mounted volume.
19833     * <p>
19834     * Destroys app data that isn't expected, either due to uninstallation or
19835     * reinstallation on another volume.
19836     * <p>
19837     * Verifies that directories exist and that ownership and labeling is
19838     * correct for all installed apps.
19839     */
19840    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19841            boolean migrateAppData) {
19842        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19843                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19844
19845        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19846        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19847
19848        // First look for stale data that doesn't belong, and check if things
19849        // have changed since we did our last restorecon
19850        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19851            if (StorageManager.isFileEncryptedNativeOrEmulated()
19852                    && !StorageManager.isUserKeyUnlocked(userId)) {
19853                throw new RuntimeException(
19854                        "Yikes, someone asked us to reconcile CE storage while " + userId
19855                                + " was still locked; this would have caused massive data loss!");
19856            }
19857
19858            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19859            for (File file : files) {
19860                final String packageName = file.getName();
19861                try {
19862                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19863                } catch (PackageManagerException e) {
19864                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19865                    try {
19866                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19867                                StorageManager.FLAG_STORAGE_CE, 0);
19868                    } catch (InstallerException e2) {
19869                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19870                    }
19871                }
19872            }
19873        }
19874        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19875            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19876            for (File file : files) {
19877                final String packageName = file.getName();
19878                try {
19879                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19880                } catch (PackageManagerException e) {
19881                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19882                    try {
19883                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19884                                StorageManager.FLAG_STORAGE_DE, 0);
19885                    } catch (InstallerException e2) {
19886                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19887                    }
19888                }
19889            }
19890        }
19891
19892        // Ensure that data directories are ready to roll for all packages
19893        // installed for this volume and user
19894        final List<PackageSetting> packages;
19895        synchronized (mPackages) {
19896            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19897        }
19898        int preparedCount = 0;
19899        for (PackageSetting ps : packages) {
19900            final String packageName = ps.name;
19901            if (ps.pkg == null) {
19902                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19903                // TODO: might be due to legacy ASEC apps; we should circle back
19904                // and reconcile again once they're scanned
19905                continue;
19906            }
19907
19908            if (ps.getInstalled(userId)) {
19909                prepareAppDataLIF(ps.pkg, userId, flags);
19910
19911                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
19912                    // We may have just shuffled around app data directories, so
19913                    // prepare them one more time
19914                    prepareAppDataLIF(ps.pkg, userId, flags);
19915                }
19916
19917                preparedCount++;
19918            }
19919        }
19920
19921        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19922    }
19923
19924    /**
19925     * Prepare app data for the given app just after it was installed or
19926     * upgraded. This method carefully only touches users that it's installed
19927     * for, and it forces a restorecon to handle any seinfo changes.
19928     * <p>
19929     * Verifies that directories exist and that ownership and labeling is
19930     * correct for all installed apps. If there is an ownership mismatch, it
19931     * will try recovering system apps by wiping data; third-party app data is
19932     * left intact.
19933     * <p>
19934     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19935     */
19936    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19937        final PackageSetting ps;
19938        synchronized (mPackages) {
19939            ps = mSettings.mPackages.get(pkg.packageName);
19940            mSettings.writeKernelMappingLPr(ps);
19941        }
19942
19943        final UserManager um = mContext.getSystemService(UserManager.class);
19944        UserManagerInternal umInternal = getUserManagerInternal();
19945        for (UserInfo user : um.getUsers()) {
19946            final int flags;
19947            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19948                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19949            } else if (umInternal.isUserRunning(user.id)) {
19950                flags = StorageManager.FLAG_STORAGE_DE;
19951            } else {
19952                continue;
19953            }
19954
19955            if (ps.getInstalled(user.id)) {
19956                // TODO: when user data is locked, mark that we're still dirty
19957                prepareAppDataLIF(pkg, user.id, flags);
19958            }
19959        }
19960    }
19961
19962    /**
19963     * Prepare app data for the given app.
19964     * <p>
19965     * Verifies that directories exist and that ownership and labeling is
19966     * correct for all installed apps. If there is an ownership mismatch, this
19967     * will try recovering system apps by wiping data; third-party app data is
19968     * left intact.
19969     */
19970    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19971        if (pkg == null) {
19972            Slog.wtf(TAG, "Package was null!", new Throwable());
19973            return;
19974        }
19975        prepareAppDataLeafLIF(pkg, userId, flags);
19976        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19977        for (int i = 0; i < childCount; i++) {
19978            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19979        }
19980    }
19981
19982    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19983        if (DEBUG_APP_DATA) {
19984            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19985                    + Integer.toHexString(flags));
19986        }
19987
19988        final String volumeUuid = pkg.volumeUuid;
19989        final String packageName = pkg.packageName;
19990        final ApplicationInfo app = pkg.applicationInfo;
19991        final int appId = UserHandle.getAppId(app.uid);
19992
19993        Preconditions.checkNotNull(app.seinfo);
19994
19995        try {
19996            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19997                    appId, app.seinfo, app.targetSdkVersion);
19998        } catch (InstallerException e) {
19999            if (app.isSystemApp()) {
20000                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20001                        + ", but trying to recover: " + e);
20002                destroyAppDataLeafLIF(pkg, userId, flags);
20003                try {
20004                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20005                            appId, app.seinfo, app.targetSdkVersion);
20006                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20007                } catch (InstallerException e2) {
20008                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20009                }
20010            } else {
20011                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20012            }
20013        }
20014
20015        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20016            try {
20017                // CE storage is unlocked right now, so read out the inode and
20018                // remember for use later when it's locked
20019                // TODO: mark this structure as dirty so we persist it!
20020                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20021                        StorageManager.FLAG_STORAGE_CE);
20022                synchronized (mPackages) {
20023                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20024                    if (ps != null) {
20025                        ps.setCeDataInode(ceDataInode, userId);
20026                    }
20027                }
20028            } catch (InstallerException e) {
20029                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20030            }
20031        }
20032
20033        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20034    }
20035
20036    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20037        if (pkg == null) {
20038            Slog.wtf(TAG, "Package was null!", new Throwable());
20039            return;
20040        }
20041        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20042        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20043        for (int i = 0; i < childCount; i++) {
20044            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20045        }
20046    }
20047
20048    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20049        final String volumeUuid = pkg.volumeUuid;
20050        final String packageName = pkg.packageName;
20051        final ApplicationInfo app = pkg.applicationInfo;
20052
20053        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20054            // Create a native library symlink only if we have native libraries
20055            // and if the native libraries are 32 bit libraries. We do not provide
20056            // this symlink for 64 bit libraries.
20057            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20058                final String nativeLibPath = app.nativeLibraryDir;
20059                try {
20060                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20061                            nativeLibPath, userId);
20062                } catch (InstallerException e) {
20063                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20064                }
20065            }
20066        }
20067    }
20068
20069    /**
20070     * For system apps on non-FBE devices, this method migrates any existing
20071     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20072     * requested by the app.
20073     */
20074    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20075        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20076                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20077            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20078                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20079            try {
20080                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20081                        storageTarget);
20082            } catch (InstallerException e) {
20083                logCriticalInfo(Log.WARN,
20084                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20085            }
20086            return true;
20087        } else {
20088            return false;
20089        }
20090    }
20091
20092    public PackageFreezer freezePackage(String packageName, String killReason) {
20093        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20094    }
20095
20096    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20097        return new PackageFreezer(packageName, userId, killReason);
20098    }
20099
20100    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20101            String killReason) {
20102        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20103    }
20104
20105    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20106            String killReason) {
20107        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20108            return new PackageFreezer();
20109        } else {
20110            return freezePackage(packageName, userId, killReason);
20111        }
20112    }
20113
20114    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20115            String killReason) {
20116        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20117    }
20118
20119    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20120            String killReason) {
20121        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20122            return new PackageFreezer();
20123        } else {
20124            return freezePackage(packageName, userId, killReason);
20125        }
20126    }
20127
20128    /**
20129     * Class that freezes and kills the given package upon creation, and
20130     * unfreezes it upon closing. This is typically used when doing surgery on
20131     * app code/data to prevent the app from running while you're working.
20132     */
20133    private class PackageFreezer implements AutoCloseable {
20134        private final String mPackageName;
20135        private final PackageFreezer[] mChildren;
20136
20137        private final boolean mWeFroze;
20138
20139        private final AtomicBoolean mClosed = new AtomicBoolean();
20140        private final CloseGuard mCloseGuard = CloseGuard.get();
20141
20142        /**
20143         * Create and return a stub freezer that doesn't actually do anything,
20144         * typically used when someone requested
20145         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20146         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20147         */
20148        public PackageFreezer() {
20149            mPackageName = null;
20150            mChildren = null;
20151            mWeFroze = false;
20152            mCloseGuard.open("close");
20153        }
20154
20155        public PackageFreezer(String packageName, int userId, String killReason) {
20156            synchronized (mPackages) {
20157                mPackageName = packageName;
20158                mWeFroze = mFrozenPackages.add(mPackageName);
20159
20160                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20161                if (ps != null) {
20162                    killApplication(ps.name, ps.appId, userId, killReason);
20163                }
20164
20165                final PackageParser.Package p = mPackages.get(packageName);
20166                if (p != null && p.childPackages != null) {
20167                    final int N = p.childPackages.size();
20168                    mChildren = new PackageFreezer[N];
20169                    for (int i = 0; i < N; i++) {
20170                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20171                                userId, killReason);
20172                    }
20173                } else {
20174                    mChildren = null;
20175                }
20176            }
20177            mCloseGuard.open("close");
20178        }
20179
20180        @Override
20181        protected void finalize() throws Throwable {
20182            try {
20183                mCloseGuard.warnIfOpen();
20184                close();
20185            } finally {
20186                super.finalize();
20187            }
20188        }
20189
20190        @Override
20191        public void close() {
20192            mCloseGuard.close();
20193            if (mClosed.compareAndSet(false, true)) {
20194                synchronized (mPackages) {
20195                    if (mWeFroze) {
20196                        mFrozenPackages.remove(mPackageName);
20197                    }
20198
20199                    if (mChildren != null) {
20200                        for (PackageFreezer freezer : mChildren) {
20201                            freezer.close();
20202                        }
20203                    }
20204                }
20205            }
20206        }
20207    }
20208
20209    /**
20210     * Verify that given package is currently frozen.
20211     */
20212    private void checkPackageFrozen(String packageName) {
20213        synchronized (mPackages) {
20214            if (!mFrozenPackages.contains(packageName)) {
20215                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20216            }
20217        }
20218    }
20219
20220    @Override
20221    public int movePackage(final String packageName, final String volumeUuid) {
20222        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20223
20224        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20225        final int moveId = mNextMoveId.getAndIncrement();
20226        mHandler.post(new Runnable() {
20227            @Override
20228            public void run() {
20229                try {
20230                    movePackageInternal(packageName, volumeUuid, moveId, user);
20231                } catch (PackageManagerException e) {
20232                    Slog.w(TAG, "Failed to move " + packageName, e);
20233                    mMoveCallbacks.notifyStatusChanged(moveId,
20234                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20235                }
20236            }
20237        });
20238        return moveId;
20239    }
20240
20241    private void movePackageInternal(final String packageName, final String volumeUuid,
20242            final int moveId, UserHandle user) throws PackageManagerException {
20243        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20244        final PackageManager pm = mContext.getPackageManager();
20245
20246        final boolean currentAsec;
20247        final String currentVolumeUuid;
20248        final File codeFile;
20249        final String installerPackageName;
20250        final String packageAbiOverride;
20251        final int appId;
20252        final String seinfo;
20253        final String label;
20254        final int targetSdkVersion;
20255        final PackageFreezer freezer;
20256        final int[] installedUserIds;
20257
20258        // reader
20259        synchronized (mPackages) {
20260            final PackageParser.Package pkg = mPackages.get(packageName);
20261            final PackageSetting ps = mSettings.mPackages.get(packageName);
20262            if (pkg == null || ps == null) {
20263                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20264            }
20265
20266            if (pkg.applicationInfo.isSystemApp()) {
20267                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20268                        "Cannot move system application");
20269            }
20270
20271            if (pkg.applicationInfo.isExternalAsec()) {
20272                currentAsec = true;
20273                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20274            } else if (pkg.applicationInfo.isForwardLocked()) {
20275                currentAsec = true;
20276                currentVolumeUuid = "forward_locked";
20277            } else {
20278                currentAsec = false;
20279                currentVolumeUuid = ps.volumeUuid;
20280
20281                final File probe = new File(pkg.codePath);
20282                final File probeOat = new File(probe, "oat");
20283                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20284                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20285                            "Move only supported for modern cluster style installs");
20286                }
20287            }
20288
20289            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20290                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20291                        "Package already moved to " + volumeUuid);
20292            }
20293            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20294                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20295                        "Device admin cannot be moved");
20296            }
20297
20298            if (mFrozenPackages.contains(packageName)) {
20299                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20300                        "Failed to move already frozen package");
20301            }
20302
20303            codeFile = new File(pkg.codePath);
20304            installerPackageName = ps.installerPackageName;
20305            packageAbiOverride = ps.cpuAbiOverrideString;
20306            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20307            seinfo = pkg.applicationInfo.seinfo;
20308            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20309            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20310            freezer = freezePackage(packageName, "movePackageInternal");
20311            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20312        }
20313
20314        final Bundle extras = new Bundle();
20315        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20316        extras.putString(Intent.EXTRA_TITLE, label);
20317        mMoveCallbacks.notifyCreated(moveId, extras);
20318
20319        int installFlags;
20320        final boolean moveCompleteApp;
20321        final File measurePath;
20322
20323        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20324            installFlags = INSTALL_INTERNAL;
20325            moveCompleteApp = !currentAsec;
20326            measurePath = Environment.getDataAppDirectory(volumeUuid);
20327        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20328            installFlags = INSTALL_EXTERNAL;
20329            moveCompleteApp = false;
20330            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20331        } else {
20332            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20333            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20334                    || !volume.isMountedWritable()) {
20335                freezer.close();
20336                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20337                        "Move location not mounted private volume");
20338            }
20339
20340            Preconditions.checkState(!currentAsec);
20341
20342            installFlags = INSTALL_INTERNAL;
20343            moveCompleteApp = true;
20344            measurePath = Environment.getDataAppDirectory(volumeUuid);
20345        }
20346
20347        final PackageStats stats = new PackageStats(null, -1);
20348        synchronized (mInstaller) {
20349            for (int userId : installedUserIds) {
20350                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20351                    freezer.close();
20352                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20353                            "Failed to measure package size");
20354                }
20355            }
20356        }
20357
20358        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20359                + stats.dataSize);
20360
20361        final long startFreeBytes = measurePath.getFreeSpace();
20362        final long sizeBytes;
20363        if (moveCompleteApp) {
20364            sizeBytes = stats.codeSize + stats.dataSize;
20365        } else {
20366            sizeBytes = stats.codeSize;
20367        }
20368
20369        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20370            freezer.close();
20371            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20372                    "Not enough free space to move");
20373        }
20374
20375        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20376
20377        final CountDownLatch installedLatch = new CountDownLatch(1);
20378        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20379            @Override
20380            public void onUserActionRequired(Intent intent) throws RemoteException {
20381                throw new IllegalStateException();
20382            }
20383
20384            @Override
20385            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20386                    Bundle extras) throws RemoteException {
20387                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20388                        + PackageManager.installStatusToString(returnCode, msg));
20389
20390                installedLatch.countDown();
20391                freezer.close();
20392
20393                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20394                switch (status) {
20395                    case PackageInstaller.STATUS_SUCCESS:
20396                        mMoveCallbacks.notifyStatusChanged(moveId,
20397                                PackageManager.MOVE_SUCCEEDED);
20398                        break;
20399                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20400                        mMoveCallbacks.notifyStatusChanged(moveId,
20401                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20402                        break;
20403                    default:
20404                        mMoveCallbacks.notifyStatusChanged(moveId,
20405                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20406                        break;
20407                }
20408            }
20409        };
20410
20411        final MoveInfo move;
20412        if (moveCompleteApp) {
20413            // Kick off a thread to report progress estimates
20414            new Thread() {
20415                @Override
20416                public void run() {
20417                    while (true) {
20418                        try {
20419                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20420                                break;
20421                            }
20422                        } catch (InterruptedException ignored) {
20423                        }
20424
20425                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20426                        final int progress = 10 + (int) MathUtils.constrain(
20427                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20428                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20429                    }
20430                }
20431            }.start();
20432
20433            final String dataAppName = codeFile.getName();
20434            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20435                    dataAppName, appId, seinfo, targetSdkVersion);
20436        } else {
20437            move = null;
20438        }
20439
20440        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20441
20442        final Message msg = mHandler.obtainMessage(INIT_COPY);
20443        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20444        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20445                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20446                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20447        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20448        msg.obj = params;
20449
20450        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20451                System.identityHashCode(msg.obj));
20452        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20453                System.identityHashCode(msg.obj));
20454
20455        mHandler.sendMessage(msg);
20456    }
20457
20458    @Override
20459    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20461
20462        final int realMoveId = mNextMoveId.getAndIncrement();
20463        final Bundle extras = new Bundle();
20464        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20465        mMoveCallbacks.notifyCreated(realMoveId, extras);
20466
20467        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20468            @Override
20469            public void onCreated(int moveId, Bundle extras) {
20470                // Ignored
20471            }
20472
20473            @Override
20474            public void onStatusChanged(int moveId, int status, long estMillis) {
20475                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20476            }
20477        };
20478
20479        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20480        storage.setPrimaryStorageUuid(volumeUuid, callback);
20481        return realMoveId;
20482    }
20483
20484    @Override
20485    public int getMoveStatus(int moveId) {
20486        mContext.enforceCallingOrSelfPermission(
20487                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20488        return mMoveCallbacks.mLastStatus.get(moveId);
20489    }
20490
20491    @Override
20492    public void registerMoveCallback(IPackageMoveObserver callback) {
20493        mContext.enforceCallingOrSelfPermission(
20494                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20495        mMoveCallbacks.register(callback);
20496    }
20497
20498    @Override
20499    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20500        mContext.enforceCallingOrSelfPermission(
20501                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20502        mMoveCallbacks.unregister(callback);
20503    }
20504
20505    @Override
20506    public boolean setInstallLocation(int loc) {
20507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20508                null);
20509        if (getInstallLocation() == loc) {
20510            return true;
20511        }
20512        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20513                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20514            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20515                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20516            return true;
20517        }
20518        return false;
20519   }
20520
20521    @Override
20522    public int getInstallLocation() {
20523        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20524                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20525                PackageHelper.APP_INSTALL_AUTO);
20526    }
20527
20528    /** Called by UserManagerService */
20529    void cleanUpUser(UserManagerService userManager, int userHandle) {
20530        synchronized (mPackages) {
20531            mDirtyUsers.remove(userHandle);
20532            mUserNeedsBadging.delete(userHandle);
20533            mSettings.removeUserLPw(userHandle);
20534            mPendingBroadcasts.remove(userHandle);
20535            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20536            removeUnusedPackagesLPw(userManager, userHandle);
20537        }
20538    }
20539
20540    /**
20541     * We're removing userHandle and would like to remove any downloaded packages
20542     * that are no longer in use by any other user.
20543     * @param userHandle the user being removed
20544     */
20545    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20546        final boolean DEBUG_CLEAN_APKS = false;
20547        int [] users = userManager.getUserIds();
20548        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20549        while (psit.hasNext()) {
20550            PackageSetting ps = psit.next();
20551            if (ps.pkg == null) {
20552                continue;
20553            }
20554            final String packageName = ps.pkg.packageName;
20555            // Skip over if system app
20556            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20557                continue;
20558            }
20559            if (DEBUG_CLEAN_APKS) {
20560                Slog.i(TAG, "Checking package " + packageName);
20561            }
20562            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20563            if (keep) {
20564                if (DEBUG_CLEAN_APKS) {
20565                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20566                }
20567            } else {
20568                for (int i = 0; i < users.length; i++) {
20569                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20570                        keep = true;
20571                        if (DEBUG_CLEAN_APKS) {
20572                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20573                                    + users[i]);
20574                        }
20575                        break;
20576                    }
20577                }
20578            }
20579            if (!keep) {
20580                if (DEBUG_CLEAN_APKS) {
20581                    Slog.i(TAG, "  Removing package " + packageName);
20582                }
20583                mHandler.post(new Runnable() {
20584                    public void run() {
20585                        deletePackageX(packageName, userHandle, 0);
20586                    } //end run
20587                });
20588            }
20589        }
20590    }
20591
20592    /** Called by UserManagerService */
20593    void createNewUser(int userId) {
20594        synchronized (mInstallLock) {
20595            mSettings.createNewUserLI(this, mInstaller, userId);
20596        }
20597        synchronized (mPackages) {
20598            scheduleWritePackageRestrictionsLocked(userId);
20599            scheduleWritePackageListLocked(userId);
20600            applyFactoryDefaultBrowserLPw(userId);
20601            primeDomainVerificationsLPw(userId);
20602        }
20603    }
20604
20605    void onNewUserCreated(final int userId) {
20606        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20607        // If permission review for legacy apps is required, we represent
20608        // dagerous permissions for such apps as always granted runtime
20609        // permissions to keep per user flag state whether review is needed.
20610        // Hence, if a new user is added we have to propagate dangerous
20611        // permission grants for these legacy apps.
20612        if (mPermissionReviewRequired) {
20613            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20614                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20615        }
20616    }
20617
20618    @Override
20619    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20620        mContext.enforceCallingOrSelfPermission(
20621                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20622                "Only package verification agents can read the verifier device identity");
20623
20624        synchronized (mPackages) {
20625            return mSettings.getVerifierDeviceIdentityLPw();
20626        }
20627    }
20628
20629    @Override
20630    public void setPermissionEnforced(String permission, boolean enforced) {
20631        // TODO: Now that we no longer change GID for storage, this should to away.
20632        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20633                "setPermissionEnforced");
20634        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20635            synchronized (mPackages) {
20636                if (mSettings.mReadExternalStorageEnforced == null
20637                        || mSettings.mReadExternalStorageEnforced != enforced) {
20638                    mSettings.mReadExternalStorageEnforced = enforced;
20639                    mSettings.writeLPr();
20640                }
20641            }
20642            // kill any non-foreground processes so we restart them and
20643            // grant/revoke the GID.
20644            final IActivityManager am = ActivityManagerNative.getDefault();
20645            if (am != null) {
20646                final long token = Binder.clearCallingIdentity();
20647                try {
20648                    am.killProcessesBelowForeground("setPermissionEnforcement");
20649                } catch (RemoteException e) {
20650                } finally {
20651                    Binder.restoreCallingIdentity(token);
20652                }
20653            }
20654        } else {
20655            throw new IllegalArgumentException("No selective enforcement for " + permission);
20656        }
20657    }
20658
20659    @Override
20660    @Deprecated
20661    public boolean isPermissionEnforced(String permission) {
20662        return true;
20663    }
20664
20665    @Override
20666    public boolean isStorageLow() {
20667        final long token = Binder.clearCallingIdentity();
20668        try {
20669            final DeviceStorageMonitorInternal
20670                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20671            if (dsm != null) {
20672                return dsm.isMemoryLow();
20673            } else {
20674                return false;
20675            }
20676        } finally {
20677            Binder.restoreCallingIdentity(token);
20678        }
20679    }
20680
20681    @Override
20682    public IPackageInstaller getPackageInstaller() {
20683        return mInstallerService;
20684    }
20685
20686    private boolean userNeedsBadging(int userId) {
20687        int index = mUserNeedsBadging.indexOfKey(userId);
20688        if (index < 0) {
20689            final UserInfo userInfo;
20690            final long token = Binder.clearCallingIdentity();
20691            try {
20692                userInfo = sUserManager.getUserInfo(userId);
20693            } finally {
20694                Binder.restoreCallingIdentity(token);
20695            }
20696            final boolean b;
20697            if (userInfo != null && userInfo.isManagedProfile()) {
20698                b = true;
20699            } else {
20700                b = false;
20701            }
20702            mUserNeedsBadging.put(userId, b);
20703            return b;
20704        }
20705        return mUserNeedsBadging.valueAt(index);
20706    }
20707
20708    @Override
20709    public KeySet getKeySetByAlias(String packageName, String alias) {
20710        if (packageName == null || alias == null) {
20711            return null;
20712        }
20713        synchronized(mPackages) {
20714            final PackageParser.Package pkg = mPackages.get(packageName);
20715            if (pkg == null) {
20716                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20717                throw new IllegalArgumentException("Unknown package: " + packageName);
20718            }
20719            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20720            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20721        }
20722    }
20723
20724    @Override
20725    public KeySet getSigningKeySet(String packageName) {
20726        if (packageName == null) {
20727            return null;
20728        }
20729        synchronized(mPackages) {
20730            final PackageParser.Package pkg = mPackages.get(packageName);
20731            if (pkg == null) {
20732                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20733                throw new IllegalArgumentException("Unknown package: " + packageName);
20734            }
20735            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20736                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20737                throw new SecurityException("May not access signing KeySet of other apps.");
20738            }
20739            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20740            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20741        }
20742    }
20743
20744    @Override
20745    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20746        if (packageName == null || ks == null) {
20747            return false;
20748        }
20749        synchronized(mPackages) {
20750            final PackageParser.Package pkg = mPackages.get(packageName);
20751            if (pkg == null) {
20752                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20753                throw new IllegalArgumentException("Unknown package: " + packageName);
20754            }
20755            IBinder ksh = ks.getToken();
20756            if (ksh instanceof KeySetHandle) {
20757                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20758                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20759            }
20760            return false;
20761        }
20762    }
20763
20764    @Override
20765    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20766        if (packageName == null || ks == null) {
20767            return false;
20768        }
20769        synchronized(mPackages) {
20770            final PackageParser.Package pkg = mPackages.get(packageName);
20771            if (pkg == null) {
20772                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20773                throw new IllegalArgumentException("Unknown package: " + packageName);
20774            }
20775            IBinder ksh = ks.getToken();
20776            if (ksh instanceof KeySetHandle) {
20777                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20778                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20779            }
20780            return false;
20781        }
20782    }
20783
20784    private void deletePackageIfUnusedLPr(final String packageName) {
20785        PackageSetting ps = mSettings.mPackages.get(packageName);
20786        if (ps == null) {
20787            return;
20788        }
20789        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20790            // TODO Implement atomic delete if package is unused
20791            // It is currently possible that the package will be deleted even if it is installed
20792            // after this method returns.
20793            mHandler.post(new Runnable() {
20794                public void run() {
20795                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20796                }
20797            });
20798        }
20799    }
20800
20801    /**
20802     * Check and throw if the given before/after packages would be considered a
20803     * downgrade.
20804     */
20805    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20806            throws PackageManagerException {
20807        if (after.versionCode < before.mVersionCode) {
20808            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20809                    "Update version code " + after.versionCode + " is older than current "
20810                    + before.mVersionCode);
20811        } else if (after.versionCode == before.mVersionCode) {
20812            if (after.baseRevisionCode < before.baseRevisionCode) {
20813                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20814                        "Update base revision code " + after.baseRevisionCode
20815                        + " is older than current " + before.baseRevisionCode);
20816            }
20817
20818            if (!ArrayUtils.isEmpty(after.splitNames)) {
20819                for (int i = 0; i < after.splitNames.length; i++) {
20820                    final String splitName = after.splitNames[i];
20821                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20822                    if (j != -1) {
20823                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20824                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20825                                    "Update split " + splitName + " revision code "
20826                                    + after.splitRevisionCodes[i] + " is older than current "
20827                                    + before.splitRevisionCodes[j]);
20828                        }
20829                    }
20830                }
20831            }
20832        }
20833    }
20834
20835    private static class MoveCallbacks extends Handler {
20836        private static final int MSG_CREATED = 1;
20837        private static final int MSG_STATUS_CHANGED = 2;
20838
20839        private final RemoteCallbackList<IPackageMoveObserver>
20840                mCallbacks = new RemoteCallbackList<>();
20841
20842        private final SparseIntArray mLastStatus = new SparseIntArray();
20843
20844        public MoveCallbacks(Looper looper) {
20845            super(looper);
20846        }
20847
20848        public void register(IPackageMoveObserver callback) {
20849            mCallbacks.register(callback);
20850        }
20851
20852        public void unregister(IPackageMoveObserver callback) {
20853            mCallbacks.unregister(callback);
20854        }
20855
20856        @Override
20857        public void handleMessage(Message msg) {
20858            final SomeArgs args = (SomeArgs) msg.obj;
20859            final int n = mCallbacks.beginBroadcast();
20860            for (int i = 0; i < n; i++) {
20861                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20862                try {
20863                    invokeCallback(callback, msg.what, args);
20864                } catch (RemoteException ignored) {
20865                }
20866            }
20867            mCallbacks.finishBroadcast();
20868            args.recycle();
20869        }
20870
20871        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20872                throws RemoteException {
20873            switch (what) {
20874                case MSG_CREATED: {
20875                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20876                    break;
20877                }
20878                case MSG_STATUS_CHANGED: {
20879                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20880                    break;
20881                }
20882            }
20883        }
20884
20885        private void notifyCreated(int moveId, Bundle extras) {
20886            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20887
20888            final SomeArgs args = SomeArgs.obtain();
20889            args.argi1 = moveId;
20890            args.arg2 = extras;
20891            obtainMessage(MSG_CREATED, args).sendToTarget();
20892        }
20893
20894        private void notifyStatusChanged(int moveId, int status) {
20895            notifyStatusChanged(moveId, status, -1);
20896        }
20897
20898        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20899            Slog.v(TAG, "Move " + moveId + " status " + status);
20900
20901            final SomeArgs args = SomeArgs.obtain();
20902            args.argi1 = moveId;
20903            args.argi2 = status;
20904            args.arg3 = estMillis;
20905            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20906
20907            synchronized (mLastStatus) {
20908                mLastStatus.put(moveId, status);
20909            }
20910        }
20911    }
20912
20913    private final static class OnPermissionChangeListeners extends Handler {
20914        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20915
20916        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20917                new RemoteCallbackList<>();
20918
20919        public OnPermissionChangeListeners(Looper looper) {
20920            super(looper);
20921        }
20922
20923        @Override
20924        public void handleMessage(Message msg) {
20925            switch (msg.what) {
20926                case MSG_ON_PERMISSIONS_CHANGED: {
20927                    final int uid = msg.arg1;
20928                    handleOnPermissionsChanged(uid);
20929                } break;
20930            }
20931        }
20932
20933        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20934            mPermissionListeners.register(listener);
20935
20936        }
20937
20938        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20939            mPermissionListeners.unregister(listener);
20940        }
20941
20942        public void onPermissionsChanged(int uid) {
20943            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20944                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20945            }
20946        }
20947
20948        private void handleOnPermissionsChanged(int uid) {
20949            final int count = mPermissionListeners.beginBroadcast();
20950            try {
20951                for (int i = 0; i < count; i++) {
20952                    IOnPermissionsChangeListener callback = mPermissionListeners
20953                            .getBroadcastItem(i);
20954                    try {
20955                        callback.onPermissionsChanged(uid);
20956                    } catch (RemoteException e) {
20957                        Log.e(TAG, "Permission listener is dead", e);
20958                    }
20959                }
20960            } finally {
20961                mPermissionListeners.finishBroadcast();
20962            }
20963        }
20964    }
20965
20966    private class PackageManagerInternalImpl extends PackageManagerInternal {
20967        @Override
20968        public void setLocationPackagesProvider(PackagesProvider provider) {
20969            synchronized (mPackages) {
20970                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20971            }
20972        }
20973
20974        @Override
20975        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20976            synchronized (mPackages) {
20977                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20978            }
20979        }
20980
20981        @Override
20982        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20983            synchronized (mPackages) {
20984                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20985            }
20986        }
20987
20988        @Override
20989        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20990            synchronized (mPackages) {
20991                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20992            }
20993        }
20994
20995        @Override
20996        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20997            synchronized (mPackages) {
20998                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20999            }
21000        }
21001
21002        @Override
21003        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21004            synchronized (mPackages) {
21005                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21006            }
21007        }
21008
21009        @Override
21010        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21011            synchronized (mPackages) {
21012                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21013                        packageName, userId);
21014            }
21015        }
21016
21017        @Override
21018        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21019            synchronized (mPackages) {
21020                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21021                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21022                        packageName, userId);
21023            }
21024        }
21025
21026        @Override
21027        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21028            synchronized (mPackages) {
21029                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21030                        packageName, userId);
21031            }
21032        }
21033
21034        @Override
21035        public void setKeepUninstalledPackages(final List<String> packageList) {
21036            Preconditions.checkNotNull(packageList);
21037            List<String> removedFromList = null;
21038            synchronized (mPackages) {
21039                if (mKeepUninstalledPackages != null) {
21040                    final int packagesCount = mKeepUninstalledPackages.size();
21041                    for (int i = 0; i < packagesCount; i++) {
21042                        String oldPackage = mKeepUninstalledPackages.get(i);
21043                        if (packageList != null && packageList.contains(oldPackage)) {
21044                            continue;
21045                        }
21046                        if (removedFromList == null) {
21047                            removedFromList = new ArrayList<>();
21048                        }
21049                        removedFromList.add(oldPackage);
21050                    }
21051                }
21052                mKeepUninstalledPackages = new ArrayList<>(packageList);
21053                if (removedFromList != null) {
21054                    final int removedCount = removedFromList.size();
21055                    for (int i = 0; i < removedCount; i++) {
21056                        deletePackageIfUnusedLPr(removedFromList.get(i));
21057                    }
21058                }
21059            }
21060        }
21061
21062        @Override
21063        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21064            synchronized (mPackages) {
21065                // If we do not support permission review, done.
21066                if (!mPermissionReviewRequired) {
21067                    return false;
21068                }
21069
21070                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21071                if (packageSetting == null) {
21072                    return false;
21073                }
21074
21075                // Permission review applies only to apps not supporting the new permission model.
21076                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21077                    return false;
21078                }
21079
21080                // Legacy apps have the permission and get user consent on launch.
21081                PermissionsState permissionsState = packageSetting.getPermissionsState();
21082                return permissionsState.isPermissionReviewRequired(userId);
21083            }
21084        }
21085
21086        @Override
21087        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21088            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21089        }
21090
21091        @Override
21092        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21093                int userId) {
21094            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21095        }
21096
21097        @Override
21098        public void setDeviceAndProfileOwnerPackages(
21099                int deviceOwnerUserId, String deviceOwnerPackage,
21100                SparseArray<String> profileOwnerPackages) {
21101            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21102                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21103        }
21104
21105        @Override
21106        public boolean isPackageDataProtected(int userId, String packageName) {
21107            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21108        }
21109
21110        @Override
21111        public boolean wasPackageEverLaunched(String packageName, int userId) {
21112            synchronized (mPackages) {
21113                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21114            }
21115        }
21116    }
21117
21118    @Override
21119    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21120        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21121        synchronized (mPackages) {
21122            final long identity = Binder.clearCallingIdentity();
21123            try {
21124                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21125                        packageNames, userId);
21126            } finally {
21127                Binder.restoreCallingIdentity(identity);
21128            }
21129        }
21130    }
21131
21132    private static void enforceSystemOrPhoneCaller(String tag) {
21133        int callingUid = Binder.getCallingUid();
21134        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21135            throw new SecurityException(
21136                    "Cannot call " + tag + " from UID " + callingUid);
21137        }
21138    }
21139
21140    boolean isHistoricalPackageUsageAvailable() {
21141        return mPackageUsage.isHistoricalPackageUsageAvailable();
21142    }
21143
21144    /**
21145     * Return a <b>copy</b> of the collection of packages known to the package manager.
21146     * @return A copy of the values of mPackages.
21147     */
21148    Collection<PackageParser.Package> getPackages() {
21149        synchronized (mPackages) {
21150            return new ArrayList<>(mPackages.values());
21151        }
21152    }
21153
21154    /**
21155     * Logs process start information (including base APK hash) to the security log.
21156     * @hide
21157     */
21158    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21159            String apkFile, int pid) {
21160        if (!SecurityLog.isLoggingEnabled()) {
21161            return;
21162        }
21163        Bundle data = new Bundle();
21164        data.putLong("startTimestamp", System.currentTimeMillis());
21165        data.putString("processName", processName);
21166        data.putInt("uid", uid);
21167        data.putString("seinfo", seinfo);
21168        data.putString("apkFile", apkFile);
21169        data.putInt("pid", pid);
21170        Message msg = mProcessLoggingHandler.obtainMessage(
21171                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21172        msg.setData(data);
21173        mProcessLoggingHandler.sendMessage(msg);
21174    }
21175
21176    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21177        return mCompilerStats.getPackageStats(pkgName);
21178    }
21179
21180    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21181        return getOrCreateCompilerPackageStats(pkg.packageName);
21182    }
21183
21184    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21185        return mCompilerStats.getOrCreatePackageStats(pkgName);
21186    }
21187
21188    public void deleteCompilerPackageStats(String pkgName) {
21189        mCompilerStats.deletePackageStats(pkgName);
21190    }
21191}
21192