PackageManagerService.java revision c8cc38c8c56770dd3ff2a7e2fbb3267c6a9a14d0
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_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.INetworkPolicyManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.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.security.KeyStore;
200import android.security.SystemKeyStore;
201import android.system.ErrnoException;
202import android.system.Os;
203import android.text.TextUtils;
204import android.text.format.DateUtils;
205import android.util.ArrayMap;
206import android.util.ArraySet;
207import android.util.AtomicFile;
208import android.util.DisplayMetrics;
209import android.util.EventLog;
210import android.util.ExceptionUtils;
211import android.util.Log;
212import android.util.LogPrinter;
213import android.util.MathUtils;
214import android.util.PrintStreamPrinter;
215import android.util.Slog;
216import android.util.SparseArray;
217import android.util.SparseBooleanArray;
218import android.util.SparseIntArray;
219import android.util.Xml;
220import android.util.jar.StrictJarFile;
221import android.view.Display;
222
223import com.android.internal.R;
224import com.android.internal.annotations.GuardedBy;
225import com.android.internal.app.IMediaContainerService;
226import com.android.internal.app.ResolverActivity;
227import com.android.internal.content.NativeLibraryHelper;
228import com.android.internal.content.PackageHelper;
229import com.android.internal.os.IParcelFileDescriptorFactory;
230import com.android.internal.os.InstallerConnection.InstallerException;
231import com.android.internal.os.SomeArgs;
232import com.android.internal.os.Zygote;
233import com.android.internal.telephony.CarrierAppUtils;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.EventLogTags;
241import com.android.server.FgThread;
242import com.android.server.IntentResolver;
243import com.android.server.LocalServices;
244import com.android.server.ServiceThread;
245import com.android.server.SystemConfig;
246import com.android.server.Watchdog;
247import com.android.server.net.NetworkPolicyManagerInternal;
248import com.android.server.pm.PermissionsState.PermissionState;
249import com.android.server.pm.Settings.DatabaseVersion;
250import com.android.server.pm.Settings.VersionInfo;
251import com.android.server.storage.DeviceStorageMonitorInternal;
252
253import dalvik.system.CloseGuard;
254import dalvik.system.DexFile;
255import dalvik.system.VMRuntime;
256
257import libcore.io.IoUtils;
258import libcore.util.EmptyArray;
259
260import org.xmlpull.v1.XmlPullParser;
261import org.xmlpull.v1.XmlPullParserException;
262import org.xmlpull.v1.XmlSerializer;
263
264import java.io.BufferedInputStream;
265import java.io.BufferedOutputStream;
266import java.io.BufferedReader;
267import java.io.ByteArrayInputStream;
268import java.io.ByteArrayOutputStream;
269import java.io.File;
270import java.io.FileDescriptor;
271import java.io.FileInputStream;
272import java.io.FileNotFoundException;
273import java.io.FileOutputStream;
274import java.io.FileReader;
275import java.io.FilenameFilter;
276import java.io.IOException;
277import java.io.InputStream;
278import java.io.PrintWriter;
279import java.nio.charset.StandardCharsets;
280import java.security.DigestInputStream;
281import java.security.MessageDigest;
282import java.security.NoSuchAlgorithmException;
283import java.security.PublicKey;
284import java.security.cert.Certificate;
285import java.security.cert.CertificateEncodingException;
286import java.security.cert.CertificateException;
287import java.text.SimpleDateFormat;
288import java.util.ArrayList;
289import java.util.Arrays;
290import java.util.Collection;
291import java.util.Collections;
292import java.util.Comparator;
293import java.util.Date;
294import java.util.HashSet;
295import java.util.Iterator;
296import java.util.List;
297import java.util.Map;
298import java.util.Objects;
299import java.util.Set;
300import java.util.concurrent.CountDownLatch;
301import java.util.concurrent.TimeUnit;
302import java.util.concurrent.atomic.AtomicBoolean;
303import java.util.concurrent.atomic.AtomicInteger;
304import java.util.concurrent.atomic.AtomicLong;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = false;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    private static final boolean DISABLE_EPHEMERAL_APPS = true;
369
370    private static final int RADIO_UID = Process.PHONE_UID;
371    private static final int LOG_UID = Process.LOG_UID;
372    private static final int NFC_UID = Process.NFC_UID;
373    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
374    private static final int SHELL_UID = Process.SHELL_UID;
375
376    // Cap the size of permission trees that 3rd party apps can define
377    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
378
379    // Suffix used during package installation when copying/moving
380    // package apks to install directory.
381    private static final String INSTALL_PACKAGE_SUFFIX = "-";
382
383    static final int SCAN_NO_DEX = 1<<1;
384    static final int SCAN_FORCE_DEX = 1<<2;
385    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
386    static final int SCAN_NEW_INSTALL = 1<<4;
387    static final int SCAN_NO_PATHS = 1<<5;
388    static final int SCAN_UPDATE_TIME = 1<<6;
389    static final int SCAN_DEFER_DEX = 1<<7;
390    static final int SCAN_BOOTING = 1<<8;
391    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
392    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
393    static final int SCAN_REPLACING = 1<<11;
394    static final int SCAN_REQUIRE_KNOWN = 1<<12;
395    static final int SCAN_MOVE = 1<<13;
396    static final int SCAN_INITIAL = 1<<14;
397    static final int SCAN_CHECK_ONLY = 1<<15;
398    static final int SCAN_DONT_KILL_APP = 1<<17;
399    static final int SCAN_IGNORE_FROZEN = 1<<18;
400
401    static final int REMOVE_CHATTY = 1<<16;
402
403    private static final int[] EMPTY_INT_ARRAY = new int[0];
404
405    /**
406     * Timeout (in milliseconds) after which the watchdog should declare that
407     * our handler thread is wedged.  The usual default for such things is one
408     * minute but we sometimes do very lengthy I/O operations on this thread,
409     * such as installing multi-gigabyte applications, so ours needs to be longer.
410     */
411    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
412
413    /**
414     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
415     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
416     * settings entry if available, otherwise we use the hardcoded default.  If it's been
417     * more than this long since the last fstrim, we force one during the boot sequence.
418     *
419     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
420     * one gets run at the next available charging+idle time.  This final mandatory
421     * no-fstrim check kicks in only of the other scheduling criteria is never met.
422     */
423    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
424
425    /**
426     * Whether verification is enabled by default.
427     */
428    private static final boolean DEFAULT_VERIFY_ENABLE = true;
429
430    /**
431     * The default maximum time to wait for the verification agent to return in
432     * milliseconds.
433     */
434    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
435
436    /**
437     * The default response for package verification timeout.
438     *
439     * This can be either PackageManager.VERIFICATION_ALLOW or
440     * PackageManager.VERIFICATION_REJECT.
441     */
442    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
443
444    static final String PLATFORM_PACKAGE_NAME = "android";
445
446    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
447
448    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
449            DEFAULT_CONTAINER_PACKAGE,
450            "com.android.defcontainer.DefaultContainerService");
451
452    private static final String KILL_APP_REASON_GIDS_CHANGED =
453            "permission grant or revoke changed gids";
454
455    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
456            "permissions revoked";
457
458    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    /** Permission grant: not grant the permission. */
463    private static final int GRANT_DENIED = 1;
464
465    /** Permission grant: grant the permission as an install permission. */
466    private static final int GRANT_INSTALL = 2;
467
468    /** Permission grant: grant the permission as a runtime one. */
469    private static final int GRANT_RUNTIME = 3;
470
471    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
472    private static final int GRANT_UPGRADE = 4;
473
474    /** Canonical intent used to identify what counts as a "web browser" app */
475    private static final Intent sBrowserIntent;
476    static {
477        sBrowserIntent = new Intent();
478        sBrowserIntent.setAction(Intent.ACTION_VIEW);
479        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
480        sBrowserIntent.setData(Uri.parse("http:"));
481    }
482
483    /**
484     * The set of all protected actions [i.e. those actions for which a high priority
485     * intent filter is disallowed].
486     */
487    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
488    static {
489        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
490        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
491        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
492        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
493    }
494
495    // Compilation reasons.
496    public static final int REASON_FIRST_BOOT = 0;
497    public static final int REASON_BOOT = 1;
498    public static final int REASON_INSTALL = 2;
499    public static final int REASON_BACKGROUND_DEXOPT = 3;
500    public static final int REASON_AB_OTA = 4;
501    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
502    public static final int REASON_SHARED_APK = 6;
503    public static final int REASON_FORCED_DEXOPT = 7;
504
505    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
506
507    /** Special library name that skips shared libraries check during compilation. */
508    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
509
510    final ServiceThread mHandlerThread;
511
512    final PackageHandler mHandler;
513
514    private final ProcessLoggingHandler mProcessLoggingHandler;
515
516    /**
517     * Messages for {@link #mHandler} that need to wait for system ready before
518     * being dispatched.
519     */
520    private ArrayList<Message> mPostSystemReadyMessages;
521
522    final int mSdkVersion = Build.VERSION.SDK_INT;
523
524    final Context mContext;
525    final boolean mFactoryTest;
526    final boolean mOnlyCore;
527    final DisplayMetrics mMetrics;
528    final int mDefParseFlags;
529    final String[] mSeparateProcesses;
530    final boolean mIsUpgrade;
531    final boolean mIsPreNUpgrade;
532
533    /** The location for ASEC container files on internal storage. */
534    final String mAsecInternalPath;
535
536    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
537    // LOCK HELD.  Can be called with mInstallLock held.
538    @GuardedBy("mInstallLock")
539    final Installer mInstaller;
540
541    /** Directory where installed third-party apps stored */
542    final File mAppInstallDir;
543    final File mEphemeralInstallDir;
544
545    /**
546     * Directory to which applications installed internally have their
547     * 32 bit native libraries copied.
548     */
549    private File mAppLib32InstallDir;
550
551    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
552    // apps.
553    final File mDrmAppPrivateInstallDir;
554
555    // ----------------------------------------------------------------
556
557    // Lock for state used when installing and doing other long running
558    // operations.  Methods that must be called with this lock held have
559    // the suffix "LI".
560    final Object mInstallLock = new Object();
561
562    // ----------------------------------------------------------------
563
564    // Keys are String (package name), values are Package.  This also serves
565    // as the lock for the global state.  Methods that must be called with
566    // this lock held have the prefix "LP".
567    @GuardedBy("mPackages")
568    final ArrayMap<String, PackageParser.Package> mPackages =
569            new ArrayMap<String, PackageParser.Package>();
570
571    final ArrayMap<String, Set<String>> mKnownCodebase =
572            new ArrayMap<String, Set<String>>();
573
574    // Tracks available target package names -> overlay package paths.
575    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
576        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
577
578    /**
579     * Tracks new system packages [received in an OTA] that we expect to
580     * find updated user-installed versions. Keys are package name, values
581     * are package location.
582     */
583    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
584    /**
585     * Tracks high priority intent filters for protected actions. During boot, certain
586     * filter actions are protected and should never be allowed to have a high priority
587     * intent filter for them. However, there is one, and only one exception -- the
588     * setup wizard. It must be able to define a high priority intent filter for these
589     * actions to ensure there are no escapes from the wizard. We need to delay processing
590     * of these during boot as we need to look at all of the system packages in order
591     * to know which component is the setup wizard.
592     */
593    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
594    /**
595     * Whether or not processing protected filters should be deferred.
596     */
597    private boolean mDeferProtectedFilters = true;
598
599    /**
600     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
601     */
602    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
603    /**
604     * Whether or not system app permissions should be promoted from install to runtime.
605     */
606    boolean mPromoteSystemApps;
607
608    @GuardedBy("mPackages")
609    final Settings mSettings;
610
611    /**
612     * Set of package names that are currently "frozen", which means active
613     * surgery is being done on the code/data for that package. The platform
614     * will refuse to launch frozen packages to avoid race conditions.
615     *
616     * @see PackageFreezer
617     */
618    @GuardedBy("mPackages")
619    final ArraySet<String> mFrozenPackages = new ArraySet<>();
620
621    boolean mRestoredSettings;
622
623    // System configuration read by SystemConfig.
624    final int[] mGlobalGids;
625    final SparseArray<ArraySet<String>> mSystemPermissions;
626    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
627
628    // If mac_permissions.xml was found for seinfo labeling.
629    boolean mFoundPolicyFile;
630
631    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
632
633    public static final class SharedLibraryEntry {
634        public final String path;
635        public final String apk;
636
637        SharedLibraryEntry(String _path, String _apk) {
638            path = _path;
639            apk = _apk;
640        }
641    }
642
643    // Currently known shared libraries.
644    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
645            new ArrayMap<String, SharedLibraryEntry>();
646
647    // All available activities, for your resolving pleasure.
648    final ActivityIntentResolver mActivities =
649            new ActivityIntentResolver();
650
651    // All available receivers, for your resolving pleasure.
652    final ActivityIntentResolver mReceivers =
653            new ActivityIntentResolver();
654
655    // All available services, for your resolving pleasure.
656    final ServiceIntentResolver mServices = new ServiceIntentResolver();
657
658    // All available providers, for your resolving pleasure.
659    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
660
661    // Mapping from provider base names (first directory in content URI codePath)
662    // to the provider information.
663    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
664            new ArrayMap<String, PackageParser.Provider>();
665
666    // Mapping from instrumentation class names to info about them.
667    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
668            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
669
670    // Mapping from permission names to info about them.
671    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
672            new ArrayMap<String, PackageParser.PermissionGroup>();
673
674    // Packages whose data we have transfered into another package, thus
675    // should no longer exist.
676    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
677
678    // Broadcast actions that are only available to the system.
679    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
680
681    /** List of packages waiting for verification. */
682    final SparseArray<PackageVerificationState> mPendingVerification
683            = new SparseArray<PackageVerificationState>();
684
685    /** Set of packages associated with each app op permission. */
686    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
687
688    final PackageInstallerService mInstallerService;
689
690    private final PackageDexOptimizer mPackageDexOptimizer;
691
692    private AtomicInteger mNextMoveId = new AtomicInteger();
693    private final MoveCallbacks mMoveCallbacks;
694
695    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
696
697    // Cache of users who need badging.
698    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
699
700    /** Token for keys in mPendingVerification. */
701    private int mPendingVerificationToken = 0;
702
703    volatile boolean mSystemReady;
704    volatile boolean mSafeMode;
705    volatile boolean mHasSystemUidErrors;
706
707    ApplicationInfo mAndroidApplication;
708    final ActivityInfo mResolveActivity = new ActivityInfo();
709    final ResolveInfo mResolveInfo = new ResolveInfo();
710    ComponentName mResolveComponentName;
711    PackageParser.Package mPlatformPackage;
712    ComponentName mCustomResolverComponentName;
713
714    boolean mResolverReplaced = false;
715
716    private final @Nullable ComponentName mIntentFilterVerifierComponent;
717    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
718
719    private int mIntentFilterVerificationToken = 0;
720
721    /** Component that knows whether or not an ephemeral application exists */
722    final ComponentName mEphemeralResolverComponent;
723    /** The service connection to the ephemeral resolver */
724    final EphemeralResolverConnection mEphemeralResolverConnection;
725
726    /** Component used to install ephemeral applications */
727    final ComponentName mEphemeralInstallerComponent;
728    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
729    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
730
731    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
732            = new SparseArray<IntentFilterVerificationState>();
733
734    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
735            new DefaultPermissionGrantPolicy(this);
736
737    // List of packages names to keep cached, even if they are uninstalled for all users
738    private List<String> mKeepUninstalledPackages;
739
740    private static class IFVerificationParams {
741        PackageParser.Package pkg;
742        boolean replacing;
743        int userId;
744        int verifierUid;
745
746        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
747                int _userId, int _verifierUid) {
748            pkg = _pkg;
749            replacing = _replacing;
750            userId = _userId;
751            replacing = _replacing;
752            verifierUid = _verifierUid;
753        }
754    }
755
756    private interface IntentFilterVerifier<T extends IntentFilter> {
757        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
758                                               T filter, String packageName);
759        void startVerifications(int userId);
760        void receiveVerificationResponse(int verificationId);
761    }
762
763    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
764        private Context mContext;
765        private ComponentName mIntentFilterVerifierComponent;
766        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
767
768        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
769            mContext = context;
770            mIntentFilterVerifierComponent = verifierComponent;
771        }
772
773        private String getDefaultScheme() {
774            return IntentFilter.SCHEME_HTTPS;
775        }
776
777        @Override
778        public void startVerifications(int userId) {
779            // Launch verifications requests
780            int count = mCurrentIntentFilterVerifications.size();
781            for (int n=0; n<count; n++) {
782                int verificationId = mCurrentIntentFilterVerifications.get(n);
783                final IntentFilterVerificationState ivs =
784                        mIntentFilterVerificationStates.get(verificationId);
785
786                String packageName = ivs.getPackageName();
787
788                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
789                final int filterCount = filters.size();
790                ArraySet<String> domainsSet = new ArraySet<>();
791                for (int m=0; m<filterCount; m++) {
792                    PackageParser.ActivityIntentInfo filter = filters.get(m);
793                    domainsSet.addAll(filter.getHostsList());
794                }
795                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
796                synchronized (mPackages) {
797                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
798                            packageName, domainsList) != null) {
799                        scheduleWriteSettingsLocked();
800                    }
801                }
802                sendVerificationRequest(userId, verificationId, ivs);
803            }
804            mCurrentIntentFilterVerifications.clear();
805        }
806
807        private void sendVerificationRequest(int userId, int verificationId,
808                IntentFilterVerificationState ivs) {
809
810            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
811            verificationIntent.putExtra(
812                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
813                    verificationId);
814            verificationIntent.putExtra(
815                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
816                    getDefaultScheme());
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
819                    ivs.getHostsString());
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
822                    ivs.getPackageName());
823            verificationIntent.setComponent(mIntentFilterVerifierComponent);
824            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
825
826            UserHandle user = new UserHandle(userId);
827            mContext.sendBroadcastAsUser(verificationIntent, user);
828            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
829                    "Sending IntentFilter verification broadcast");
830        }
831
832        public void receiveVerificationResponse(int verificationId) {
833            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
834
835            final boolean verified = ivs.isVerified();
836
837            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
838            final int count = filters.size();
839            if (DEBUG_DOMAIN_VERIFICATION) {
840                Slog.i(TAG, "Received verification response " + verificationId
841                        + " for " + count + " filters, verified=" + verified);
842            }
843            for (int n=0; n<count; n++) {
844                PackageParser.ActivityIntentInfo filter = filters.get(n);
845                filter.setVerified(verified);
846
847                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
848                        + " verified with result:" + verified + " and hosts:"
849                        + ivs.getHostsString());
850            }
851
852            mIntentFilterVerificationStates.remove(verificationId);
853
854            final String packageName = ivs.getPackageName();
855            IntentFilterVerificationInfo ivi = null;
856
857            synchronized (mPackages) {
858                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
859            }
860            if (ivi == null) {
861                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
862                        + verificationId + " packageName:" + packageName);
863                return;
864            }
865            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
866                    "Updating IntentFilterVerificationInfo for package " + packageName
867                            +" verificationId:" + verificationId);
868
869            synchronized (mPackages) {
870                if (verified) {
871                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
872                } else {
873                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
874                }
875                scheduleWriteSettingsLocked();
876
877                final int userId = ivs.getUserId();
878                if (userId != UserHandle.USER_ALL) {
879                    final int userStatus =
880                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
881
882                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
883                    boolean needUpdate = false;
884
885                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
886                    // already been set by the User thru the Disambiguation dialog
887                    switch (userStatus) {
888                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
889                            if (verified) {
890                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
891                            } else {
892                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
893                            }
894                            needUpdate = true;
895                            break;
896
897                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
898                            if (verified) {
899                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
900                                needUpdate = true;
901                            }
902                            break;
903
904                        default:
905                            // Nothing to do
906                    }
907
908                    if (needUpdate) {
909                        mSettings.updateIntentFilterVerificationStatusLPw(
910                                packageName, updatedStatus, userId);
911                        scheduleWritePackageRestrictionsLocked(userId);
912                    }
913                }
914            }
915        }
916
917        @Override
918        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
919                    ActivityIntentInfo filter, String packageName) {
920            if (!hasValidDomains(filter)) {
921                return false;
922            }
923            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
924            if (ivs == null) {
925                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
926                        packageName);
927            }
928            if (DEBUG_DOMAIN_VERIFICATION) {
929                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
930            }
931            ivs.addFilter(filter);
932            return true;
933        }
934
935        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
936                int userId, int verificationId, String packageName) {
937            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
938                    verifierUid, userId, packageName);
939            ivs.setPendingState();
940            synchronized (mPackages) {
941                mIntentFilterVerificationStates.append(verificationId, ivs);
942                mCurrentIntentFilterVerifications.add(verificationId);
943            }
944            return ivs;
945        }
946    }
947
948    private static boolean hasValidDomains(ActivityIntentInfo filter) {
949        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
950                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
951                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
952    }
953
954    // Set of pending broadcasts for aggregating enable/disable of components.
955    static class PendingPackageBroadcasts {
956        // for each user id, a map of <package name -> components within that package>
957        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
958
959        public PendingPackageBroadcasts() {
960            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
961        }
962
963        public ArrayList<String> get(int userId, String packageName) {
964            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
965            return packages.get(packageName);
966        }
967
968        public void put(int userId, String packageName, ArrayList<String> components) {
969            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
970            packages.put(packageName, components);
971        }
972
973        public void remove(int userId, String packageName) {
974            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
975            if (packages != null) {
976                packages.remove(packageName);
977            }
978        }
979
980        public void remove(int userId) {
981            mUidMap.remove(userId);
982        }
983
984        public int userIdCount() {
985            return mUidMap.size();
986        }
987
988        public int userIdAt(int n) {
989            return mUidMap.keyAt(n);
990        }
991
992        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
993            return mUidMap.get(userId);
994        }
995
996        public int size() {
997            // total number of pending broadcast entries across all userIds
998            int num = 0;
999            for (int i = 0; i< mUidMap.size(); i++) {
1000                num += mUidMap.valueAt(i).size();
1001            }
1002            return num;
1003        }
1004
1005        public void clear() {
1006            mUidMap.clear();
1007        }
1008
1009        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1010            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1011            if (map == null) {
1012                map = new ArrayMap<String, ArrayList<String>>();
1013                mUidMap.put(userId, map);
1014            }
1015            return map;
1016        }
1017    }
1018    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1019
1020    // Service Connection to remote media container service to copy
1021    // package uri's from external media onto secure containers
1022    // or internal storage.
1023    private IMediaContainerService mContainerService = null;
1024
1025    static final int SEND_PENDING_BROADCAST = 1;
1026    static final int MCS_BOUND = 3;
1027    static final int END_COPY = 4;
1028    static final int INIT_COPY = 5;
1029    static final int MCS_UNBIND = 6;
1030    static final int START_CLEANING_PACKAGE = 7;
1031    static final int FIND_INSTALL_LOC = 8;
1032    static final int POST_INSTALL = 9;
1033    static final int MCS_RECONNECT = 10;
1034    static final int MCS_GIVE_UP = 11;
1035    static final int UPDATED_MEDIA_STATUS = 12;
1036    static final int WRITE_SETTINGS = 13;
1037    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1038    static final int PACKAGE_VERIFIED = 15;
1039    static final int CHECK_PENDING_VERIFICATION = 16;
1040    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1041    static final int INTENT_FILTER_VERIFIED = 18;
1042
1043    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1044
1045    // Delay time in millisecs
1046    static final int BROADCAST_DELAY = 10 * 1000;
1047
1048    static UserManagerService sUserManager;
1049
1050    // Stores a list of users whose package restrictions file needs to be updated
1051    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1052
1053    final private DefaultContainerConnection mDefContainerConn =
1054            new DefaultContainerConnection();
1055    class DefaultContainerConnection implements ServiceConnection {
1056        public void onServiceConnected(ComponentName name, IBinder service) {
1057            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1058            IMediaContainerService imcs =
1059                IMediaContainerService.Stub.asInterface(service);
1060            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1061        }
1062
1063        public void onServiceDisconnected(ComponentName name) {
1064            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1065        }
1066    }
1067
1068    // Recordkeeping of restore-after-install operations that are currently in flight
1069    // between the Package Manager and the Backup Manager
1070    static class PostInstallData {
1071        public InstallArgs args;
1072        public PackageInstalledInfo res;
1073
1074        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1075            args = _a;
1076            res = _r;
1077        }
1078    }
1079
1080    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1081    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1082
1083    // XML tags for backup/restore of various bits of state
1084    private static final String TAG_PREFERRED_BACKUP = "pa";
1085    private static final String TAG_DEFAULT_APPS = "da";
1086    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1087
1088    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1089    private static final String TAG_ALL_GRANTS = "rt-grants";
1090    private static final String TAG_GRANT = "grant";
1091    private static final String ATTR_PACKAGE_NAME = "pkg";
1092
1093    private static final String TAG_PERMISSION = "perm";
1094    private static final String ATTR_PERMISSION_NAME = "name";
1095    private static final String ATTR_IS_GRANTED = "g";
1096    private static final String ATTR_USER_SET = "set";
1097    private static final String ATTR_USER_FIXED = "fixed";
1098    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1099
1100    // System/policy permission grants are not backed up
1101    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1102            FLAG_PERMISSION_POLICY_FIXED
1103            | FLAG_PERMISSION_SYSTEM_FIXED
1104            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1105
1106    // And we back up these user-adjusted states
1107    private static final int USER_RUNTIME_GRANT_MASK =
1108            FLAG_PERMISSION_USER_SET
1109            | FLAG_PERMISSION_USER_FIXED
1110            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1111
1112    final @Nullable String mRequiredVerifierPackage;
1113    final @NonNull String mRequiredInstallerPackage;
1114    final @Nullable String mSetupWizardPackage;
1115    final @NonNull String mServicesSystemSharedLibraryPackageName;
1116    final @NonNull String mSharedSystemSharedLibraryPackageName;
1117
1118    private final PackageUsage mPackageUsage = new PackageUsage();
1119
1120    private class PackageUsage {
1121        private static final int WRITE_INTERVAL
1122            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1123
1124        private final Object mFileLock = new Object();
1125        private final AtomicLong mLastWritten = new AtomicLong(0);
1126        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1127
1128        private boolean mIsHistoricalPackageUsageAvailable = true;
1129
1130        boolean isHistoricalPackageUsageAvailable() {
1131            return mIsHistoricalPackageUsageAvailable;
1132        }
1133
1134        void write(boolean force) {
1135            if (force) {
1136                writeInternal();
1137                return;
1138            }
1139            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1140                && !DEBUG_DEXOPT) {
1141                return;
1142            }
1143            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1144                new Thread("PackageUsage_DiskWriter") {
1145                    @Override
1146                    public void run() {
1147                        try {
1148                            writeInternal();
1149                        } finally {
1150                            mBackgroundWriteRunning.set(false);
1151                        }
1152                    }
1153                }.start();
1154            }
1155        }
1156
1157        private void writeInternal() {
1158            synchronized (mPackages) {
1159                synchronized (mFileLock) {
1160                    AtomicFile file = getFile();
1161                    FileOutputStream f = null;
1162                    try {
1163                        f = file.startWrite();
1164                        BufferedOutputStream out = new BufferedOutputStream(f);
1165                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1166                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1167                        StringBuilder sb = new StringBuilder();
1168
1169                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1170                        sb.append('\n');
1171                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1172
1173                        for (PackageParser.Package pkg : mPackages.values()) {
1174                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1175                                continue;
1176                            }
1177                            sb.setLength(0);
1178                            sb.append(pkg.packageName);
1179                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1180                                sb.append(' ');
1181                                sb.append(usageTimeInMillis);
1182                            }
1183                            sb.append('\n');
1184                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1185                        }
1186                        out.flush();
1187                        file.finishWrite(f);
1188                    } catch (IOException e) {
1189                        if (f != null) {
1190                            file.failWrite(f);
1191                        }
1192                        Log.e(TAG, "Failed to write package usage times", e);
1193                    }
1194                }
1195            }
1196            mLastWritten.set(SystemClock.elapsedRealtime());
1197        }
1198
1199        void readLP() {
1200            synchronized (mFileLock) {
1201                AtomicFile file = getFile();
1202                BufferedInputStream in = null;
1203                try {
1204                    in = new BufferedInputStream(file.openRead());
1205                    StringBuffer sb = new StringBuffer();
1206
1207                    String firstLine = readLine(in, sb);
1208                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1209                        readVersion1LP(in, sb);
1210                    } else {
1211                        readVersion0LP(in, sb, firstLine);
1212                    }
1213                } catch (FileNotFoundException expected) {
1214                    mIsHistoricalPackageUsageAvailable = false;
1215                } catch (IOException e) {
1216                    Log.w(TAG, "Failed to read package usage times", e);
1217                } finally {
1218                    IoUtils.closeQuietly(in);
1219                }
1220            }
1221            mLastWritten.set(SystemClock.elapsedRealtime());
1222        }
1223
1224        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1225                throws IOException {
1226            // Initial version of the file had no version number and stored one
1227            // package-timestamp pair per line.
1228            // Note that the first line has already been read from the InputStream.
1229            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1230                String[] tokens = line.split(" ");
1231                if (tokens.length != 2) {
1232                    throw new IOException("Failed to parse " + line +
1233                            " as package-timestamp pair.");
1234                }
1235
1236                String packageName = tokens[0];
1237                PackageParser.Package pkg = mPackages.get(packageName);
1238                if (pkg == null) {
1239                    continue;
1240                }
1241
1242                long timestamp = parseAsLong(tokens[1]);
1243                for (int reason = 0;
1244                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1245                        reason++) {
1246                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1247                }
1248            }
1249        }
1250
1251        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1252            // Version 1 of the file started with the corresponding version
1253            // number and then stored a package name and eight timestamps per line.
1254            String line;
1255            while ((line = readLine(in, sb)) != null) {
1256                String[] tokens = line.split(" ");
1257                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1258                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1259                }
1260
1261                String packageName = tokens[0];
1262                PackageParser.Package pkg = mPackages.get(packageName);
1263                if (pkg == null) {
1264                    continue;
1265                }
1266
1267                for (int reason = 0;
1268                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1269                        reason++) {
1270                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1271                }
1272            }
1273        }
1274
1275        private long parseAsLong(String token) throws IOException {
1276            try {
1277                return Long.parseLong(token);
1278            } catch (NumberFormatException e) {
1279                throw new IOException("Failed to parse " + token + " as a long.", e);
1280            }
1281        }
1282
1283        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1284            return readToken(in, sb, '\n');
1285        }
1286
1287        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1288                throws IOException {
1289            sb.setLength(0);
1290            while (true) {
1291                int ch = in.read();
1292                if (ch == -1) {
1293                    if (sb.length() == 0) {
1294                        return null;
1295                    }
1296                    throw new IOException("Unexpected EOF");
1297                }
1298                if (ch == endOfToken) {
1299                    return sb.toString();
1300                }
1301                sb.append((char)ch);
1302            }
1303        }
1304
1305        private AtomicFile getFile() {
1306            File dataDir = Environment.getDataDirectory();
1307            File systemDir = new File(dataDir, "system");
1308            File fname = new File(systemDir, "package-usage.list");
1309            return new AtomicFile(fname);
1310        }
1311
1312        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1313        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1314    }
1315
1316    class PackageHandler extends Handler {
1317        private boolean mBound = false;
1318        final ArrayList<HandlerParams> mPendingInstalls =
1319            new ArrayList<HandlerParams>();
1320
1321        private boolean connectToService() {
1322            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1323                    " DefaultContainerService");
1324            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1325            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1326            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1327                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1328                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1329                mBound = true;
1330                return true;
1331            }
1332            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333            return false;
1334        }
1335
1336        private void disconnectService() {
1337            mContainerService = null;
1338            mBound = false;
1339            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340            mContext.unbindService(mDefContainerConn);
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1342        }
1343
1344        PackageHandler(Looper looper) {
1345            super(looper);
1346        }
1347
1348        public void handleMessage(Message msg) {
1349            try {
1350                doHandleMessage(msg);
1351            } finally {
1352                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353            }
1354        }
1355
1356        void doHandleMessage(Message msg) {
1357            switch (msg.what) {
1358                case INIT_COPY: {
1359                    HandlerParams params = (HandlerParams) msg.obj;
1360                    int idx = mPendingInstalls.size();
1361                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1362                    // If a bind was already initiated we dont really
1363                    // need to do anything. The pending install
1364                    // will be processed later on.
1365                    if (!mBound) {
1366                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1367                                System.identityHashCode(mHandler));
1368                        // If this is the only one pending we might
1369                        // have to bind to the service again.
1370                        if (!connectToService()) {
1371                            Slog.e(TAG, "Failed to bind to media container service");
1372                            params.serviceError();
1373                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1374                                    System.identityHashCode(mHandler));
1375                            if (params.traceMethod != null) {
1376                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1377                                        params.traceCookie);
1378                            }
1379                            return;
1380                        } else {
1381                            // Once we bind to the service, the first
1382                            // pending request will be processed.
1383                            mPendingInstalls.add(idx, params);
1384                        }
1385                    } else {
1386                        mPendingInstalls.add(idx, params);
1387                        // Already bound to the service. Just make
1388                        // sure we trigger off processing the first request.
1389                        if (idx == 0) {
1390                            mHandler.sendEmptyMessage(MCS_BOUND);
1391                        }
1392                    }
1393                    break;
1394                }
1395                case MCS_BOUND: {
1396                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1397                    if (msg.obj != null) {
1398                        mContainerService = (IMediaContainerService) msg.obj;
1399                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1400                                System.identityHashCode(mHandler));
1401                    }
1402                    if (mContainerService == null) {
1403                        if (!mBound) {
1404                            // Something seriously wrong since we are not bound and we are not
1405                            // waiting for connection. Bail out.
1406                            Slog.e(TAG, "Cannot bind to media container service");
1407                            for (HandlerParams params : mPendingInstalls) {
1408                                // Indicate service bind error
1409                                params.serviceError();
1410                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1411                                        System.identityHashCode(params));
1412                                if (params.traceMethod != null) {
1413                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1414                                            params.traceMethod, params.traceCookie);
1415                                }
1416                                return;
1417                            }
1418                            mPendingInstalls.clear();
1419                        } else {
1420                            Slog.w(TAG, "Waiting to connect to media container service");
1421                        }
1422                    } else if (mPendingInstalls.size() > 0) {
1423                        HandlerParams params = mPendingInstalls.get(0);
1424                        if (params != null) {
1425                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1426                                    System.identityHashCode(params));
1427                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1428                            if (params.startCopy()) {
1429                                // We are done...  look for more work or to
1430                                // go idle.
1431                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1432                                        "Checking for more work or unbind...");
1433                                // Delete pending install
1434                                if (mPendingInstalls.size() > 0) {
1435                                    mPendingInstalls.remove(0);
1436                                }
1437                                if (mPendingInstalls.size() == 0) {
1438                                    if (mBound) {
1439                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1440                                                "Posting delayed MCS_UNBIND");
1441                                        removeMessages(MCS_UNBIND);
1442                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1443                                        // Unbind after a little delay, to avoid
1444                                        // continual thrashing.
1445                                        sendMessageDelayed(ubmsg, 10000);
1446                                    }
1447                                } else {
1448                                    // There are more pending requests in queue.
1449                                    // Just post MCS_BOUND message to trigger processing
1450                                    // of next pending install.
1451                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1452                                            "Posting MCS_BOUND for next work");
1453                                    mHandler.sendEmptyMessage(MCS_BOUND);
1454                                }
1455                            }
1456                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1457                        }
1458                    } else {
1459                        // Should never happen ideally.
1460                        Slog.w(TAG, "Empty queue");
1461                    }
1462                    break;
1463                }
1464                case MCS_RECONNECT: {
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1466                    if (mPendingInstalls.size() > 0) {
1467                        if (mBound) {
1468                            disconnectService();
1469                        }
1470                        if (!connectToService()) {
1471                            Slog.e(TAG, "Failed to bind to media container service");
1472                            for (HandlerParams params : mPendingInstalls) {
1473                                // Indicate service bind error
1474                                params.serviceError();
1475                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1476                                        System.identityHashCode(params));
1477                            }
1478                            mPendingInstalls.clear();
1479                        }
1480                    }
1481                    break;
1482                }
1483                case MCS_UNBIND: {
1484                    // If there is no actual work left, then time to unbind.
1485                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1486
1487                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1488                        if (mBound) {
1489                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1490
1491                            disconnectService();
1492                        }
1493                    } else if (mPendingInstalls.size() > 0) {
1494                        // There are more pending requests in queue.
1495                        // Just post MCS_BOUND message to trigger processing
1496                        // of next pending install.
1497                        mHandler.sendEmptyMessage(MCS_BOUND);
1498                    }
1499
1500                    break;
1501                }
1502                case MCS_GIVE_UP: {
1503                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1504                    HandlerParams params = mPendingInstalls.remove(0);
1505                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                            System.identityHashCode(params));
1507                    break;
1508                }
1509                case SEND_PENDING_BROADCAST: {
1510                    String packages[];
1511                    ArrayList<String> components[];
1512                    int size = 0;
1513                    int uids[];
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1515                    synchronized (mPackages) {
1516                        if (mPendingBroadcasts == null) {
1517                            return;
1518                        }
1519                        size = mPendingBroadcasts.size();
1520                        if (size <= 0) {
1521                            // Nothing to be done. Just return
1522                            return;
1523                        }
1524                        packages = new String[size];
1525                        components = new ArrayList[size];
1526                        uids = new int[size];
1527                        int i = 0;  // filling out the above arrays
1528
1529                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1530                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1531                            Iterator<Map.Entry<String, ArrayList<String>>> it
1532                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1533                                            .entrySet().iterator();
1534                            while (it.hasNext() && i < size) {
1535                                Map.Entry<String, ArrayList<String>> ent = it.next();
1536                                packages[i] = ent.getKey();
1537                                components[i] = ent.getValue();
1538                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1539                                uids[i] = (ps != null)
1540                                        ? UserHandle.getUid(packageUserId, ps.appId)
1541                                        : -1;
1542                                i++;
1543                            }
1544                        }
1545                        size = i;
1546                        mPendingBroadcasts.clear();
1547                    }
1548                    // Send broadcasts
1549                    for (int i = 0; i < size; i++) {
1550                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1551                    }
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1553                    break;
1554                }
1555                case START_CLEANING_PACKAGE: {
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1557                    final String packageName = (String)msg.obj;
1558                    final int userId = msg.arg1;
1559                    final boolean andCode = msg.arg2 != 0;
1560                    synchronized (mPackages) {
1561                        if (userId == UserHandle.USER_ALL) {
1562                            int[] users = sUserManager.getUserIds();
1563                            for (int user : users) {
1564                                mSettings.addPackageToCleanLPw(
1565                                        new PackageCleanItem(user, packageName, andCode));
1566                            }
1567                        } else {
1568                            mSettings.addPackageToCleanLPw(
1569                                    new PackageCleanItem(userId, packageName, andCode));
1570                        }
1571                    }
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1573                    startCleaningPackages();
1574                } break;
1575                case POST_INSTALL: {
1576                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1577
1578                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1579                    final boolean didRestore = (msg.arg2 != 0);
1580                    mRunningInstalls.delete(msg.arg1);
1581
1582                    if (data != null) {
1583                        InstallArgs args = data.args;
1584                        PackageInstalledInfo parentRes = data.res;
1585
1586                        final boolean grantPermissions = (args.installFlags
1587                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1588                        final boolean killApp = (args.installFlags
1589                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1590                        final String[] grantedPermissions = args.installGrantPermissions;
1591
1592                        // Handle the parent package
1593                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1594                                grantedPermissions, didRestore, args.installerPackageName,
1595                                args.observer);
1596
1597                        // Handle the child packages
1598                        final int childCount = (parentRes.addedChildPackages != null)
1599                                ? parentRes.addedChildPackages.size() : 0;
1600                        for (int i = 0; i < childCount; i++) {
1601                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1602                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1603                                    grantedPermissions, false, args.installerPackageName,
1604                                    args.observer);
1605                        }
1606
1607                        // Log tracing if needed
1608                        if (args.traceMethod != null) {
1609                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1610                                    args.traceCookie);
1611                        }
1612                    } else {
1613                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1614                    }
1615
1616                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1617                } break;
1618                case UPDATED_MEDIA_STATUS: {
1619                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1620                    boolean reportStatus = msg.arg1 == 1;
1621                    boolean doGc = msg.arg2 == 1;
1622                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1623                    if (doGc) {
1624                        // Force a gc to clear up stale containers.
1625                        Runtime.getRuntime().gc();
1626                    }
1627                    if (msg.obj != null) {
1628                        @SuppressWarnings("unchecked")
1629                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1630                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1631                        // Unload containers
1632                        unloadAllContainers(args);
1633                    }
1634                    if (reportStatus) {
1635                        try {
1636                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1637                            PackageHelper.getMountService().finishMediaUpdate();
1638                        } catch (RemoteException e) {
1639                            Log.e(TAG, "MountService not running?");
1640                        }
1641                    }
1642                } break;
1643                case WRITE_SETTINGS: {
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1645                    synchronized (mPackages) {
1646                        removeMessages(WRITE_SETTINGS);
1647                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1648                        mSettings.writeLPr();
1649                        mDirtyUsers.clear();
1650                    }
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652                } break;
1653                case WRITE_PACKAGE_RESTRICTIONS: {
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1655                    synchronized (mPackages) {
1656                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1657                        for (int userId : mDirtyUsers) {
1658                            mSettings.writePackageRestrictionsLPr(userId);
1659                        }
1660                        mDirtyUsers.clear();
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                } break;
1664                case CHECK_PENDING_VERIFICATION: {
1665                    final int verificationId = msg.arg1;
1666                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1667
1668                    if ((state != null) && !state.timeoutExtended()) {
1669                        final InstallArgs args = state.getInstallArgs();
1670                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1671
1672                        Slog.i(TAG, "Verification timed out for " + originUri);
1673                        mPendingVerification.remove(verificationId);
1674
1675                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1676
1677                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1678                            Slog.i(TAG, "Continuing with installation of " + originUri);
1679                            state.setVerifierResponse(Binder.getCallingUid(),
1680                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1681                            broadcastPackageVerified(verificationId, originUri,
1682                                    PackageManager.VERIFICATION_ALLOW,
1683                                    state.getInstallArgs().getUser());
1684                            try {
1685                                ret = args.copyApk(mContainerService, true);
1686                            } catch (RemoteException e) {
1687                                Slog.e(TAG, "Could not contact the ContainerService");
1688                            }
1689                        } else {
1690                            broadcastPackageVerified(verificationId, originUri,
1691                                    PackageManager.VERIFICATION_REJECT,
1692                                    state.getInstallArgs().getUser());
1693                        }
1694
1695                        Trace.asyncTraceEnd(
1696                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1697
1698                        processPendingInstall(args, ret);
1699                        mHandler.sendEmptyMessage(MCS_UNBIND);
1700                    }
1701                    break;
1702                }
1703                case PACKAGE_VERIFIED: {
1704                    final int verificationId = msg.arg1;
1705
1706                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1707                    if (state == null) {
1708                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1709                        break;
1710                    }
1711
1712                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1713
1714                    state.setVerifierResponse(response.callerUid, response.code);
1715
1716                    if (state.isVerificationComplete()) {
1717                        mPendingVerification.remove(verificationId);
1718
1719                        final InstallArgs args = state.getInstallArgs();
1720                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1721
1722                        int ret;
1723                        if (state.isInstallAllowed()) {
1724                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1725                            broadcastPackageVerified(verificationId, originUri,
1726                                    response.code, state.getInstallArgs().getUser());
1727                            try {
1728                                ret = args.copyApk(mContainerService, true);
1729                            } catch (RemoteException e) {
1730                                Slog.e(TAG, "Could not contact the ContainerService");
1731                            }
1732                        } else {
1733                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1734                        }
1735
1736                        Trace.asyncTraceEnd(
1737                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1738
1739                        processPendingInstall(args, ret);
1740                        mHandler.sendEmptyMessage(MCS_UNBIND);
1741                    }
1742
1743                    break;
1744                }
1745                case START_INTENT_FILTER_VERIFICATIONS: {
1746                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1747                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1748                            params.replacing, params.pkg);
1749                    break;
1750                }
1751                case INTENT_FILTER_VERIFIED: {
1752                    final int verificationId = msg.arg1;
1753
1754                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1755                            verificationId);
1756                    if (state == null) {
1757                        Slog.w(TAG, "Invalid IntentFilter verification token "
1758                                + verificationId + " received");
1759                        break;
1760                    }
1761
1762                    final int userId = state.getUserId();
1763
1764                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1765                            "Processing IntentFilter verification with token:"
1766                            + verificationId + " and userId:" + userId);
1767
1768                    final IntentFilterVerificationResponse response =
1769                            (IntentFilterVerificationResponse) msg.obj;
1770
1771                    state.setVerifierResponse(response.callerUid, response.code);
1772
1773                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1774                            "IntentFilter verification with token:" + verificationId
1775                            + " and userId:" + userId
1776                            + " is settings verifier response with response code:"
1777                            + response.code);
1778
1779                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1780                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1781                                + response.getFailedDomainsString());
1782                    }
1783
1784                    if (state.isVerificationComplete()) {
1785                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1786                    } else {
1787                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1788                                "IntentFilter verification with token:" + verificationId
1789                                + " was not said to be complete");
1790                    }
1791
1792                    break;
1793                }
1794            }
1795        }
1796    }
1797
1798    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1799            boolean killApp, String[] grantedPermissions,
1800            boolean launchedForRestore, String installerPackage,
1801            IPackageInstallObserver2 installObserver) {
1802        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1803            // Send the removed broadcasts
1804            if (res.removedInfo != null) {
1805                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1806            }
1807
1808            // Now that we successfully installed the package, grant runtime
1809            // permissions if requested before broadcasting the install.
1810            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1811                    >= Build.VERSION_CODES.M) {
1812                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1813            }
1814
1815            final boolean update = res.removedInfo != null
1816                    && res.removedInfo.removedPackage != null;
1817
1818            // If this is the first time we have child packages for a disabled privileged
1819            // app that had no children, we grant requested runtime permissions to the new
1820            // children if the parent on the system image had them already granted.
1821            if (res.pkg.parentPackage != null) {
1822                synchronized (mPackages) {
1823                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1824                }
1825            }
1826
1827            synchronized (mPackages) {
1828                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1829            }
1830
1831            final String packageName = res.pkg.applicationInfo.packageName;
1832            Bundle extras = new Bundle(1);
1833            extras.putInt(Intent.EXTRA_UID, res.uid);
1834
1835            // Determine the set of users who are adding this package for
1836            // the first time vs. those who are seeing an update.
1837            int[] firstUsers = EMPTY_INT_ARRAY;
1838            int[] updateUsers = EMPTY_INT_ARRAY;
1839            if (res.origUsers == null || res.origUsers.length == 0) {
1840                firstUsers = res.newUsers;
1841            } else {
1842                for (int newUser : res.newUsers) {
1843                    boolean isNew = true;
1844                    for (int origUser : res.origUsers) {
1845                        if (origUser == newUser) {
1846                            isNew = false;
1847                            break;
1848                        }
1849                    }
1850                    if (isNew) {
1851                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1852                    } else {
1853                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1854                    }
1855                }
1856            }
1857
1858            // Send installed broadcasts if the install/update is not ephemeral
1859            if (!isEphemeral(res.pkg)) {
1860                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1861
1862                // Send added for users that see the package for the first time
1863                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1864                        extras, 0 /*flags*/, null /*targetPackage*/,
1865                        null /*finishedReceiver*/, firstUsers);
1866
1867                // Send added for users that don't see the package for the first time
1868                if (update) {
1869                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1870                }
1871                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1872                        extras, 0 /*flags*/, null /*targetPackage*/,
1873                        null /*finishedReceiver*/, updateUsers);
1874
1875                // Send replaced for users that don't see the package for the first time
1876                if (update) {
1877                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1878                            packageName, extras, 0 /*flags*/,
1879                            null /*targetPackage*/, null /*finishedReceiver*/,
1880                            updateUsers);
1881                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1882                            null /*package*/, null /*extras*/, 0 /*flags*/,
1883                            packageName /*targetPackage*/,
1884                            null /*finishedReceiver*/, updateUsers);
1885                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1886                    // First-install and we did a restore, so we're responsible for the
1887                    // first-launch broadcast.
1888                    if (DEBUG_BACKUP) {
1889                        Slog.i(TAG, "Post-restore of " + packageName
1890                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1891                    }
1892                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1893                }
1894
1895                // Send broadcast package appeared if forward locked/external for all users
1896                // treat asec-hosted packages like removable media on upgrade
1897                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1898                    if (DEBUG_INSTALL) {
1899                        Slog.i(TAG, "upgrading pkg " + res.pkg
1900                                + " is ASEC-hosted -> AVAILABLE");
1901                    }
1902                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1903                    ArrayList<String> pkgList = new ArrayList<>(1);
1904                    pkgList.add(packageName);
1905                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1906                }
1907            }
1908
1909            // Work that needs to happen on first install within each user
1910            if (firstUsers != null && firstUsers.length > 0) {
1911                synchronized (mPackages) {
1912                    for (int userId : firstUsers) {
1913                        // If this app is a browser and it's newly-installed for some
1914                        // users, clear any default-browser state in those users. The
1915                        // app's nature doesn't depend on the user, so we can just check
1916                        // its browser nature in any user and generalize.
1917                        if (packageIsBrowser(packageName, userId)) {
1918                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1919                        }
1920
1921                        // We may also need to apply pending (restored) runtime
1922                        // permission grants within these users.
1923                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1924                    }
1925                }
1926            }
1927
1928            // Log current value of "unknown sources" setting
1929            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1930                    getUnknownSourcesSettings());
1931
1932            // Force a gc to clear up things
1933            Runtime.getRuntime().gc();
1934
1935            // Remove the replaced package's older resources safely now
1936            // We delete after a gc for applications  on sdcard.
1937            if (res.removedInfo != null && res.removedInfo.args != null) {
1938                synchronized (mInstallLock) {
1939                    res.removedInfo.args.doPostDeleteLI(true);
1940                }
1941            }
1942        }
1943
1944        // If someone is watching installs - notify them
1945        if (installObserver != null) {
1946            try {
1947                Bundle extras = extrasForInstallResult(res);
1948                installObserver.onPackageInstalled(res.name, res.returnCode,
1949                        res.returnMsg, extras);
1950            } catch (RemoteException e) {
1951                Slog.i(TAG, "Observer no longer exists.");
1952            }
1953        }
1954    }
1955
1956    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1957            PackageParser.Package pkg) {
1958        if (pkg.parentPackage == null) {
1959            return;
1960        }
1961        if (pkg.requestedPermissions == null) {
1962            return;
1963        }
1964        final PackageSetting disabledSysParentPs = mSettings
1965                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1966        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1967                || !disabledSysParentPs.isPrivileged()
1968                || (disabledSysParentPs.childPackageNames != null
1969                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1970            return;
1971        }
1972        final int[] allUserIds = sUserManager.getUserIds();
1973        final int permCount = pkg.requestedPermissions.size();
1974        for (int i = 0; i < permCount; i++) {
1975            String permission = pkg.requestedPermissions.get(i);
1976            BasePermission bp = mSettings.mPermissions.get(permission);
1977            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1978                continue;
1979            }
1980            for (int userId : allUserIds) {
1981                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1982                        permission, userId)) {
1983                    grantRuntimePermission(pkg.packageName, permission, userId);
1984                }
1985            }
1986        }
1987    }
1988
1989    private StorageEventListener mStorageListener = new StorageEventListener() {
1990        @Override
1991        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1992            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1993                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1994                    final String volumeUuid = vol.getFsUuid();
1995
1996                    // Clean up any users or apps that were removed or recreated
1997                    // while this volume was missing
1998                    reconcileUsers(volumeUuid);
1999                    reconcileApps(volumeUuid);
2000
2001                    // Clean up any install sessions that expired or were
2002                    // cancelled while this volume was missing
2003                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2004
2005                    loadPrivatePackages(vol);
2006
2007                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2008                    unloadPrivatePackages(vol);
2009                }
2010            }
2011
2012            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2013                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2014                    updateExternalMediaStatus(true, false);
2015                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2016                    updateExternalMediaStatus(false, false);
2017                }
2018            }
2019        }
2020
2021        @Override
2022        public void onVolumeForgotten(String fsUuid) {
2023            if (TextUtils.isEmpty(fsUuid)) {
2024                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2025                return;
2026            }
2027
2028            // Remove any apps installed on the forgotten volume
2029            synchronized (mPackages) {
2030                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2031                for (PackageSetting ps : packages) {
2032                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2033                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2034                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2035                }
2036
2037                mSettings.onVolumeForgotten(fsUuid);
2038                mSettings.writeLPr();
2039            }
2040        }
2041    };
2042
2043    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2044            String[] grantedPermissions) {
2045        for (int userId : userIds) {
2046            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2047        }
2048
2049        // We could have touched GID membership, so flush out packages.list
2050        synchronized (mPackages) {
2051            mSettings.writePackageListLPr();
2052        }
2053    }
2054
2055    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2056            String[] grantedPermissions) {
2057        SettingBase sb = (SettingBase) pkg.mExtras;
2058        if (sb == null) {
2059            return;
2060        }
2061
2062        PermissionsState permissionsState = sb.getPermissionsState();
2063
2064        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2065                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2066
2067        for (String permission : pkg.requestedPermissions) {
2068            final BasePermission bp;
2069            synchronized (mPackages) {
2070                bp = mSettings.mPermissions.get(permission);
2071            }
2072            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2073                    && (grantedPermissions == null
2074                           || ArrayUtils.contains(grantedPermissions, permission))) {
2075                final int flags = permissionsState.getPermissionFlags(permission, userId);
2076                // Installer cannot change immutable permissions.
2077                if ((flags & immutableFlags) == 0) {
2078                    grantRuntimePermission(pkg.packageName, permission, userId);
2079                }
2080            }
2081        }
2082    }
2083
2084    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2085        Bundle extras = null;
2086        switch (res.returnCode) {
2087            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2088                extras = new Bundle();
2089                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2090                        res.origPermission);
2091                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2092                        res.origPackage);
2093                break;
2094            }
2095            case PackageManager.INSTALL_SUCCEEDED: {
2096                extras = new Bundle();
2097                extras.putBoolean(Intent.EXTRA_REPLACING,
2098                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2099                break;
2100            }
2101        }
2102        return extras;
2103    }
2104
2105    void scheduleWriteSettingsLocked() {
2106        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2107            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2108        }
2109    }
2110
2111    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2112        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2113        scheduleWritePackageRestrictionsLocked(userId);
2114    }
2115
2116    void scheduleWritePackageRestrictionsLocked(int userId) {
2117        final int[] userIds = (userId == UserHandle.USER_ALL)
2118                ? sUserManager.getUserIds() : new int[]{userId};
2119        for (int nextUserId : userIds) {
2120            if (!sUserManager.exists(nextUserId)) return;
2121            mDirtyUsers.add(nextUserId);
2122            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2123                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2124            }
2125        }
2126    }
2127
2128    public static PackageManagerService main(Context context, Installer installer,
2129            boolean factoryTest, boolean onlyCore) {
2130        // Self-check for initial settings.
2131        PackageManagerServiceCompilerMapping.checkProperties();
2132
2133        PackageManagerService m = new PackageManagerService(context, installer,
2134                factoryTest, onlyCore);
2135        m.enableSystemUserPackages();
2136        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2137        // disabled after already being started.
2138        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2139                UserHandle.USER_SYSTEM);
2140        ServiceManager.addService("package", m);
2141        return m;
2142    }
2143
2144    private void enableSystemUserPackages() {
2145        if (!UserManager.isSplitSystemUser()) {
2146            return;
2147        }
2148        // For system user, enable apps based on the following conditions:
2149        // - app is whitelisted or belong to one of these groups:
2150        //   -- system app which has no launcher icons
2151        //   -- system app which has INTERACT_ACROSS_USERS permission
2152        //   -- system IME app
2153        // - app is not in the blacklist
2154        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2155        Set<String> enableApps = new ArraySet<>();
2156        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2157                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2158                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2159        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2160        enableApps.addAll(wlApps);
2161        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2162                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2163        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2164        enableApps.removeAll(blApps);
2165        Log.i(TAG, "Applications installed for system user: " + enableApps);
2166        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2167                UserHandle.SYSTEM);
2168        final int allAppsSize = allAps.size();
2169        synchronized (mPackages) {
2170            for (int i = 0; i < allAppsSize; i++) {
2171                String pName = allAps.get(i);
2172                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2173                // Should not happen, but we shouldn't be failing if it does
2174                if (pkgSetting == null) {
2175                    continue;
2176                }
2177                boolean install = enableApps.contains(pName);
2178                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2179                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2180                            + " for system user");
2181                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2182                }
2183            }
2184        }
2185    }
2186
2187    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2188        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2189                Context.DISPLAY_SERVICE);
2190        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2191    }
2192
2193    public PackageManagerService(Context context, Installer installer,
2194            boolean factoryTest, boolean onlyCore) {
2195        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2196                SystemClock.uptimeMillis());
2197
2198        if (mSdkVersion <= 0) {
2199            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2200        }
2201
2202        mContext = context;
2203        mFactoryTest = factoryTest;
2204        mOnlyCore = onlyCore;
2205        mMetrics = new DisplayMetrics();
2206        mSettings = new Settings(mPackages);
2207        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2216                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2217        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2218                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2219
2220        String separateProcesses = SystemProperties.get("debug.separate_processes");
2221        if (separateProcesses != null && separateProcesses.length() > 0) {
2222            if ("*".equals(separateProcesses)) {
2223                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2224                mSeparateProcesses = null;
2225                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2226            } else {
2227                mDefParseFlags = 0;
2228                mSeparateProcesses = separateProcesses.split(",");
2229                Slog.w(TAG, "Running with debug.separate_processes: "
2230                        + separateProcesses);
2231            }
2232        } else {
2233            mDefParseFlags = 0;
2234            mSeparateProcesses = null;
2235        }
2236
2237        mInstaller = installer;
2238        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2239                "*dexopt*");
2240        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2241
2242        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2243                FgThread.get().getLooper());
2244
2245        getDefaultDisplayMetrics(context, mMetrics);
2246
2247        SystemConfig systemConfig = SystemConfig.getInstance();
2248        mGlobalGids = systemConfig.getGlobalGids();
2249        mSystemPermissions = systemConfig.getSystemPermissions();
2250        mAvailableFeatures = systemConfig.getAvailableFeatures();
2251
2252        synchronized (mInstallLock) {
2253        // writer
2254        synchronized (mPackages) {
2255            mHandlerThread = new ServiceThread(TAG,
2256                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2257            mHandlerThread.start();
2258            mHandler = new PackageHandler(mHandlerThread.getLooper());
2259            mProcessLoggingHandler = new ProcessLoggingHandler();
2260            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2261
2262            File dataDir = Environment.getDataDirectory();
2263            mAppInstallDir = new File(dataDir, "app");
2264            mAppLib32InstallDir = new File(dataDir, "app-lib");
2265            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2266            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2267            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2268
2269            sUserManager = new UserManagerService(context, this, mPackages);
2270
2271            // Propagate permission configuration in to package manager.
2272            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2273                    = systemConfig.getPermissions();
2274            for (int i=0; i<permConfig.size(); i++) {
2275                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2276                BasePermission bp = mSettings.mPermissions.get(perm.name);
2277                if (bp == null) {
2278                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2279                    mSettings.mPermissions.put(perm.name, bp);
2280                }
2281                if (perm.gids != null) {
2282                    bp.setGids(perm.gids, perm.perUser);
2283                }
2284            }
2285
2286            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2287            for (int i=0; i<libConfig.size(); i++) {
2288                mSharedLibraries.put(libConfig.keyAt(i),
2289                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2290            }
2291
2292            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2293
2294            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2295
2296            String customResolverActivity = Resources.getSystem().getString(
2297                    R.string.config_customResolverActivity);
2298            if (TextUtils.isEmpty(customResolverActivity)) {
2299                customResolverActivity = null;
2300            } else {
2301                mCustomResolverComponentName = ComponentName.unflattenFromString(
2302                        customResolverActivity);
2303            }
2304
2305            long startTime = SystemClock.uptimeMillis();
2306
2307            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2308                    startTime);
2309
2310            // Set flag to monitor and not change apk file paths when
2311            // scanning install directories.
2312            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2313
2314            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2315            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2316
2317            if (bootClassPath == null) {
2318                Slog.w(TAG, "No BOOTCLASSPATH found!");
2319            }
2320
2321            if (systemServerClassPath == null) {
2322                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2323            }
2324
2325            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2326            final String[] dexCodeInstructionSets =
2327                    getDexCodeInstructionSets(
2328                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2329
2330            /**
2331             * Ensure all external libraries have had dexopt run on them.
2332             */
2333            if (mSharedLibraries.size() > 0) {
2334                // NOTE: For now, we're compiling these system "shared libraries"
2335                // (and framework jars) into all available architectures. It's possible
2336                // to compile them only when we come across an app that uses them (there's
2337                // already logic for that in scanPackageLI) but that adds some complexity.
2338                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2339                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2340                        final String lib = libEntry.path;
2341                        if (lib == null) {
2342                            continue;
2343                        }
2344
2345                        try {
2346                            // Shared libraries do not have profiles so we perform a full
2347                            // AOT compilation (if needed).
2348                            int dexoptNeeded = DexFile.getDexOptNeeded(
2349                                    lib, dexCodeInstructionSet,
2350                                    getCompilerFilterForReason(REASON_SHARED_APK),
2351                                    false /* newProfile */);
2352                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2353                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2354                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2355                                        getCompilerFilterForReason(REASON_SHARED_APK),
2356                                        StorageManager.UUID_PRIVATE_INTERNAL,
2357                                        SKIP_SHARED_LIBRARY_CHECK);
2358                            }
2359                        } catch (FileNotFoundException e) {
2360                            Slog.w(TAG, "Library not found: " + lib);
2361                        } catch (IOException | InstallerException e) {
2362                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2363                                    + e.getMessage());
2364                        }
2365                    }
2366                }
2367            }
2368
2369            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2370
2371            final VersionInfo ver = mSettings.getInternalVersion();
2372            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2373
2374            // when upgrading from pre-M, promote system app permissions from install to runtime
2375            mPromoteSystemApps =
2376                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2377
2378            // save off the names of pre-existing system packages prior to scanning; we don't
2379            // want to automatically grant runtime permissions for new system apps
2380            if (mPromoteSystemApps) {
2381                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2382                while (pkgSettingIter.hasNext()) {
2383                    PackageSetting ps = pkgSettingIter.next();
2384                    if (isSystemApp(ps)) {
2385                        mExistingSystemPackages.add(ps.name);
2386                    }
2387                }
2388            }
2389
2390            // When upgrading from pre-N, we need to handle package extraction like first boot,
2391            // as there is no profiling data available.
2392            mIsPreNUpgrade = !mSettings.isNWorkDone();
2393            mSettings.setNWorkDone();
2394
2395            // Collect vendor overlay packages.
2396            // (Do this before scanning any apps.)
2397            // For security and version matching reason, only consider
2398            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2399            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2400            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2401                    | PackageParser.PARSE_IS_SYSTEM
2402                    | PackageParser.PARSE_IS_SYSTEM_DIR
2403                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2404
2405            // Find base frameworks (resource packages without code).
2406            scanDirTracedLI(frameworkDir, mDefParseFlags
2407                    | PackageParser.PARSE_IS_SYSTEM
2408                    | PackageParser.PARSE_IS_SYSTEM_DIR
2409                    | PackageParser.PARSE_IS_PRIVILEGED,
2410                    scanFlags | SCAN_NO_DEX, 0);
2411
2412            // Collected privileged system packages.
2413            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2414            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2415                    | PackageParser.PARSE_IS_SYSTEM
2416                    | PackageParser.PARSE_IS_SYSTEM_DIR
2417                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2418
2419            // Collect ordinary system packages.
2420            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2421            scanDirTracedLI(systemAppDir, mDefParseFlags
2422                    | PackageParser.PARSE_IS_SYSTEM
2423                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2424
2425            // Collect all vendor packages.
2426            File vendorAppDir = new File("/vendor/app");
2427            try {
2428                vendorAppDir = vendorAppDir.getCanonicalFile();
2429            } catch (IOException e) {
2430                // failed to look up canonical path, continue with original one
2431            }
2432            scanDirTracedLI(vendorAppDir, mDefParseFlags
2433                    | PackageParser.PARSE_IS_SYSTEM
2434                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2435
2436            // Collect all OEM packages.
2437            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2438            scanDirTracedLI(oemAppDir, mDefParseFlags
2439                    | PackageParser.PARSE_IS_SYSTEM
2440                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2441
2442            // Prune any system packages that no longer exist.
2443            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2444            if (!mOnlyCore) {
2445                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2446                while (psit.hasNext()) {
2447                    PackageSetting ps = psit.next();
2448
2449                    /*
2450                     * If this is not a system app, it can't be a
2451                     * disable system app.
2452                     */
2453                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2454                        continue;
2455                    }
2456
2457                    /*
2458                     * If the package is scanned, it's not erased.
2459                     */
2460                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2461                    if (scannedPkg != null) {
2462                        /*
2463                         * If the system app is both scanned and in the
2464                         * disabled packages list, then it must have been
2465                         * added via OTA. Remove it from the currently
2466                         * scanned package so the previously user-installed
2467                         * application can be scanned.
2468                         */
2469                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2470                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2471                                    + ps.name + "; removing system app.  Last known codePath="
2472                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2473                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2474                                    + scannedPkg.mVersionCode);
2475                            removePackageLI(scannedPkg, true);
2476                            mExpectingBetter.put(ps.name, ps.codePath);
2477                        }
2478
2479                        continue;
2480                    }
2481
2482                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2483                        psit.remove();
2484                        logCriticalInfo(Log.WARN, "System package " + ps.name
2485                                + " no longer exists; it's data will be wiped");
2486                        // Actual deletion of code and data will be handled by later
2487                        // reconciliation step
2488                    } else {
2489                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2490                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2491                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2492                        }
2493                    }
2494                }
2495            }
2496
2497            //look for any incomplete package installations
2498            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2499            for (int i = 0; i < deletePkgsList.size(); i++) {
2500                // Actual deletion of code and data will be handled by later
2501                // reconciliation step
2502                final String packageName = deletePkgsList.get(i).name;
2503                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2504                synchronized (mPackages) {
2505                    mSettings.removePackageLPw(packageName);
2506                }
2507            }
2508
2509            //delete tmp files
2510            deleteTempPackageFiles();
2511
2512            // Remove any shared userIDs that have no associated packages
2513            mSettings.pruneSharedUsersLPw();
2514
2515            if (!mOnlyCore) {
2516                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2517                        SystemClock.uptimeMillis());
2518                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2519
2520                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2521                        | PackageParser.PARSE_FORWARD_LOCK,
2522                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2523
2524                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2525                        | PackageParser.PARSE_IS_EPHEMERAL,
2526                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2527
2528                /**
2529                 * Remove disable package settings for any updated system
2530                 * apps that were removed via an OTA. If they're not a
2531                 * previously-updated app, remove them completely.
2532                 * Otherwise, just revoke their system-level permissions.
2533                 */
2534                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2535                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2536                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2537
2538                    String msg;
2539                    if (deletedPkg == null) {
2540                        msg = "Updated system package " + deletedAppName
2541                                + " no longer exists; it's data will be wiped";
2542                        // Actual deletion of code and data will be handled by later
2543                        // reconciliation step
2544                    } else {
2545                        msg = "Updated system app + " + deletedAppName
2546                                + " no longer present; removing system privileges for "
2547                                + deletedAppName;
2548
2549                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2550
2551                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2552                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2553                    }
2554                    logCriticalInfo(Log.WARN, msg);
2555                }
2556
2557                /**
2558                 * Make sure all system apps that we expected to appear on
2559                 * the userdata partition actually showed up. If they never
2560                 * appeared, crawl back and revive the system version.
2561                 */
2562                for (int i = 0; i < mExpectingBetter.size(); i++) {
2563                    final String packageName = mExpectingBetter.keyAt(i);
2564                    if (!mPackages.containsKey(packageName)) {
2565                        final File scanFile = mExpectingBetter.valueAt(i);
2566
2567                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2568                                + " but never showed up; reverting to system");
2569
2570                        int reparseFlags = mDefParseFlags;
2571                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2572                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2573                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2574                                    | PackageParser.PARSE_IS_PRIVILEGED;
2575                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2576                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2577                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2578                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2579                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2580                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2581                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2582                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2583                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2584                        } else {
2585                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2586                            continue;
2587                        }
2588
2589                        mSettings.enableSystemPackageLPw(packageName);
2590
2591                        try {
2592                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2593                        } catch (PackageManagerException e) {
2594                            Slog.e(TAG, "Failed to parse original system package: "
2595                                    + e.getMessage());
2596                        }
2597                    }
2598                }
2599            }
2600            mExpectingBetter.clear();
2601
2602            // Resolve protected action filters. Only the setup wizard is allowed to
2603            // have a high priority filter for these actions.
2604            mSetupWizardPackage = getSetupWizardPackageName();
2605            if (mProtectedFilters.size() > 0) {
2606                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2607                    Slog.i(TAG, "No setup wizard;"
2608                        + " All protected intents capped to priority 0");
2609                }
2610                for (ActivityIntentInfo filter : mProtectedFilters) {
2611                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2612                        if (DEBUG_FILTERS) {
2613                            Slog.i(TAG, "Found setup wizard;"
2614                                + " allow priority " + filter.getPriority() + ";"
2615                                + " package: " + filter.activity.info.packageName
2616                                + " activity: " + filter.activity.className
2617                                + " priority: " + filter.getPriority());
2618                        }
2619                        // skip setup wizard; allow it to keep the high priority filter
2620                        continue;
2621                    }
2622                    Slog.w(TAG, "Protected action; cap priority to 0;"
2623                            + " package: " + filter.activity.info.packageName
2624                            + " activity: " + filter.activity.className
2625                            + " origPrio: " + filter.getPriority());
2626                    filter.setPriority(0);
2627                }
2628            }
2629            mDeferProtectedFilters = false;
2630            mProtectedFilters.clear();
2631
2632            // Now that we know all of the shared libraries, update all clients to have
2633            // the correct library paths.
2634            updateAllSharedLibrariesLPw();
2635
2636            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2637                // NOTE: We ignore potential failures here during a system scan (like
2638                // the rest of the commands above) because there's precious little we
2639                // can do about it. A settings error is reported, though.
2640                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2641                        false /* boot complete */);
2642            }
2643
2644            // Now that we know all the packages we are keeping,
2645            // read and update their last usage times.
2646            mPackageUsage.readLP();
2647
2648            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2649                    SystemClock.uptimeMillis());
2650            Slog.i(TAG, "Time to scan packages: "
2651                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2652                    + " seconds");
2653
2654            // If the platform SDK has changed since the last time we booted,
2655            // we need to re-grant app permission to catch any new ones that
2656            // appear.  This is really a hack, and means that apps can in some
2657            // cases get permissions that the user didn't initially explicitly
2658            // allow...  it would be nice to have some better way to handle
2659            // this situation.
2660            int updateFlags = UPDATE_PERMISSIONS_ALL;
2661            if (ver.sdkVersion != mSdkVersion) {
2662                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2663                        + mSdkVersion + "; regranting permissions for internal storage");
2664                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2665            }
2666            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2667            ver.sdkVersion = mSdkVersion;
2668
2669            // If this is the first boot or an update from pre-M, and it is a normal
2670            // boot, then we need to initialize the default preferred apps across
2671            // all defined users.
2672            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2673                for (UserInfo user : sUserManager.getUsers(true)) {
2674                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2675                    applyFactoryDefaultBrowserLPw(user.id);
2676                    primeDomainVerificationsLPw(user.id);
2677                }
2678            }
2679
2680            // Prepare storage for system user really early during boot,
2681            // since core system apps like SettingsProvider and SystemUI
2682            // can't wait for user to start
2683            final int storageFlags;
2684            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2685                storageFlags = StorageManager.FLAG_STORAGE_DE;
2686            } else {
2687                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2688            }
2689            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2690                    storageFlags);
2691
2692            // If this is first boot after an OTA, and a normal boot, then
2693            // we need to clear code cache directories.
2694            if (mIsUpgrade && !onlyCore) {
2695                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2696                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2697                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2698                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2699                        // No apps are running this early, so no need to freeze
2700                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2701                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2702                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2703                    }
2704                    clearAppProfilesLIF(ps.pkg);
2705                }
2706                ver.fingerprint = Build.FINGERPRINT;
2707            }
2708
2709            checkDefaultBrowser();
2710
2711            // clear only after permissions and other defaults have been updated
2712            mExistingSystemPackages.clear();
2713            mPromoteSystemApps = false;
2714
2715            // All the changes are done during package scanning.
2716            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2717
2718            // can downgrade to reader
2719            mSettings.writeLPr();
2720
2721            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2722                    SystemClock.uptimeMillis());
2723
2724            if (!mOnlyCore) {
2725                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2726                mRequiredInstallerPackage = getRequiredInstallerLPr();
2727                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2728                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2729                        mIntentFilterVerifierComponent);
2730                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2731                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2732                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2733                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2734            } else {
2735                mRequiredVerifierPackage = null;
2736                mRequiredInstallerPackage = null;
2737                mIntentFilterVerifierComponent = null;
2738                mIntentFilterVerifier = null;
2739                mServicesSystemSharedLibraryPackageName = null;
2740                mSharedSystemSharedLibraryPackageName = null;
2741            }
2742
2743            mInstallerService = new PackageInstallerService(context, this);
2744
2745            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2746            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2747            // both the installer and resolver must be present to enable ephemeral
2748            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2749                if (DEBUG_EPHEMERAL) {
2750                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2751                            + " installer:" + ephemeralInstallerComponent);
2752                }
2753                mEphemeralResolverComponent = ephemeralResolverComponent;
2754                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2755                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2756                mEphemeralResolverConnection =
2757                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2758            } else {
2759                if (DEBUG_EPHEMERAL) {
2760                    final String missingComponent =
2761                            (ephemeralResolverComponent == null)
2762                            ? (ephemeralInstallerComponent == null)
2763                                    ? "resolver and installer"
2764                                    : "resolver"
2765                            : "installer";
2766                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2767                }
2768                mEphemeralResolverComponent = null;
2769                mEphemeralInstallerComponent = null;
2770                mEphemeralResolverConnection = null;
2771            }
2772
2773            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2774        } // synchronized (mPackages)
2775        } // synchronized (mInstallLock)
2776
2777        // Now after opening every single application zip, make sure they
2778        // are all flushed.  Not really needed, but keeps things nice and
2779        // tidy.
2780        Runtime.getRuntime().gc();
2781
2782        // The initial scanning above does many calls into installd while
2783        // holding the mPackages lock, but we're mostly interested in yelling
2784        // once we have a booted system.
2785        mInstaller.setWarnIfHeld(mPackages);
2786
2787        // Expose private service for system components to use.
2788        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2789    }
2790
2791    @Override
2792    public boolean isFirstBoot() {
2793        return !mRestoredSettings;
2794    }
2795
2796    @Override
2797    public boolean isOnlyCoreApps() {
2798        return mOnlyCore;
2799    }
2800
2801    @Override
2802    public boolean isUpgrade() {
2803        return mIsUpgrade;
2804    }
2805
2806    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2807        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2808
2809        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2810                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2811                UserHandle.USER_SYSTEM);
2812        if (matches.size() == 1) {
2813            return matches.get(0).getComponentInfo().packageName;
2814        } else {
2815            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2816            return null;
2817        }
2818    }
2819
2820    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2821        synchronized (mPackages) {
2822            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2823            if (libraryEntry == null) {
2824                throw new IllegalStateException("Missing required shared library:" + libraryName);
2825            }
2826            return libraryEntry.apk;
2827        }
2828    }
2829
2830    private @NonNull String getRequiredInstallerLPr() {
2831        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2832        intent.addCategory(Intent.CATEGORY_DEFAULT);
2833        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2834
2835        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2836                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2837                UserHandle.USER_SYSTEM);
2838        if (matches.size() == 1) {
2839            ResolveInfo resolveInfo = matches.get(0);
2840            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2841                throw new RuntimeException("The installer must be a privileged app");
2842            }
2843            return matches.get(0).getComponentInfo().packageName;
2844        } else {
2845            throw new RuntimeException("There must be exactly one installer; found " + matches);
2846        }
2847    }
2848
2849    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2850        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2851
2852        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2853                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2854                UserHandle.USER_SYSTEM);
2855        ResolveInfo best = null;
2856        final int N = matches.size();
2857        for (int i = 0; i < N; i++) {
2858            final ResolveInfo cur = matches.get(i);
2859            final String packageName = cur.getComponentInfo().packageName;
2860            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2861                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2862                continue;
2863            }
2864
2865            if (best == null || cur.priority > best.priority) {
2866                best = cur;
2867            }
2868        }
2869
2870        if (best != null) {
2871            return best.getComponentInfo().getComponentName();
2872        } else {
2873            throw new RuntimeException("There must be at least one intent filter verifier");
2874        }
2875    }
2876
2877    private @Nullable ComponentName getEphemeralResolverLPr() {
2878        final String[] packageArray =
2879                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2880        if (packageArray.length == 0) {
2881            if (DEBUG_EPHEMERAL) {
2882                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2883            }
2884            return null;
2885        }
2886
2887        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2888        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2889                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2890                UserHandle.USER_SYSTEM);
2891
2892        final int N = resolvers.size();
2893        if (N == 0) {
2894            if (DEBUG_EPHEMERAL) {
2895                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2896            }
2897            return null;
2898        }
2899
2900        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2901        for (int i = 0; i < N; i++) {
2902            final ResolveInfo info = resolvers.get(i);
2903
2904            if (info.serviceInfo == null) {
2905                continue;
2906            }
2907
2908            final String packageName = info.serviceInfo.packageName;
2909            if (!possiblePackages.contains(packageName)) {
2910                if (DEBUG_EPHEMERAL) {
2911                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2912                            + " pkg: " + packageName + ", info:" + info);
2913                }
2914                continue;
2915            }
2916
2917            if (DEBUG_EPHEMERAL) {
2918                Slog.v(TAG, "Ephemeral resolver found;"
2919                        + " pkg: " + packageName + ", info:" + info);
2920            }
2921            return new ComponentName(packageName, info.serviceInfo.name);
2922        }
2923        if (DEBUG_EPHEMERAL) {
2924            Slog.v(TAG, "Ephemeral resolver NOT found");
2925        }
2926        return null;
2927    }
2928
2929    private @Nullable ComponentName getEphemeralInstallerLPr() {
2930        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2931        intent.addCategory(Intent.CATEGORY_DEFAULT);
2932        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2933
2934        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2935                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2936                UserHandle.USER_SYSTEM);
2937        if (matches.size() == 0) {
2938            return null;
2939        } else if (matches.size() == 1) {
2940            return matches.get(0).getComponentInfo().getComponentName();
2941        } else {
2942            throw new RuntimeException(
2943                    "There must be at most one ephemeral installer; found " + matches);
2944        }
2945    }
2946
2947    private void primeDomainVerificationsLPw(int userId) {
2948        if (DEBUG_DOMAIN_VERIFICATION) {
2949            Slog.d(TAG, "Priming domain verifications in user " + userId);
2950        }
2951
2952        SystemConfig systemConfig = SystemConfig.getInstance();
2953        ArraySet<String> packages = systemConfig.getLinkedApps();
2954        ArraySet<String> domains = new ArraySet<String>();
2955
2956        for (String packageName : packages) {
2957            PackageParser.Package pkg = mPackages.get(packageName);
2958            if (pkg != null) {
2959                if (!pkg.isSystemApp()) {
2960                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2961                    continue;
2962                }
2963
2964                domains.clear();
2965                for (PackageParser.Activity a : pkg.activities) {
2966                    for (ActivityIntentInfo filter : a.intents) {
2967                        if (hasValidDomains(filter)) {
2968                            domains.addAll(filter.getHostsList());
2969                        }
2970                    }
2971                }
2972
2973                if (domains.size() > 0) {
2974                    if (DEBUG_DOMAIN_VERIFICATION) {
2975                        Slog.v(TAG, "      + " + packageName);
2976                    }
2977                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2978                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2979                    // and then 'always' in the per-user state actually used for intent resolution.
2980                    final IntentFilterVerificationInfo ivi;
2981                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2982                            new ArrayList<String>(domains));
2983                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2984                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2985                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2986                } else {
2987                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2988                            + "' does not handle web links");
2989                }
2990            } else {
2991                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2992            }
2993        }
2994
2995        scheduleWritePackageRestrictionsLocked(userId);
2996        scheduleWriteSettingsLocked();
2997    }
2998
2999    private void applyFactoryDefaultBrowserLPw(int userId) {
3000        // The default browser app's package name is stored in a string resource,
3001        // with a product-specific overlay used for vendor customization.
3002        String browserPkg = mContext.getResources().getString(
3003                com.android.internal.R.string.default_browser);
3004        if (!TextUtils.isEmpty(browserPkg)) {
3005            // non-empty string => required to be a known package
3006            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3007            if (ps == null) {
3008                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3009                browserPkg = null;
3010            } else {
3011                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3012            }
3013        }
3014
3015        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3016        // default.  If there's more than one, just leave everything alone.
3017        if (browserPkg == null) {
3018            calculateDefaultBrowserLPw(userId);
3019        }
3020    }
3021
3022    private void calculateDefaultBrowserLPw(int userId) {
3023        List<String> allBrowsers = resolveAllBrowserApps(userId);
3024        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3025        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3026    }
3027
3028    private List<String> resolveAllBrowserApps(int userId) {
3029        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3030        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3031                PackageManager.MATCH_ALL, userId);
3032
3033        final int count = list.size();
3034        List<String> result = new ArrayList<String>(count);
3035        for (int i=0; i<count; i++) {
3036            ResolveInfo info = list.get(i);
3037            if (info.activityInfo == null
3038                    || !info.handleAllWebDataURI
3039                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3040                    || result.contains(info.activityInfo.packageName)) {
3041                continue;
3042            }
3043            result.add(info.activityInfo.packageName);
3044        }
3045
3046        return result;
3047    }
3048
3049    private boolean packageIsBrowser(String packageName, int userId) {
3050        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3051                PackageManager.MATCH_ALL, userId);
3052        final int N = list.size();
3053        for (int i = 0; i < N; i++) {
3054            ResolveInfo info = list.get(i);
3055            if (packageName.equals(info.activityInfo.packageName)) {
3056                return true;
3057            }
3058        }
3059        return false;
3060    }
3061
3062    private void checkDefaultBrowser() {
3063        final int myUserId = UserHandle.myUserId();
3064        final String packageName = getDefaultBrowserPackageName(myUserId);
3065        if (packageName != null) {
3066            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3067            if (info == null) {
3068                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3069                synchronized (mPackages) {
3070                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3071                }
3072            }
3073        }
3074    }
3075
3076    @Override
3077    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3078            throws RemoteException {
3079        try {
3080            return super.onTransact(code, data, reply, flags);
3081        } catch (RuntimeException e) {
3082            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3083                Slog.wtf(TAG, "Package Manager Crash", e);
3084            }
3085            throw e;
3086        }
3087    }
3088
3089    static int[] appendInts(int[] cur, int[] add) {
3090        if (add == null) return cur;
3091        if (cur == null) return add;
3092        final int N = add.length;
3093        for (int i=0; i<N; i++) {
3094            cur = appendInt(cur, add[i]);
3095        }
3096        return cur;
3097    }
3098
3099    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3100        if (!sUserManager.exists(userId)) return null;
3101        if (ps == null) {
3102            return null;
3103        }
3104        final PackageParser.Package p = ps.pkg;
3105        if (p == null) {
3106            return null;
3107        }
3108
3109        final PermissionsState permissionsState = ps.getPermissionsState();
3110
3111        final int[] gids = permissionsState.computeGids(userId);
3112        final Set<String> permissions = permissionsState.getPermissions(userId);
3113        final PackageUserState state = ps.readUserState(userId);
3114
3115        return PackageParser.generatePackageInfo(p, gids, flags,
3116                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3117    }
3118
3119    @Override
3120    public void checkPackageStartable(String packageName, int userId) {
3121        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3122
3123        synchronized (mPackages) {
3124            final PackageSetting ps = mSettings.mPackages.get(packageName);
3125            if (ps == null) {
3126                throw new SecurityException("Package " + packageName + " was not found!");
3127            }
3128
3129            if (!ps.getInstalled(userId)) {
3130                throw new SecurityException(
3131                        "Package " + packageName + " was not installed for user " + userId + "!");
3132            }
3133
3134            if (mSafeMode && !ps.isSystem()) {
3135                throw new SecurityException("Package " + packageName + " not a system app!");
3136            }
3137
3138            if (mFrozenPackages.contains(packageName)) {
3139                throw new SecurityException("Package " + packageName + " is currently frozen!");
3140            }
3141
3142            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3143                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3144                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3145            }
3146        }
3147    }
3148
3149    @Override
3150    public boolean isPackageAvailable(String packageName, int userId) {
3151        if (!sUserManager.exists(userId)) return false;
3152        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3153                false /* requireFullPermission */, false /* checkShell */, "is package available");
3154        synchronized (mPackages) {
3155            PackageParser.Package p = mPackages.get(packageName);
3156            if (p != null) {
3157                final PackageSetting ps = (PackageSetting) p.mExtras;
3158                if (ps != null) {
3159                    final PackageUserState state = ps.readUserState(userId);
3160                    if (state != null) {
3161                        return PackageParser.isAvailable(state);
3162                    }
3163                }
3164            }
3165        }
3166        return false;
3167    }
3168
3169    @Override
3170    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3171        if (!sUserManager.exists(userId)) return null;
3172        flags = updateFlagsForPackage(flags, userId, packageName);
3173        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3174                false /* requireFullPermission */, false /* checkShell */, "get package info");
3175        // reader
3176        synchronized (mPackages) {
3177            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3178            PackageParser.Package p = null;
3179            if (matchFactoryOnly) {
3180                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3181                if (ps != null) {
3182                    return generatePackageInfo(ps, flags, userId);
3183                }
3184            }
3185            if (p == null) {
3186                p = mPackages.get(packageName);
3187                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3188                    return null;
3189                }
3190            }
3191            if (DEBUG_PACKAGE_INFO)
3192                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3193            if (p != null) {
3194                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3195            }
3196            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3197                final PackageSetting ps = mSettings.mPackages.get(packageName);
3198                return generatePackageInfo(ps, flags, userId);
3199            }
3200        }
3201        return null;
3202    }
3203
3204    @Override
3205    public String[] currentToCanonicalPackageNames(String[] names) {
3206        String[] out = new String[names.length];
3207        // reader
3208        synchronized (mPackages) {
3209            for (int i=names.length-1; i>=0; i--) {
3210                PackageSetting ps = mSettings.mPackages.get(names[i]);
3211                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3212            }
3213        }
3214        return out;
3215    }
3216
3217    @Override
3218    public String[] canonicalToCurrentPackageNames(String[] names) {
3219        String[] out = new String[names.length];
3220        // reader
3221        synchronized (mPackages) {
3222            for (int i=names.length-1; i>=0; i--) {
3223                String cur = mSettings.mRenamedPackages.get(names[i]);
3224                out[i] = cur != null ? cur : names[i];
3225            }
3226        }
3227        return out;
3228    }
3229
3230    @Override
3231    public int getPackageUid(String packageName, int flags, int userId) {
3232        if (!sUserManager.exists(userId)) return -1;
3233        flags = updateFlagsForPackage(flags, userId, packageName);
3234        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3235                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3236
3237        // reader
3238        synchronized (mPackages) {
3239            final PackageParser.Package p = mPackages.get(packageName);
3240            if (p != null && p.isMatch(flags)) {
3241                return UserHandle.getUid(userId, p.applicationInfo.uid);
3242            }
3243            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3244                final PackageSetting ps = mSettings.mPackages.get(packageName);
3245                if (ps != null && ps.isMatch(flags)) {
3246                    return UserHandle.getUid(userId, ps.appId);
3247                }
3248            }
3249        }
3250
3251        return -1;
3252    }
3253
3254    @Override
3255    public int[] getPackageGids(String packageName, int flags, int userId) {
3256        if (!sUserManager.exists(userId)) return null;
3257        flags = updateFlagsForPackage(flags, userId, packageName);
3258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3259                false /* requireFullPermission */, false /* checkShell */,
3260                "getPackageGids");
3261
3262        // reader
3263        synchronized (mPackages) {
3264            final PackageParser.Package p = mPackages.get(packageName);
3265            if (p != null && p.isMatch(flags)) {
3266                PackageSetting ps = (PackageSetting) p.mExtras;
3267                return ps.getPermissionsState().computeGids(userId);
3268            }
3269            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3270                final PackageSetting ps = mSettings.mPackages.get(packageName);
3271                if (ps != null && ps.isMatch(flags)) {
3272                    return ps.getPermissionsState().computeGids(userId);
3273                }
3274            }
3275        }
3276
3277        return null;
3278    }
3279
3280    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3281        if (bp.perm != null) {
3282            return PackageParser.generatePermissionInfo(bp.perm, flags);
3283        }
3284        PermissionInfo pi = new PermissionInfo();
3285        pi.name = bp.name;
3286        pi.packageName = bp.sourcePackage;
3287        pi.nonLocalizedLabel = bp.name;
3288        pi.protectionLevel = bp.protectionLevel;
3289        return pi;
3290    }
3291
3292    @Override
3293    public PermissionInfo getPermissionInfo(String name, int flags) {
3294        // reader
3295        synchronized (mPackages) {
3296            final BasePermission p = mSettings.mPermissions.get(name);
3297            if (p != null) {
3298                return generatePermissionInfo(p, flags);
3299            }
3300            return null;
3301        }
3302    }
3303
3304    @Override
3305    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3306            int flags) {
3307        // reader
3308        synchronized (mPackages) {
3309            if (group != null && !mPermissionGroups.containsKey(group)) {
3310                // This is thrown as NameNotFoundException
3311                return null;
3312            }
3313
3314            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3315            for (BasePermission p : mSettings.mPermissions.values()) {
3316                if (group == null) {
3317                    if (p.perm == null || p.perm.info.group == null) {
3318                        out.add(generatePermissionInfo(p, flags));
3319                    }
3320                } else {
3321                    if (p.perm != null && group.equals(p.perm.info.group)) {
3322                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3323                    }
3324                }
3325            }
3326            return new ParceledListSlice<>(out);
3327        }
3328    }
3329
3330    @Override
3331    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3332        // reader
3333        synchronized (mPackages) {
3334            return PackageParser.generatePermissionGroupInfo(
3335                    mPermissionGroups.get(name), flags);
3336        }
3337    }
3338
3339    @Override
3340    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3341        // reader
3342        synchronized (mPackages) {
3343            final int N = mPermissionGroups.size();
3344            ArrayList<PermissionGroupInfo> out
3345                    = new ArrayList<PermissionGroupInfo>(N);
3346            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3347                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3348            }
3349            return new ParceledListSlice<>(out);
3350        }
3351    }
3352
3353    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3354            int userId) {
3355        if (!sUserManager.exists(userId)) return null;
3356        PackageSetting ps = mSettings.mPackages.get(packageName);
3357        if (ps != null) {
3358            if (ps.pkg == null) {
3359                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3360                if (pInfo != null) {
3361                    return pInfo.applicationInfo;
3362                }
3363                return null;
3364            }
3365            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3366                    ps.readUserState(userId), userId);
3367        }
3368        return null;
3369    }
3370
3371    @Override
3372    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3373        if (!sUserManager.exists(userId)) return null;
3374        flags = updateFlagsForApplication(flags, userId, packageName);
3375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3376                false /* requireFullPermission */, false /* checkShell */, "get application info");
3377        // writer
3378        synchronized (mPackages) {
3379            PackageParser.Package p = mPackages.get(packageName);
3380            if (DEBUG_PACKAGE_INFO) Log.v(
3381                    TAG, "getApplicationInfo " + packageName
3382                    + ": " + p);
3383            if (p != null) {
3384                PackageSetting ps = mSettings.mPackages.get(packageName);
3385                if (ps == null) return null;
3386                // Note: isEnabledLP() does not apply here - always return info
3387                return PackageParser.generateApplicationInfo(
3388                        p, flags, ps.readUserState(userId), userId);
3389            }
3390            if ("android".equals(packageName)||"system".equals(packageName)) {
3391                return mAndroidApplication;
3392            }
3393            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3394                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3395            }
3396        }
3397        return null;
3398    }
3399
3400    @Override
3401    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3402            final IPackageDataObserver observer) {
3403        mContext.enforceCallingOrSelfPermission(
3404                android.Manifest.permission.CLEAR_APP_CACHE, null);
3405        // Queue up an async operation since clearing cache may take a little while.
3406        mHandler.post(new Runnable() {
3407            public void run() {
3408                mHandler.removeCallbacks(this);
3409                boolean success = true;
3410                synchronized (mInstallLock) {
3411                    try {
3412                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3413                    } catch (InstallerException e) {
3414                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3415                        success = false;
3416                    }
3417                }
3418                if (observer != null) {
3419                    try {
3420                        observer.onRemoveCompleted(null, success);
3421                    } catch (RemoteException e) {
3422                        Slog.w(TAG, "RemoveException when invoking call back");
3423                    }
3424                }
3425            }
3426        });
3427    }
3428
3429    @Override
3430    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3431            final IntentSender pi) {
3432        mContext.enforceCallingOrSelfPermission(
3433                android.Manifest.permission.CLEAR_APP_CACHE, null);
3434        // Queue up an async operation since clearing cache may take a little while.
3435        mHandler.post(new Runnable() {
3436            public void run() {
3437                mHandler.removeCallbacks(this);
3438                boolean success = true;
3439                synchronized (mInstallLock) {
3440                    try {
3441                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3442                    } catch (InstallerException e) {
3443                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3444                        success = false;
3445                    }
3446                }
3447                if(pi != null) {
3448                    try {
3449                        // Callback via pending intent
3450                        int code = success ? 1 : 0;
3451                        pi.sendIntent(null, code, null,
3452                                null, null);
3453                    } catch (SendIntentException e1) {
3454                        Slog.i(TAG, "Failed to send pending intent");
3455                    }
3456                }
3457            }
3458        });
3459    }
3460
3461    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3462        synchronized (mInstallLock) {
3463            try {
3464                mInstaller.freeCache(volumeUuid, freeStorageSize);
3465            } catch (InstallerException e) {
3466                throw new IOException("Failed to free enough space", e);
3467            }
3468        }
3469    }
3470
3471    /**
3472     * Update given flags based on encryption status of current user.
3473     */
3474    private int updateFlags(int flags, int userId) {
3475        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3476                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3477            // Caller expressed an explicit opinion about what encryption
3478            // aware/unaware components they want to see, so fall through and
3479            // give them what they want
3480        } else {
3481            // Caller expressed no opinion, so match based on user state
3482            if (StorageManager.isUserKeyUnlocked(userId)) {
3483                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3484            } else {
3485                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3486            }
3487        }
3488        return flags;
3489    }
3490
3491    /**
3492     * Update given flags when being used to request {@link PackageInfo}.
3493     */
3494    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3495        boolean triaged = true;
3496        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3497                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3498            // Caller is asking for component details, so they'd better be
3499            // asking for specific encryption matching behavior, or be triaged
3500            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3501                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3502                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3503                triaged = false;
3504            }
3505        }
3506        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3507                | PackageManager.MATCH_SYSTEM_ONLY
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        return updateFlags(flags, userId);
3516    }
3517
3518    /**
3519     * Update given flags when being used to request {@link ApplicationInfo}.
3520     */
3521    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3522        return updateFlagsForPackage(flags, userId, cookie);
3523    }
3524
3525    /**
3526     * Update given flags when being used to request {@link ComponentInfo}.
3527     */
3528    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3529        if (cookie instanceof Intent) {
3530            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3531                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3532            }
3533        }
3534
3535        boolean triaged = true;
3536        // Caller is asking for component details, so they'd better be
3537        // asking for specific encryption matching behavior, or be triaged
3538        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3539                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3540                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3541            triaged = false;
3542        }
3543        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3544            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3545                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3546        }
3547
3548        return updateFlags(flags, userId);
3549    }
3550
3551    /**
3552     * Update given flags when being used to request {@link ResolveInfo}.
3553     */
3554    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3555        // Safe mode means we shouldn't match any third-party components
3556        if (mSafeMode) {
3557            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3558        }
3559
3560        return updateFlagsForComponent(flags, userId, cookie);
3561    }
3562
3563    @Override
3564    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3565        if (!sUserManager.exists(userId)) return null;
3566        flags = updateFlagsForComponent(flags, userId, component);
3567        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3568                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3569        synchronized (mPackages) {
3570            PackageParser.Activity a = mActivities.mActivities.get(component);
3571
3572            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3573            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3574                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3575                if (ps == null) return null;
3576                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3577                        userId);
3578            }
3579            if (mResolveComponentName.equals(component)) {
3580                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3581                        new PackageUserState(), userId);
3582            }
3583        }
3584        return null;
3585    }
3586
3587    @Override
3588    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3589            String resolvedType) {
3590        synchronized (mPackages) {
3591            if (component.equals(mResolveComponentName)) {
3592                // The resolver supports EVERYTHING!
3593                return true;
3594            }
3595            PackageParser.Activity a = mActivities.mActivities.get(component);
3596            if (a == null) {
3597                return false;
3598            }
3599            for (int i=0; i<a.intents.size(); i++) {
3600                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3601                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3602                    return true;
3603                }
3604            }
3605            return false;
3606        }
3607    }
3608
3609    @Override
3610    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3611        if (!sUserManager.exists(userId)) return null;
3612        flags = updateFlagsForComponent(flags, userId, component);
3613        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3614                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3615        synchronized (mPackages) {
3616            PackageParser.Activity a = mReceivers.mActivities.get(component);
3617            if (DEBUG_PACKAGE_INFO) Log.v(
3618                TAG, "getReceiverInfo " + component + ": " + a);
3619            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3620                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3621                if (ps == null) return null;
3622                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3623                        userId);
3624            }
3625        }
3626        return null;
3627    }
3628
3629    @Override
3630    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3631        if (!sUserManager.exists(userId)) return null;
3632        flags = updateFlagsForComponent(flags, userId, component);
3633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3634                false /* requireFullPermission */, false /* checkShell */, "get service info");
3635        synchronized (mPackages) {
3636            PackageParser.Service s = mServices.mServices.get(component);
3637            if (DEBUG_PACKAGE_INFO) Log.v(
3638                TAG, "getServiceInfo " + component + ": " + s);
3639            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3640                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3641                if (ps == null) return null;
3642                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3643                        userId);
3644            }
3645        }
3646        return null;
3647    }
3648
3649    @Override
3650    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3651        if (!sUserManager.exists(userId)) return null;
3652        flags = updateFlagsForComponent(flags, userId, component);
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3654                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3655        synchronized (mPackages) {
3656            PackageParser.Provider p = mProviders.mProviders.get(component);
3657            if (DEBUG_PACKAGE_INFO) Log.v(
3658                TAG, "getProviderInfo " + component + ": " + p);
3659            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3660                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3661                if (ps == null) return null;
3662                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3663                        userId);
3664            }
3665        }
3666        return null;
3667    }
3668
3669    @Override
3670    public String[] getSystemSharedLibraryNames() {
3671        Set<String> libSet;
3672        synchronized (mPackages) {
3673            libSet = mSharedLibraries.keySet();
3674            int size = libSet.size();
3675            if (size > 0) {
3676                String[] libs = new String[size];
3677                libSet.toArray(libs);
3678                return libs;
3679            }
3680        }
3681        return null;
3682    }
3683
3684    @Override
3685    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3686        synchronized (mPackages) {
3687            return mServicesSystemSharedLibraryPackageName;
3688        }
3689    }
3690
3691    @Override
3692    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3693        synchronized (mPackages) {
3694            return mSharedSystemSharedLibraryPackageName;
3695        }
3696    }
3697
3698    @Override
3699    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3700        synchronized (mPackages) {
3701            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3702
3703            final FeatureInfo fi = new FeatureInfo();
3704            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3705                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3706            res.add(fi);
3707
3708            return new ParceledListSlice<>(res);
3709        }
3710    }
3711
3712    @Override
3713    public boolean hasSystemFeature(String name, int version) {
3714        synchronized (mPackages) {
3715            final FeatureInfo feat = mAvailableFeatures.get(name);
3716            if (feat == null) {
3717                return false;
3718            } else {
3719                return feat.version >= version;
3720            }
3721        }
3722    }
3723
3724    @Override
3725    public int checkPermission(String permName, String pkgName, int userId) {
3726        if (!sUserManager.exists(userId)) {
3727            return PackageManager.PERMISSION_DENIED;
3728        }
3729
3730        synchronized (mPackages) {
3731            final PackageParser.Package p = mPackages.get(pkgName);
3732            if (p != null && p.mExtras != null) {
3733                final PackageSetting ps = (PackageSetting) p.mExtras;
3734                final PermissionsState permissionsState = ps.getPermissionsState();
3735                if (permissionsState.hasPermission(permName, userId)) {
3736                    return PackageManager.PERMISSION_GRANTED;
3737                }
3738                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3739                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3740                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3741                    return PackageManager.PERMISSION_GRANTED;
3742                }
3743            }
3744        }
3745
3746        return PackageManager.PERMISSION_DENIED;
3747    }
3748
3749    @Override
3750    public int checkUidPermission(String permName, int uid) {
3751        final int userId = UserHandle.getUserId(uid);
3752
3753        if (!sUserManager.exists(userId)) {
3754            return PackageManager.PERMISSION_DENIED;
3755        }
3756
3757        synchronized (mPackages) {
3758            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3759            if (obj != null) {
3760                final SettingBase ps = (SettingBase) obj;
3761                final PermissionsState permissionsState = ps.getPermissionsState();
3762                if (permissionsState.hasPermission(permName, userId)) {
3763                    return PackageManager.PERMISSION_GRANTED;
3764                }
3765                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3766                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3767                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3768                    return PackageManager.PERMISSION_GRANTED;
3769                }
3770            } else {
3771                ArraySet<String> perms = mSystemPermissions.get(uid);
3772                if (perms != null) {
3773                    if (perms.contains(permName)) {
3774                        return PackageManager.PERMISSION_GRANTED;
3775                    }
3776                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3777                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3778                        return PackageManager.PERMISSION_GRANTED;
3779                    }
3780                }
3781            }
3782        }
3783
3784        return PackageManager.PERMISSION_DENIED;
3785    }
3786
3787    @Override
3788    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3789        if (UserHandle.getCallingUserId() != userId) {
3790            mContext.enforceCallingPermission(
3791                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3792                    "isPermissionRevokedByPolicy for user " + userId);
3793        }
3794
3795        if (checkPermission(permission, packageName, userId)
3796                == PackageManager.PERMISSION_GRANTED) {
3797            return false;
3798        }
3799
3800        final long identity = Binder.clearCallingIdentity();
3801        try {
3802            final int flags = getPermissionFlags(permission, packageName, userId);
3803            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3804        } finally {
3805            Binder.restoreCallingIdentity(identity);
3806        }
3807    }
3808
3809    @Override
3810    public String getPermissionControllerPackageName() {
3811        synchronized (mPackages) {
3812            return mRequiredInstallerPackage;
3813        }
3814    }
3815
3816    /**
3817     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3818     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3819     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3820     * @param message the message to log on security exception
3821     */
3822    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3823            boolean checkShell, String message) {
3824        if (userId < 0) {
3825            throw new IllegalArgumentException("Invalid userId " + userId);
3826        }
3827        if (checkShell) {
3828            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3829        }
3830        if (userId == UserHandle.getUserId(callingUid)) return;
3831        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3832            if (requireFullPermission) {
3833                mContext.enforceCallingOrSelfPermission(
3834                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3835            } else {
3836                try {
3837                    mContext.enforceCallingOrSelfPermission(
3838                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3839                } catch (SecurityException se) {
3840                    mContext.enforceCallingOrSelfPermission(
3841                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3842                }
3843            }
3844        }
3845    }
3846
3847    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3848        if (callingUid == Process.SHELL_UID) {
3849            if (userHandle >= 0
3850                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3851                throw new SecurityException("Shell does not have permission to access user "
3852                        + userHandle);
3853            } else if (userHandle < 0) {
3854                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3855                        + Debug.getCallers(3));
3856            }
3857        }
3858    }
3859
3860    private BasePermission findPermissionTreeLP(String permName) {
3861        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3862            if (permName.startsWith(bp.name) &&
3863                    permName.length() > bp.name.length() &&
3864                    permName.charAt(bp.name.length()) == '.') {
3865                return bp;
3866            }
3867        }
3868        return null;
3869    }
3870
3871    private BasePermission checkPermissionTreeLP(String permName) {
3872        if (permName != null) {
3873            BasePermission bp = findPermissionTreeLP(permName);
3874            if (bp != null) {
3875                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3876                    return bp;
3877                }
3878                throw new SecurityException("Calling uid "
3879                        + Binder.getCallingUid()
3880                        + " is not allowed to add to permission tree "
3881                        + bp.name + " owned by uid " + bp.uid);
3882            }
3883        }
3884        throw new SecurityException("No permission tree found for " + permName);
3885    }
3886
3887    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3888        if (s1 == null) {
3889            return s2 == null;
3890        }
3891        if (s2 == null) {
3892            return false;
3893        }
3894        if (s1.getClass() != s2.getClass()) {
3895            return false;
3896        }
3897        return s1.equals(s2);
3898    }
3899
3900    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3901        if (pi1.icon != pi2.icon) return false;
3902        if (pi1.logo != pi2.logo) return false;
3903        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3904        if (!compareStrings(pi1.name, pi2.name)) return false;
3905        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3906        // We'll take care of setting this one.
3907        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3908        // These are not currently stored in settings.
3909        //if (!compareStrings(pi1.group, pi2.group)) return false;
3910        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3911        //if (pi1.labelRes != pi2.labelRes) return false;
3912        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3913        return true;
3914    }
3915
3916    int permissionInfoFootprint(PermissionInfo info) {
3917        int size = info.name.length();
3918        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3919        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3920        return size;
3921    }
3922
3923    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3924        int size = 0;
3925        for (BasePermission perm : mSettings.mPermissions.values()) {
3926            if (perm.uid == tree.uid) {
3927                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3928            }
3929        }
3930        return size;
3931    }
3932
3933    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3934        // We calculate the max size of permissions defined by this uid and throw
3935        // if that plus the size of 'info' would exceed our stated maximum.
3936        if (tree.uid != Process.SYSTEM_UID) {
3937            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3938            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3939                throw new SecurityException("Permission tree size cap exceeded");
3940            }
3941        }
3942    }
3943
3944    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3945        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3946            throw new SecurityException("Label must be specified in permission");
3947        }
3948        BasePermission tree = checkPermissionTreeLP(info.name);
3949        BasePermission bp = mSettings.mPermissions.get(info.name);
3950        boolean added = bp == null;
3951        boolean changed = true;
3952        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3953        if (added) {
3954            enforcePermissionCapLocked(info, tree);
3955            bp = new BasePermission(info.name, tree.sourcePackage,
3956                    BasePermission.TYPE_DYNAMIC);
3957        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3958            throw new SecurityException(
3959                    "Not allowed to modify non-dynamic permission "
3960                    + info.name);
3961        } else {
3962            if (bp.protectionLevel == fixedLevel
3963                    && bp.perm.owner.equals(tree.perm.owner)
3964                    && bp.uid == tree.uid
3965                    && comparePermissionInfos(bp.perm.info, info)) {
3966                changed = false;
3967            }
3968        }
3969        bp.protectionLevel = fixedLevel;
3970        info = new PermissionInfo(info);
3971        info.protectionLevel = fixedLevel;
3972        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3973        bp.perm.info.packageName = tree.perm.info.packageName;
3974        bp.uid = tree.uid;
3975        if (added) {
3976            mSettings.mPermissions.put(info.name, bp);
3977        }
3978        if (changed) {
3979            if (!async) {
3980                mSettings.writeLPr();
3981            } else {
3982                scheduleWriteSettingsLocked();
3983            }
3984        }
3985        return added;
3986    }
3987
3988    @Override
3989    public boolean addPermission(PermissionInfo info) {
3990        synchronized (mPackages) {
3991            return addPermissionLocked(info, false);
3992        }
3993    }
3994
3995    @Override
3996    public boolean addPermissionAsync(PermissionInfo info) {
3997        synchronized (mPackages) {
3998            return addPermissionLocked(info, true);
3999        }
4000    }
4001
4002    @Override
4003    public void removePermission(String name) {
4004        synchronized (mPackages) {
4005            checkPermissionTreeLP(name);
4006            BasePermission bp = mSettings.mPermissions.get(name);
4007            if (bp != null) {
4008                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4009                    throw new SecurityException(
4010                            "Not allowed to modify non-dynamic permission "
4011                            + name);
4012                }
4013                mSettings.mPermissions.remove(name);
4014                mSettings.writeLPr();
4015            }
4016        }
4017    }
4018
4019    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4020            BasePermission bp) {
4021        int index = pkg.requestedPermissions.indexOf(bp.name);
4022        if (index == -1) {
4023            throw new SecurityException("Package " + pkg.packageName
4024                    + " has not requested permission " + bp.name);
4025        }
4026        if (!bp.isRuntime() && !bp.isDevelopment()) {
4027            throw new SecurityException("Permission " + bp.name
4028                    + " is not a changeable permission type");
4029        }
4030    }
4031
4032    @Override
4033    public void grantRuntimePermission(String packageName, String name, final int userId) {
4034        if (!sUserManager.exists(userId)) {
4035            Log.e(TAG, "No such user:" + userId);
4036            return;
4037        }
4038
4039        mContext.enforceCallingOrSelfPermission(
4040                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4041                "grantRuntimePermission");
4042
4043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4044                true /* requireFullPermission */, true /* checkShell */,
4045                "grantRuntimePermission");
4046
4047        final int uid;
4048        final SettingBase sb;
4049
4050        synchronized (mPackages) {
4051            final PackageParser.Package pkg = mPackages.get(packageName);
4052            if (pkg == null) {
4053                throw new IllegalArgumentException("Unknown package: " + packageName);
4054            }
4055
4056            final BasePermission bp = mSettings.mPermissions.get(name);
4057            if (bp == null) {
4058                throw new IllegalArgumentException("Unknown permission: " + name);
4059            }
4060
4061            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4062
4063            // If a permission review is required for legacy apps we represent
4064            // their permissions as always granted runtime ones since we need
4065            // to keep the review required permission flag per user while an
4066            // install permission's state is shared across all users.
4067            if (Build.PERMISSIONS_REVIEW_REQUIRED
4068                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4069                    && bp.isRuntime()) {
4070                return;
4071            }
4072
4073            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4074            sb = (SettingBase) pkg.mExtras;
4075            if (sb == null) {
4076                throw new IllegalArgumentException("Unknown package: " + packageName);
4077            }
4078
4079            final PermissionsState permissionsState = sb.getPermissionsState();
4080
4081            final int flags = permissionsState.getPermissionFlags(name, userId);
4082            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4083                throw new SecurityException("Cannot grant system fixed permission "
4084                        + name + " for package " + packageName);
4085            }
4086
4087            if (bp.isDevelopment()) {
4088                // Development permissions must be handled specially, since they are not
4089                // normal runtime permissions.  For now they apply to all users.
4090                if (permissionsState.grantInstallPermission(bp) !=
4091                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4092                    scheduleWriteSettingsLocked();
4093                }
4094                return;
4095            }
4096
4097            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4098                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4099                return;
4100            }
4101
4102            final int result = permissionsState.grantRuntimePermission(bp, userId);
4103            switch (result) {
4104                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4105                    return;
4106                }
4107
4108                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4109                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4110                    mHandler.post(new Runnable() {
4111                        @Override
4112                        public void run() {
4113                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4114                        }
4115                    });
4116                }
4117                break;
4118            }
4119
4120            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4121
4122            // Not critical if that is lost - app has to request again.
4123            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4124        }
4125
4126        // Only need to do this if user is initialized. Otherwise it's a new user
4127        // and there are no processes running as the user yet and there's no need
4128        // to make an expensive call to remount processes for the changed permissions.
4129        if (READ_EXTERNAL_STORAGE.equals(name)
4130                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4131            final long token = Binder.clearCallingIdentity();
4132            try {
4133                if (sUserManager.isInitialized(userId)) {
4134                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4135                            MountServiceInternal.class);
4136                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4137                }
4138            } finally {
4139                Binder.restoreCallingIdentity(token);
4140            }
4141        }
4142    }
4143
4144    @Override
4145    public void revokeRuntimePermission(String packageName, String name, int userId) {
4146        if (!sUserManager.exists(userId)) {
4147            Log.e(TAG, "No such user:" + userId);
4148            return;
4149        }
4150
4151        mContext.enforceCallingOrSelfPermission(
4152                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4153                "revokeRuntimePermission");
4154
4155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4156                true /* requireFullPermission */, true /* checkShell */,
4157                "revokeRuntimePermission");
4158
4159        final int appId;
4160
4161        synchronized (mPackages) {
4162            final PackageParser.Package pkg = mPackages.get(packageName);
4163            if (pkg == null) {
4164                throw new IllegalArgumentException("Unknown package: " + packageName);
4165            }
4166
4167            final BasePermission bp = mSettings.mPermissions.get(name);
4168            if (bp == null) {
4169                throw new IllegalArgumentException("Unknown permission: " + name);
4170            }
4171
4172            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4173
4174            // If a permission review is required for legacy apps we represent
4175            // their permissions as always granted runtime ones since we need
4176            // to keep the review required permission flag per user while an
4177            // install permission's state is shared across all users.
4178            if (Build.PERMISSIONS_REVIEW_REQUIRED
4179                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4180                    && bp.isRuntime()) {
4181                return;
4182            }
4183
4184            SettingBase sb = (SettingBase) pkg.mExtras;
4185            if (sb == null) {
4186                throw new IllegalArgumentException("Unknown package: " + packageName);
4187            }
4188
4189            final PermissionsState permissionsState = sb.getPermissionsState();
4190
4191            final int flags = permissionsState.getPermissionFlags(name, userId);
4192            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4193                throw new SecurityException("Cannot revoke system fixed permission "
4194                        + name + " for package " + packageName);
4195            }
4196
4197            if (bp.isDevelopment()) {
4198                // Development permissions must be handled specially, since they are not
4199                // normal runtime permissions.  For now they apply to all users.
4200                if (permissionsState.revokeInstallPermission(bp) !=
4201                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4202                    scheduleWriteSettingsLocked();
4203                }
4204                return;
4205            }
4206
4207            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4208                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4209                return;
4210            }
4211
4212            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4213
4214            // Critical, after this call app should never have the permission.
4215            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4216
4217            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4218        }
4219
4220        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4221    }
4222
4223    @Override
4224    public void resetRuntimePermissions() {
4225        mContext.enforceCallingOrSelfPermission(
4226                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4227                "revokeRuntimePermission");
4228
4229        int callingUid = Binder.getCallingUid();
4230        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4231            mContext.enforceCallingOrSelfPermission(
4232                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4233                    "resetRuntimePermissions");
4234        }
4235
4236        synchronized (mPackages) {
4237            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4238            for (int userId : UserManagerService.getInstance().getUserIds()) {
4239                final int packageCount = mPackages.size();
4240                for (int i = 0; i < packageCount; i++) {
4241                    PackageParser.Package pkg = mPackages.valueAt(i);
4242                    if (!(pkg.mExtras instanceof PackageSetting)) {
4243                        continue;
4244                    }
4245                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4246                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4247                }
4248            }
4249        }
4250    }
4251
4252    @Override
4253    public int getPermissionFlags(String name, String packageName, int userId) {
4254        if (!sUserManager.exists(userId)) {
4255            return 0;
4256        }
4257
4258        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4259
4260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4261                true /* requireFullPermission */, false /* checkShell */,
4262                "getPermissionFlags");
4263
4264        synchronized (mPackages) {
4265            final PackageParser.Package pkg = mPackages.get(packageName);
4266            if (pkg == null) {
4267                throw new IllegalArgumentException("Unknown package: " + packageName);
4268            }
4269
4270            final BasePermission bp = mSettings.mPermissions.get(name);
4271            if (bp == null) {
4272                throw new IllegalArgumentException("Unknown permission: " + name);
4273            }
4274
4275            SettingBase sb = (SettingBase) pkg.mExtras;
4276            if (sb == null) {
4277                throw new IllegalArgumentException("Unknown package: " + packageName);
4278            }
4279
4280            PermissionsState permissionsState = sb.getPermissionsState();
4281            return permissionsState.getPermissionFlags(name, userId);
4282        }
4283    }
4284
4285    @Override
4286    public void updatePermissionFlags(String name, String packageName, int flagMask,
4287            int flagValues, int userId) {
4288        if (!sUserManager.exists(userId)) {
4289            return;
4290        }
4291
4292        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4293
4294        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4295                true /* requireFullPermission */, true /* checkShell */,
4296                "updatePermissionFlags");
4297
4298        // Only the system can change these flags and nothing else.
4299        if (getCallingUid() != Process.SYSTEM_UID) {
4300            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4301            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4302            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4303            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4304            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4305        }
4306
4307        synchronized (mPackages) {
4308            final PackageParser.Package pkg = mPackages.get(packageName);
4309            if (pkg == null) {
4310                throw new IllegalArgumentException("Unknown package: " + packageName);
4311            }
4312
4313            final BasePermission bp = mSettings.mPermissions.get(name);
4314            if (bp == null) {
4315                throw new IllegalArgumentException("Unknown permission: " + name);
4316            }
4317
4318            SettingBase sb = (SettingBase) pkg.mExtras;
4319            if (sb == null) {
4320                throw new IllegalArgumentException("Unknown package: " + packageName);
4321            }
4322
4323            PermissionsState permissionsState = sb.getPermissionsState();
4324
4325            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4326
4327            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4328                // Install and runtime permissions are stored in different places,
4329                // so figure out what permission changed and persist the change.
4330                if (permissionsState.getInstallPermissionState(name) != null) {
4331                    scheduleWriteSettingsLocked();
4332                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4333                        || hadState) {
4334                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4335                }
4336            }
4337        }
4338    }
4339
4340    /**
4341     * Update the permission flags for all packages and runtime permissions of a user in order
4342     * to allow device or profile owner to remove POLICY_FIXED.
4343     */
4344    @Override
4345    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4346        if (!sUserManager.exists(userId)) {
4347            return;
4348        }
4349
4350        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4351
4352        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4353                true /* requireFullPermission */, true /* checkShell */,
4354                "updatePermissionFlagsForAllApps");
4355
4356        // Only the system can change system fixed flags.
4357        if (getCallingUid() != Process.SYSTEM_UID) {
4358            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4359            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4360        }
4361
4362        synchronized (mPackages) {
4363            boolean changed = false;
4364            final int packageCount = mPackages.size();
4365            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4366                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4367                SettingBase sb = (SettingBase) pkg.mExtras;
4368                if (sb == null) {
4369                    continue;
4370                }
4371                PermissionsState permissionsState = sb.getPermissionsState();
4372                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4373                        userId, flagMask, flagValues);
4374            }
4375            if (changed) {
4376                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4377            }
4378        }
4379    }
4380
4381    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4382        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4383                != PackageManager.PERMISSION_GRANTED
4384            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4385                != PackageManager.PERMISSION_GRANTED) {
4386            throw new SecurityException(message + " requires "
4387                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4388                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4389        }
4390    }
4391
4392    @Override
4393    public boolean shouldShowRequestPermissionRationale(String permissionName,
4394            String packageName, int userId) {
4395        if (UserHandle.getCallingUserId() != userId) {
4396            mContext.enforceCallingPermission(
4397                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4398                    "canShowRequestPermissionRationale for user " + userId);
4399        }
4400
4401        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4402        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4403            return false;
4404        }
4405
4406        if (checkPermission(permissionName, packageName, userId)
4407                == PackageManager.PERMISSION_GRANTED) {
4408            return false;
4409        }
4410
4411        final int flags;
4412
4413        final long identity = Binder.clearCallingIdentity();
4414        try {
4415            flags = getPermissionFlags(permissionName,
4416                    packageName, userId);
4417        } finally {
4418            Binder.restoreCallingIdentity(identity);
4419        }
4420
4421        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4422                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4423                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4424
4425        if ((flags & fixedFlags) != 0) {
4426            return false;
4427        }
4428
4429        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4430    }
4431
4432    @Override
4433    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4434        mContext.enforceCallingOrSelfPermission(
4435                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4436                "addOnPermissionsChangeListener");
4437
4438        synchronized (mPackages) {
4439            mOnPermissionChangeListeners.addListenerLocked(listener);
4440        }
4441    }
4442
4443    @Override
4444    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4445        synchronized (mPackages) {
4446            mOnPermissionChangeListeners.removeListenerLocked(listener);
4447        }
4448    }
4449
4450    @Override
4451    public boolean isProtectedBroadcast(String actionName) {
4452        synchronized (mPackages) {
4453            if (mProtectedBroadcasts.contains(actionName)) {
4454                return true;
4455            } else if (actionName != null) {
4456                // TODO: remove these terrible hacks
4457                if (actionName.startsWith("android.net.netmon.lingerExpired")
4458                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4459                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4460                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4461                    return true;
4462                }
4463            }
4464        }
4465        return false;
4466    }
4467
4468    @Override
4469    public int checkSignatures(String pkg1, String pkg2) {
4470        synchronized (mPackages) {
4471            final PackageParser.Package p1 = mPackages.get(pkg1);
4472            final PackageParser.Package p2 = mPackages.get(pkg2);
4473            if (p1 == null || p1.mExtras == null
4474                    || p2 == null || p2.mExtras == null) {
4475                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4476            }
4477            return compareSignatures(p1.mSignatures, p2.mSignatures);
4478        }
4479    }
4480
4481    @Override
4482    public int checkUidSignatures(int uid1, int uid2) {
4483        // Map to base uids.
4484        uid1 = UserHandle.getAppId(uid1);
4485        uid2 = UserHandle.getAppId(uid2);
4486        // reader
4487        synchronized (mPackages) {
4488            Signature[] s1;
4489            Signature[] s2;
4490            Object obj = mSettings.getUserIdLPr(uid1);
4491            if (obj != null) {
4492                if (obj instanceof SharedUserSetting) {
4493                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4494                } else if (obj instanceof PackageSetting) {
4495                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4496                } else {
4497                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4498                }
4499            } else {
4500                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4501            }
4502            obj = mSettings.getUserIdLPr(uid2);
4503            if (obj != null) {
4504                if (obj instanceof SharedUserSetting) {
4505                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4506                } else if (obj instanceof PackageSetting) {
4507                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4508                } else {
4509                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4510                }
4511            } else {
4512                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4513            }
4514            return compareSignatures(s1, s2);
4515        }
4516    }
4517
4518    /**
4519     * This method should typically only be used when granting or revoking
4520     * permissions, since the app may immediately restart after this call.
4521     * <p>
4522     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4523     * guard your work against the app being relaunched.
4524     */
4525    private void killUid(int appId, int userId, String reason) {
4526        final long identity = Binder.clearCallingIdentity();
4527        try {
4528            IActivityManager am = ActivityManagerNative.getDefault();
4529            if (am != null) {
4530                try {
4531                    am.killUid(appId, userId, reason);
4532                } catch (RemoteException e) {
4533                    /* ignore - same process */
4534                }
4535            }
4536        } finally {
4537            Binder.restoreCallingIdentity(identity);
4538        }
4539    }
4540
4541    /**
4542     * Compares two sets of signatures. Returns:
4543     * <br />
4544     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4545     * <br />
4546     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4547     * <br />
4548     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4553     */
4554    static int compareSignatures(Signature[] s1, Signature[] s2) {
4555        if (s1 == null) {
4556            return s2 == null
4557                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4558                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4559        }
4560
4561        if (s2 == null) {
4562            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4563        }
4564
4565        if (s1.length != s2.length) {
4566            return PackageManager.SIGNATURE_NO_MATCH;
4567        }
4568
4569        // Since both signature sets are of size 1, we can compare without HashSets.
4570        if (s1.length == 1) {
4571            return s1[0].equals(s2[0]) ?
4572                    PackageManager.SIGNATURE_MATCH :
4573                    PackageManager.SIGNATURE_NO_MATCH;
4574        }
4575
4576        ArraySet<Signature> set1 = new ArraySet<Signature>();
4577        for (Signature sig : s1) {
4578            set1.add(sig);
4579        }
4580        ArraySet<Signature> set2 = new ArraySet<Signature>();
4581        for (Signature sig : s2) {
4582            set2.add(sig);
4583        }
4584        // Make sure s2 contains all signatures in s1.
4585        if (set1.equals(set2)) {
4586            return PackageManager.SIGNATURE_MATCH;
4587        }
4588        return PackageManager.SIGNATURE_NO_MATCH;
4589    }
4590
4591    /**
4592     * If the database version for this type of package (internal storage or
4593     * external storage) is less than the version where package signatures
4594     * were updated, return true.
4595     */
4596    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4597        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4598        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4599    }
4600
4601    /**
4602     * Used for backward compatibility to make sure any packages with
4603     * certificate chains get upgraded to the new style. {@code existingSigs}
4604     * will be in the old format (since they were stored on disk from before the
4605     * system upgrade) and {@code scannedSigs} will be in the newer format.
4606     */
4607    private int compareSignaturesCompat(PackageSignatures existingSigs,
4608            PackageParser.Package scannedPkg) {
4609        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4610            return PackageManager.SIGNATURE_NO_MATCH;
4611        }
4612
4613        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4614        for (Signature sig : existingSigs.mSignatures) {
4615            existingSet.add(sig);
4616        }
4617        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4618        for (Signature sig : scannedPkg.mSignatures) {
4619            try {
4620                Signature[] chainSignatures = sig.getChainSignatures();
4621                for (Signature chainSig : chainSignatures) {
4622                    scannedCompatSet.add(chainSig);
4623                }
4624            } catch (CertificateEncodingException e) {
4625                scannedCompatSet.add(sig);
4626            }
4627        }
4628        /*
4629         * Make sure the expanded scanned set contains all signatures in the
4630         * existing one.
4631         */
4632        if (scannedCompatSet.equals(existingSet)) {
4633            // Migrate the old signatures to the new scheme.
4634            existingSigs.assignSignatures(scannedPkg.mSignatures);
4635            // The new KeySets will be re-added later in the scanning process.
4636            synchronized (mPackages) {
4637                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4638            }
4639            return PackageManager.SIGNATURE_MATCH;
4640        }
4641        return PackageManager.SIGNATURE_NO_MATCH;
4642    }
4643
4644    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4645        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4646        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4647    }
4648
4649    private int compareSignaturesRecover(PackageSignatures existingSigs,
4650            PackageParser.Package scannedPkg) {
4651        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4652            return PackageManager.SIGNATURE_NO_MATCH;
4653        }
4654
4655        String msg = null;
4656        try {
4657            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4658                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4659                        + scannedPkg.packageName);
4660                return PackageManager.SIGNATURE_MATCH;
4661            }
4662        } catch (CertificateException e) {
4663            msg = e.getMessage();
4664        }
4665
4666        logCriticalInfo(Log.INFO,
4667                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4668        return PackageManager.SIGNATURE_NO_MATCH;
4669    }
4670
4671    @Override
4672    public List<String> getAllPackages() {
4673        synchronized (mPackages) {
4674            return new ArrayList<String>(mPackages.keySet());
4675        }
4676    }
4677
4678    @Override
4679    public String[] getPackagesForUid(int uid) {
4680        uid = UserHandle.getAppId(uid);
4681        // reader
4682        synchronized (mPackages) {
4683            Object obj = mSettings.getUserIdLPr(uid);
4684            if (obj instanceof SharedUserSetting) {
4685                final SharedUserSetting sus = (SharedUserSetting) obj;
4686                final int N = sus.packages.size();
4687                final String[] res = new String[N];
4688                final Iterator<PackageSetting> it = sus.packages.iterator();
4689                int i = 0;
4690                while (it.hasNext()) {
4691                    res[i++] = it.next().name;
4692                }
4693                return res;
4694            } else if (obj instanceof PackageSetting) {
4695                final PackageSetting ps = (PackageSetting) obj;
4696                return new String[] { ps.name };
4697            }
4698        }
4699        return null;
4700    }
4701
4702    @Override
4703    public String getNameForUid(int uid) {
4704        // reader
4705        synchronized (mPackages) {
4706            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4707            if (obj instanceof SharedUserSetting) {
4708                final SharedUserSetting sus = (SharedUserSetting) obj;
4709                return sus.name + ":" + sus.userId;
4710            } else if (obj instanceof PackageSetting) {
4711                final PackageSetting ps = (PackageSetting) obj;
4712                return ps.name;
4713            }
4714        }
4715        return null;
4716    }
4717
4718    @Override
4719    public int getUidForSharedUser(String sharedUserName) {
4720        if(sharedUserName == null) {
4721            return -1;
4722        }
4723        // reader
4724        synchronized (mPackages) {
4725            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4726            if (suid == null) {
4727                return -1;
4728            }
4729            return suid.userId;
4730        }
4731    }
4732
4733    @Override
4734    public int getFlagsForUid(int uid) {
4735        synchronized (mPackages) {
4736            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4737            if (obj instanceof SharedUserSetting) {
4738                final SharedUserSetting sus = (SharedUserSetting) obj;
4739                return sus.pkgFlags;
4740            } else if (obj instanceof PackageSetting) {
4741                final PackageSetting ps = (PackageSetting) obj;
4742                return ps.pkgFlags;
4743            }
4744        }
4745        return 0;
4746    }
4747
4748    @Override
4749    public int getPrivateFlagsForUid(int uid) {
4750        synchronized (mPackages) {
4751            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4752            if (obj instanceof SharedUserSetting) {
4753                final SharedUserSetting sus = (SharedUserSetting) obj;
4754                return sus.pkgPrivateFlags;
4755            } else if (obj instanceof PackageSetting) {
4756                final PackageSetting ps = (PackageSetting) obj;
4757                return ps.pkgPrivateFlags;
4758            }
4759        }
4760        return 0;
4761    }
4762
4763    @Override
4764    public boolean isUidPrivileged(int uid) {
4765        uid = UserHandle.getAppId(uid);
4766        // reader
4767        synchronized (mPackages) {
4768            Object obj = mSettings.getUserIdLPr(uid);
4769            if (obj instanceof SharedUserSetting) {
4770                final SharedUserSetting sus = (SharedUserSetting) obj;
4771                final Iterator<PackageSetting> it = sus.packages.iterator();
4772                while (it.hasNext()) {
4773                    if (it.next().isPrivileged()) {
4774                        return true;
4775                    }
4776                }
4777            } else if (obj instanceof PackageSetting) {
4778                final PackageSetting ps = (PackageSetting) obj;
4779                return ps.isPrivileged();
4780            }
4781        }
4782        return false;
4783    }
4784
4785    @Override
4786    public String[] getAppOpPermissionPackages(String permissionName) {
4787        synchronized (mPackages) {
4788            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4789            if (pkgs == null) {
4790                return null;
4791            }
4792            return pkgs.toArray(new String[pkgs.size()]);
4793        }
4794    }
4795
4796    @Override
4797    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4798            int flags, int userId) {
4799        try {
4800            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4801
4802            if (!sUserManager.exists(userId)) return null;
4803            flags = updateFlagsForResolve(flags, userId, intent);
4804            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4805                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4806
4807            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4808            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4809                    flags, userId);
4810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4811
4812            final ResolveInfo bestChoice =
4813                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4814
4815            if (isEphemeralAllowed(intent, query, userId)) {
4816                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4817                final EphemeralResolveInfo ai =
4818                        getEphemeralResolveInfo(intent, resolvedType, userId);
4819                if (ai != null) {
4820                    if (DEBUG_EPHEMERAL) {
4821                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4822                    }
4823                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4824                    bestChoice.ephemeralResolveInfo = ai;
4825                }
4826                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4827            }
4828            return bestChoice;
4829        } finally {
4830            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4831        }
4832    }
4833
4834    @Override
4835    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4836            IntentFilter filter, int match, ComponentName activity) {
4837        final int userId = UserHandle.getCallingUserId();
4838        if (DEBUG_PREFERRED) {
4839            Log.v(TAG, "setLastChosenActivity intent=" + intent
4840                + " resolvedType=" + resolvedType
4841                + " flags=" + flags
4842                + " filter=" + filter
4843                + " match=" + match
4844                + " activity=" + activity);
4845            filter.dump(new PrintStreamPrinter(System.out), "    ");
4846        }
4847        intent.setComponent(null);
4848        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4849                userId);
4850        // Find any earlier preferred or last chosen entries and nuke them
4851        findPreferredActivity(intent, resolvedType,
4852                flags, query, 0, false, true, false, userId);
4853        // Add the new activity as the last chosen for this filter
4854        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4855                "Setting last chosen");
4856    }
4857
4858    @Override
4859    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4860        final int userId = UserHandle.getCallingUserId();
4861        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4862        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4863                userId);
4864        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4865                false, false, false, userId);
4866    }
4867
4868
4869    private boolean isEphemeralAllowed(
4870            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4871        // Short circuit and return early if possible.
4872        if (DISABLE_EPHEMERAL_APPS) {
4873            return false;
4874        }
4875        final int callingUser = UserHandle.getCallingUserId();
4876        if (callingUser != UserHandle.USER_SYSTEM) {
4877            return false;
4878        }
4879        if (mEphemeralResolverConnection == null) {
4880            return false;
4881        }
4882        if (intent.getComponent() != null) {
4883            return false;
4884        }
4885        if (intent.getPackage() != null) {
4886            return false;
4887        }
4888        final boolean isWebUri = hasWebURI(intent);
4889        if (!isWebUri) {
4890            return false;
4891        }
4892        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4893        synchronized (mPackages) {
4894            final int count = resolvedActivites.size();
4895            for (int n = 0; n < count; n++) {
4896                ResolveInfo info = resolvedActivites.get(n);
4897                String packageName = info.activityInfo.packageName;
4898                PackageSetting ps = mSettings.mPackages.get(packageName);
4899                if (ps != null) {
4900                    // Try to get the status from User settings first
4901                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4902                    int status = (int) (packedStatus >> 32);
4903                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4904                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4905                        if (DEBUG_EPHEMERAL) {
4906                            Slog.v(TAG, "DENY ephemeral apps;"
4907                                + " pkg: " + packageName + ", status: " + status);
4908                        }
4909                        return false;
4910                    }
4911                }
4912            }
4913        }
4914        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4915        return true;
4916    }
4917
4918    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4919            int userId) {
4920        MessageDigest digest = null;
4921        try {
4922            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4923        } catch (NoSuchAlgorithmException e) {
4924            // If we can't create a digest, ignore ephemeral apps.
4925            return null;
4926        }
4927
4928        final byte[] hostBytes = intent.getData().getHost().getBytes();
4929        final byte[] digestBytes = digest.digest(hostBytes);
4930        int shaPrefix =
4931                digestBytes[0] << 24
4932                | digestBytes[1] << 16
4933                | digestBytes[2] << 8
4934                | digestBytes[3] << 0;
4935        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4936                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4937        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4938            // No hash prefix match; there are no ephemeral apps for this domain.
4939            return null;
4940        }
4941        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4942            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4943            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4944                continue;
4945            }
4946            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4947            // No filters; this should never happen.
4948            if (filters.isEmpty()) {
4949                continue;
4950            }
4951            // We have a domain match; resolve the filters to see if anything matches.
4952            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4953            for (int j = filters.size() - 1; j >= 0; --j) {
4954                final EphemeralResolveIntentInfo intentInfo =
4955                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4956                ephemeralResolver.addFilter(intentInfo);
4957            }
4958            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4959                    intent, resolvedType, false /*defaultOnly*/, userId);
4960            if (!matchedResolveInfoList.isEmpty()) {
4961                return matchedResolveInfoList.get(0);
4962            }
4963        }
4964        // Hash or filter mis-match; no ephemeral apps for this domain.
4965        return null;
4966    }
4967
4968    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4969            int flags, List<ResolveInfo> query, int userId) {
4970        if (query != null) {
4971            final int N = query.size();
4972            if (N == 1) {
4973                return query.get(0);
4974            } else if (N > 1) {
4975                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4976                // If there is more than one activity with the same priority,
4977                // then let the user decide between them.
4978                ResolveInfo r0 = query.get(0);
4979                ResolveInfo r1 = query.get(1);
4980                if (DEBUG_INTENT_MATCHING || debug) {
4981                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4982                            + r1.activityInfo.name + "=" + r1.priority);
4983                }
4984                // If the first activity has a higher priority, or a different
4985                // default, then it is always desirable to pick it.
4986                if (r0.priority != r1.priority
4987                        || r0.preferredOrder != r1.preferredOrder
4988                        || r0.isDefault != r1.isDefault) {
4989                    return query.get(0);
4990                }
4991                // If we have saved a preference for a preferred activity for
4992                // this Intent, use that.
4993                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4994                        flags, query, r0.priority, true, false, debug, userId);
4995                if (ri != null) {
4996                    return ri;
4997                }
4998                ri = new ResolveInfo(mResolveInfo);
4999                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5000                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5001                ri.activityInfo.applicationInfo = new ApplicationInfo(
5002                        ri.activityInfo.applicationInfo);
5003                if (userId != 0) {
5004                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5005                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5006                }
5007                // Make sure that the resolver is displayable in car mode
5008                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5009                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5010                return ri;
5011            }
5012        }
5013        return null;
5014    }
5015
5016    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5017            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5018        final int N = query.size();
5019        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5020                .get(userId);
5021        // Get the list of persistent preferred activities that handle the intent
5022        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5023        List<PersistentPreferredActivity> pprefs = ppir != null
5024                ? ppir.queryIntent(intent, resolvedType,
5025                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5026                : null;
5027        if (pprefs != null && pprefs.size() > 0) {
5028            final int M = pprefs.size();
5029            for (int i=0; i<M; i++) {
5030                final PersistentPreferredActivity ppa = pprefs.get(i);
5031                if (DEBUG_PREFERRED || debug) {
5032                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5033                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5034                            + "\n  component=" + ppa.mComponent);
5035                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5036                }
5037                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5038                        flags | MATCH_DISABLED_COMPONENTS, userId);
5039                if (DEBUG_PREFERRED || debug) {
5040                    Slog.v(TAG, "Found persistent preferred activity:");
5041                    if (ai != null) {
5042                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5043                    } else {
5044                        Slog.v(TAG, "  null");
5045                    }
5046                }
5047                if (ai == null) {
5048                    // This previously registered persistent preferred activity
5049                    // component is no longer known. Ignore it and do NOT remove it.
5050                    continue;
5051                }
5052                for (int j=0; j<N; j++) {
5053                    final ResolveInfo ri = query.get(j);
5054                    if (!ri.activityInfo.applicationInfo.packageName
5055                            .equals(ai.applicationInfo.packageName)) {
5056                        continue;
5057                    }
5058                    if (!ri.activityInfo.name.equals(ai.name)) {
5059                        continue;
5060                    }
5061                    //  Found a persistent preference that can handle the intent.
5062                    if (DEBUG_PREFERRED || debug) {
5063                        Slog.v(TAG, "Returning persistent preferred activity: " +
5064                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5065                    }
5066                    return ri;
5067                }
5068            }
5069        }
5070        return null;
5071    }
5072
5073    // TODO: handle preferred activities missing while user has amnesia
5074    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5075            List<ResolveInfo> query, int priority, boolean always,
5076            boolean removeMatches, boolean debug, int userId) {
5077        if (!sUserManager.exists(userId)) return null;
5078        flags = updateFlagsForResolve(flags, userId, intent);
5079        // writer
5080        synchronized (mPackages) {
5081            if (intent.getSelector() != null) {
5082                intent = intent.getSelector();
5083            }
5084            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5085
5086            // Try to find a matching persistent preferred activity.
5087            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5088                    debug, userId);
5089
5090            // If a persistent preferred activity matched, use it.
5091            if (pri != null) {
5092                return pri;
5093            }
5094
5095            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5096            // Get the list of preferred activities that handle the intent
5097            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5098            List<PreferredActivity> prefs = pir != null
5099                    ? pir.queryIntent(intent, resolvedType,
5100                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5101                    : null;
5102            if (prefs != null && prefs.size() > 0) {
5103                boolean changed = false;
5104                try {
5105                    // First figure out how good the original match set is.
5106                    // We will only allow preferred activities that came
5107                    // from the same match quality.
5108                    int match = 0;
5109
5110                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5111
5112                    final int N = query.size();
5113                    for (int j=0; j<N; j++) {
5114                        final ResolveInfo ri = query.get(j);
5115                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5116                                + ": 0x" + Integer.toHexString(match));
5117                        if (ri.match > match) {
5118                            match = ri.match;
5119                        }
5120                    }
5121
5122                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5123                            + Integer.toHexString(match));
5124
5125                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5126                    final int M = prefs.size();
5127                    for (int i=0; i<M; i++) {
5128                        final PreferredActivity pa = prefs.get(i);
5129                        if (DEBUG_PREFERRED || debug) {
5130                            Slog.v(TAG, "Checking PreferredActivity ds="
5131                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5132                                    + "\n  component=" + pa.mPref.mComponent);
5133                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5134                        }
5135                        if (pa.mPref.mMatch != match) {
5136                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5137                                    + Integer.toHexString(pa.mPref.mMatch));
5138                            continue;
5139                        }
5140                        // If it's not an "always" type preferred activity and that's what we're
5141                        // looking for, skip it.
5142                        if (always && !pa.mPref.mAlways) {
5143                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5144                            continue;
5145                        }
5146                        final ActivityInfo ai = getActivityInfo(
5147                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5148                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5149                                userId);
5150                        if (DEBUG_PREFERRED || debug) {
5151                            Slog.v(TAG, "Found preferred activity:");
5152                            if (ai != null) {
5153                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5154                            } else {
5155                                Slog.v(TAG, "  null");
5156                            }
5157                        }
5158                        if (ai == null) {
5159                            // This previously registered preferred activity
5160                            // component is no longer known.  Most likely an update
5161                            // to the app was installed and in the new version this
5162                            // component no longer exists.  Clean it up by removing
5163                            // it from the preferred activities list, and skip it.
5164                            Slog.w(TAG, "Removing dangling preferred activity: "
5165                                    + pa.mPref.mComponent);
5166                            pir.removeFilter(pa);
5167                            changed = true;
5168                            continue;
5169                        }
5170                        for (int j=0; j<N; j++) {
5171                            final ResolveInfo ri = query.get(j);
5172                            if (!ri.activityInfo.applicationInfo.packageName
5173                                    .equals(ai.applicationInfo.packageName)) {
5174                                continue;
5175                            }
5176                            if (!ri.activityInfo.name.equals(ai.name)) {
5177                                continue;
5178                            }
5179
5180                            if (removeMatches) {
5181                                pir.removeFilter(pa);
5182                                changed = true;
5183                                if (DEBUG_PREFERRED) {
5184                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5185                                }
5186                                break;
5187                            }
5188
5189                            // Okay we found a previously set preferred or last chosen app.
5190                            // If the result set is different from when this
5191                            // was created, we need to clear it and re-ask the
5192                            // user their preference, if we're looking for an "always" type entry.
5193                            if (always && !pa.mPref.sameSet(query)) {
5194                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5195                                        + intent + " type " + resolvedType);
5196                                if (DEBUG_PREFERRED) {
5197                                    Slog.v(TAG, "Removing preferred activity since set changed "
5198                                            + pa.mPref.mComponent);
5199                                }
5200                                pir.removeFilter(pa);
5201                                // Re-add the filter as a "last chosen" entry (!always)
5202                                PreferredActivity lastChosen = new PreferredActivity(
5203                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5204                                pir.addFilter(lastChosen);
5205                                changed = true;
5206                                return null;
5207                            }
5208
5209                            // Yay! Either the set matched or we're looking for the last chosen
5210                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5211                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5212                            return ri;
5213                        }
5214                    }
5215                } finally {
5216                    if (changed) {
5217                        if (DEBUG_PREFERRED) {
5218                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5219                        }
5220                        scheduleWritePackageRestrictionsLocked(userId);
5221                    }
5222                }
5223            }
5224        }
5225        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5226        return null;
5227    }
5228
5229    /*
5230     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5231     */
5232    @Override
5233    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5234            int targetUserId) {
5235        mContext.enforceCallingOrSelfPermission(
5236                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5237        List<CrossProfileIntentFilter> matches =
5238                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5239        if (matches != null) {
5240            int size = matches.size();
5241            for (int i = 0; i < size; i++) {
5242                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5243            }
5244        }
5245        if (hasWebURI(intent)) {
5246            // cross-profile app linking works only towards the parent.
5247            final UserInfo parent = getProfileParent(sourceUserId);
5248            synchronized(mPackages) {
5249                int flags = updateFlagsForResolve(0, parent.id, intent);
5250                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5251                        intent, resolvedType, flags, sourceUserId, parent.id);
5252                return xpDomainInfo != null;
5253            }
5254        }
5255        return false;
5256    }
5257
5258    private UserInfo getProfileParent(int userId) {
5259        final long identity = Binder.clearCallingIdentity();
5260        try {
5261            return sUserManager.getProfileParent(userId);
5262        } finally {
5263            Binder.restoreCallingIdentity(identity);
5264        }
5265    }
5266
5267    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5268            String resolvedType, int userId) {
5269        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5270        if (resolver != null) {
5271            return resolver.queryIntent(intent, resolvedType, false, userId);
5272        }
5273        return null;
5274    }
5275
5276    @Override
5277    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5278            String resolvedType, int flags, int userId) {
5279        try {
5280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5281
5282            return new ParceledListSlice<>(
5283                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5284        } finally {
5285            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5286        }
5287    }
5288
5289    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5290            String resolvedType, int flags, int userId) {
5291        if (!sUserManager.exists(userId)) return Collections.emptyList();
5292        flags = updateFlagsForResolve(flags, userId, intent);
5293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5294                false /* requireFullPermission */, false /* checkShell */,
5295                "query intent activities");
5296        ComponentName comp = intent.getComponent();
5297        if (comp == null) {
5298            if (intent.getSelector() != null) {
5299                intent = intent.getSelector();
5300                comp = intent.getComponent();
5301            }
5302        }
5303
5304        if (comp != null) {
5305            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5306            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5307            if (ai != null) {
5308                final ResolveInfo ri = new ResolveInfo();
5309                ri.activityInfo = ai;
5310                list.add(ri);
5311            }
5312            return list;
5313        }
5314
5315        // reader
5316        synchronized (mPackages) {
5317            final String pkgName = intent.getPackage();
5318            if (pkgName == null) {
5319                List<CrossProfileIntentFilter> matchingFilters =
5320                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5321                // Check for results that need to skip the current profile.
5322                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5323                        resolvedType, flags, userId);
5324                if (xpResolveInfo != null) {
5325                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5326                    result.add(xpResolveInfo);
5327                    return filterIfNotSystemUser(result, userId);
5328                }
5329
5330                // Check for results in the current profile.
5331                List<ResolveInfo> result = mActivities.queryIntent(
5332                        intent, resolvedType, flags, userId);
5333                result = filterIfNotSystemUser(result, userId);
5334
5335                // Check for cross profile results.
5336                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5337                xpResolveInfo = queryCrossProfileIntents(
5338                        matchingFilters, intent, resolvedType, flags, userId,
5339                        hasNonNegativePriorityResult);
5340                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5341                    boolean isVisibleToUser = filterIfNotSystemUser(
5342                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5343                    if (isVisibleToUser) {
5344                        result.add(xpResolveInfo);
5345                        Collections.sort(result, mResolvePrioritySorter);
5346                    }
5347                }
5348                if (hasWebURI(intent)) {
5349                    CrossProfileDomainInfo xpDomainInfo = null;
5350                    final UserInfo parent = getProfileParent(userId);
5351                    if (parent != null) {
5352                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5353                                flags, userId, parent.id);
5354                    }
5355                    if (xpDomainInfo != null) {
5356                        if (xpResolveInfo != null) {
5357                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5358                            // in the result.
5359                            result.remove(xpResolveInfo);
5360                        }
5361                        if (result.size() == 0) {
5362                            result.add(xpDomainInfo.resolveInfo);
5363                            return result;
5364                        }
5365                    } else if (result.size() <= 1) {
5366                        return result;
5367                    }
5368                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5369                            xpDomainInfo, userId);
5370                    Collections.sort(result, mResolvePrioritySorter);
5371                }
5372                return result;
5373            }
5374            final PackageParser.Package pkg = mPackages.get(pkgName);
5375            if (pkg != null) {
5376                return filterIfNotSystemUser(
5377                        mActivities.queryIntentForPackage(
5378                                intent, resolvedType, flags, pkg.activities, userId),
5379                        userId);
5380            }
5381            return new ArrayList<ResolveInfo>();
5382        }
5383    }
5384
5385    private static class CrossProfileDomainInfo {
5386        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5387        ResolveInfo resolveInfo;
5388        /* Best domain verification status of the activities found in the other profile */
5389        int bestDomainVerificationStatus;
5390    }
5391
5392    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5393            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5394        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5395                sourceUserId)) {
5396            return null;
5397        }
5398        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5399                resolvedType, flags, parentUserId);
5400
5401        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5402            return null;
5403        }
5404        CrossProfileDomainInfo result = null;
5405        int size = resultTargetUser.size();
5406        for (int i = 0; i < size; i++) {
5407            ResolveInfo riTargetUser = resultTargetUser.get(i);
5408            // Intent filter verification is only for filters that specify a host. So don't return
5409            // those that handle all web uris.
5410            if (riTargetUser.handleAllWebDataURI) {
5411                continue;
5412            }
5413            String packageName = riTargetUser.activityInfo.packageName;
5414            PackageSetting ps = mSettings.mPackages.get(packageName);
5415            if (ps == null) {
5416                continue;
5417            }
5418            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5419            int status = (int)(verificationState >> 32);
5420            if (result == null) {
5421                result = new CrossProfileDomainInfo();
5422                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5423                        sourceUserId, parentUserId);
5424                result.bestDomainVerificationStatus = status;
5425            } else {
5426                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5427                        result.bestDomainVerificationStatus);
5428            }
5429        }
5430        // Don't consider matches with status NEVER across profiles.
5431        if (result != null && result.bestDomainVerificationStatus
5432                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5433            return null;
5434        }
5435        return result;
5436    }
5437
5438    /**
5439     * Verification statuses are ordered from the worse to the best, except for
5440     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5441     */
5442    private int bestDomainVerificationStatus(int status1, int status2) {
5443        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5444            return status2;
5445        }
5446        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5447            return status1;
5448        }
5449        return (int) MathUtils.max(status1, status2);
5450    }
5451
5452    private boolean isUserEnabled(int userId) {
5453        long callingId = Binder.clearCallingIdentity();
5454        try {
5455            UserInfo userInfo = sUserManager.getUserInfo(userId);
5456            return userInfo != null && userInfo.isEnabled();
5457        } finally {
5458            Binder.restoreCallingIdentity(callingId);
5459        }
5460    }
5461
5462    /**
5463     * Filter out activities with systemUserOnly flag set, when current user is not System.
5464     *
5465     * @return filtered list
5466     */
5467    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5468        if (userId == UserHandle.USER_SYSTEM) {
5469            return resolveInfos;
5470        }
5471        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5472            ResolveInfo info = resolveInfos.get(i);
5473            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5474                resolveInfos.remove(i);
5475            }
5476        }
5477        return resolveInfos;
5478    }
5479
5480    /**
5481     * @param resolveInfos list of resolve infos in descending priority order
5482     * @return if the list contains a resolve info with non-negative priority
5483     */
5484    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5485        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5486    }
5487
5488    private static boolean hasWebURI(Intent intent) {
5489        if (intent.getData() == null) {
5490            return false;
5491        }
5492        final String scheme = intent.getScheme();
5493        if (TextUtils.isEmpty(scheme)) {
5494            return false;
5495        }
5496        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5497    }
5498
5499    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5500            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5501            int userId) {
5502        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5503
5504        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5505            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5506                    candidates.size());
5507        }
5508
5509        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5510        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5511        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5512        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5513        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5514        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5515
5516        synchronized (mPackages) {
5517            final int count = candidates.size();
5518            // First, try to use linked apps. Partition the candidates into four lists:
5519            // one for the final results, one for the "do not use ever", one for "undefined status"
5520            // and finally one for "browser app type".
5521            for (int n=0; n<count; n++) {
5522                ResolveInfo info = candidates.get(n);
5523                String packageName = info.activityInfo.packageName;
5524                PackageSetting ps = mSettings.mPackages.get(packageName);
5525                if (ps != null) {
5526                    // Add to the special match all list (Browser use case)
5527                    if (info.handleAllWebDataURI) {
5528                        matchAllList.add(info);
5529                        continue;
5530                    }
5531                    // Try to get the status from User settings first
5532                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5533                    int status = (int)(packedStatus >> 32);
5534                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5535                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5536                        if (DEBUG_DOMAIN_VERIFICATION) {
5537                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5538                                    + " : linkgen=" + linkGeneration);
5539                        }
5540                        // Use link-enabled generation as preferredOrder, i.e.
5541                        // prefer newly-enabled over earlier-enabled.
5542                        info.preferredOrder = linkGeneration;
5543                        alwaysList.add(info);
5544                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5545                        if (DEBUG_DOMAIN_VERIFICATION) {
5546                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5547                        }
5548                        neverList.add(info);
5549                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5550                        if (DEBUG_DOMAIN_VERIFICATION) {
5551                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5552                        }
5553                        alwaysAskList.add(info);
5554                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5555                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5556                        if (DEBUG_DOMAIN_VERIFICATION) {
5557                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5558                        }
5559                        undefinedList.add(info);
5560                    }
5561                }
5562            }
5563
5564            // We'll want to include browser possibilities in a few cases
5565            boolean includeBrowser = false;
5566
5567            // First try to add the "always" resolution(s) for the current user, if any
5568            if (alwaysList.size() > 0) {
5569                result.addAll(alwaysList);
5570            } else {
5571                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5572                result.addAll(undefinedList);
5573                // Maybe add one for the other profile.
5574                if (xpDomainInfo != null && (
5575                        xpDomainInfo.bestDomainVerificationStatus
5576                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5577                    result.add(xpDomainInfo.resolveInfo);
5578                }
5579                includeBrowser = true;
5580            }
5581
5582            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5583            // If there were 'always' entries their preferred order has been set, so we also
5584            // back that off to make the alternatives equivalent
5585            if (alwaysAskList.size() > 0) {
5586                for (ResolveInfo i : result) {
5587                    i.preferredOrder = 0;
5588                }
5589                result.addAll(alwaysAskList);
5590                includeBrowser = true;
5591            }
5592
5593            if (includeBrowser) {
5594                // Also add browsers (all of them or only the default one)
5595                if (DEBUG_DOMAIN_VERIFICATION) {
5596                    Slog.v(TAG, "   ...including browsers in candidate set");
5597                }
5598                if ((matchFlags & MATCH_ALL) != 0) {
5599                    result.addAll(matchAllList);
5600                } else {
5601                    // Browser/generic handling case.  If there's a default browser, go straight
5602                    // to that (but only if there is no other higher-priority match).
5603                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5604                    int maxMatchPrio = 0;
5605                    ResolveInfo defaultBrowserMatch = null;
5606                    final int numCandidates = matchAllList.size();
5607                    for (int n = 0; n < numCandidates; n++) {
5608                        ResolveInfo info = matchAllList.get(n);
5609                        // track the highest overall match priority...
5610                        if (info.priority > maxMatchPrio) {
5611                            maxMatchPrio = info.priority;
5612                        }
5613                        // ...and the highest-priority default browser match
5614                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5615                            if (defaultBrowserMatch == null
5616                                    || (defaultBrowserMatch.priority < info.priority)) {
5617                                if (debug) {
5618                                    Slog.v(TAG, "Considering default browser match " + info);
5619                                }
5620                                defaultBrowserMatch = info;
5621                            }
5622                        }
5623                    }
5624                    if (defaultBrowserMatch != null
5625                            && defaultBrowserMatch.priority >= maxMatchPrio
5626                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5627                    {
5628                        if (debug) {
5629                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5630                        }
5631                        result.add(defaultBrowserMatch);
5632                    } else {
5633                        result.addAll(matchAllList);
5634                    }
5635                }
5636
5637                // If there is nothing selected, add all candidates and remove the ones that the user
5638                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5639                if (result.size() == 0) {
5640                    result.addAll(candidates);
5641                    result.removeAll(neverList);
5642                }
5643            }
5644        }
5645        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5646            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5647                    result.size());
5648            for (ResolveInfo info : result) {
5649                Slog.v(TAG, "  + " + info.activityInfo);
5650            }
5651        }
5652        return result;
5653    }
5654
5655    // Returns a packed value as a long:
5656    //
5657    // high 'int'-sized word: link status: undefined/ask/never/always.
5658    // low 'int'-sized word: relative priority among 'always' results.
5659    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5660        long result = ps.getDomainVerificationStatusForUser(userId);
5661        // if none available, get the master status
5662        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5663            if (ps.getIntentFilterVerificationInfo() != null) {
5664                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5665            }
5666        }
5667        return result;
5668    }
5669
5670    private ResolveInfo querySkipCurrentProfileIntents(
5671            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5672            int flags, int sourceUserId) {
5673        if (matchingFilters != null) {
5674            int size = matchingFilters.size();
5675            for (int i = 0; i < size; i ++) {
5676                CrossProfileIntentFilter filter = matchingFilters.get(i);
5677                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5678                    // Checking if there are activities in the target user that can handle the
5679                    // intent.
5680                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5681                            resolvedType, flags, sourceUserId);
5682                    if (resolveInfo != null) {
5683                        return resolveInfo;
5684                    }
5685                }
5686            }
5687        }
5688        return null;
5689    }
5690
5691    // Return matching ResolveInfo in target user if any.
5692    private ResolveInfo queryCrossProfileIntents(
5693            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5694            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5695        if (matchingFilters != null) {
5696            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5697            // match the same intent. For performance reasons, it is better not to
5698            // run queryIntent twice for the same userId
5699            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5700            int size = matchingFilters.size();
5701            for (int i = 0; i < size; i++) {
5702                CrossProfileIntentFilter filter = matchingFilters.get(i);
5703                int targetUserId = filter.getTargetUserId();
5704                boolean skipCurrentProfile =
5705                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5706                boolean skipCurrentProfileIfNoMatchFound =
5707                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5708                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5709                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5710                    // Checking if there are activities in the target user that can handle the
5711                    // intent.
5712                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5713                            resolvedType, flags, sourceUserId);
5714                    if (resolveInfo != null) return resolveInfo;
5715                    alreadyTriedUserIds.put(targetUserId, true);
5716                }
5717            }
5718        }
5719        return null;
5720    }
5721
5722    /**
5723     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5724     * will forward the intent to the filter's target user.
5725     * Otherwise, returns null.
5726     */
5727    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5728            String resolvedType, int flags, int sourceUserId) {
5729        int targetUserId = filter.getTargetUserId();
5730        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5731                resolvedType, flags, targetUserId);
5732        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5733            // If all the matches in the target profile are suspended, return null.
5734            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5735                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5736                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5737                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5738                            targetUserId);
5739                }
5740            }
5741        }
5742        return null;
5743    }
5744
5745    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5746            int sourceUserId, int targetUserId) {
5747        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5748        long ident = Binder.clearCallingIdentity();
5749        boolean targetIsProfile;
5750        try {
5751            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5752        } finally {
5753            Binder.restoreCallingIdentity(ident);
5754        }
5755        String className;
5756        if (targetIsProfile) {
5757            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5758        } else {
5759            className = FORWARD_INTENT_TO_PARENT;
5760        }
5761        ComponentName forwardingActivityComponentName = new ComponentName(
5762                mAndroidApplication.packageName, className);
5763        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5764                sourceUserId);
5765        if (!targetIsProfile) {
5766            forwardingActivityInfo.showUserIcon = targetUserId;
5767            forwardingResolveInfo.noResourceId = true;
5768        }
5769        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5770        forwardingResolveInfo.priority = 0;
5771        forwardingResolveInfo.preferredOrder = 0;
5772        forwardingResolveInfo.match = 0;
5773        forwardingResolveInfo.isDefault = true;
5774        forwardingResolveInfo.filter = filter;
5775        forwardingResolveInfo.targetUserId = targetUserId;
5776        return forwardingResolveInfo;
5777    }
5778
5779    @Override
5780    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5781            Intent[] specifics, String[] specificTypes, Intent intent,
5782            String resolvedType, int flags, int userId) {
5783        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5784                specificTypes, intent, resolvedType, flags, userId));
5785    }
5786
5787    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5788            Intent[] specifics, String[] specificTypes, Intent intent,
5789            String resolvedType, int flags, int userId) {
5790        if (!sUserManager.exists(userId)) return Collections.emptyList();
5791        flags = updateFlagsForResolve(flags, userId, intent);
5792        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5793                false /* requireFullPermission */, false /* checkShell */,
5794                "query intent activity options");
5795        final String resultsAction = intent.getAction();
5796
5797        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5798                | PackageManager.GET_RESOLVED_FILTER, userId);
5799
5800        if (DEBUG_INTENT_MATCHING) {
5801            Log.v(TAG, "Query " + intent + ": " + results);
5802        }
5803
5804        int specificsPos = 0;
5805        int N;
5806
5807        // todo: note that the algorithm used here is O(N^2).  This
5808        // isn't a problem in our current environment, but if we start running
5809        // into situations where we have more than 5 or 10 matches then this
5810        // should probably be changed to something smarter...
5811
5812        // First we go through and resolve each of the specific items
5813        // that were supplied, taking care of removing any corresponding
5814        // duplicate items in the generic resolve list.
5815        if (specifics != null) {
5816            for (int i=0; i<specifics.length; i++) {
5817                final Intent sintent = specifics[i];
5818                if (sintent == null) {
5819                    continue;
5820                }
5821
5822                if (DEBUG_INTENT_MATCHING) {
5823                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5824                }
5825
5826                String action = sintent.getAction();
5827                if (resultsAction != null && resultsAction.equals(action)) {
5828                    // If this action was explicitly requested, then don't
5829                    // remove things that have it.
5830                    action = null;
5831                }
5832
5833                ResolveInfo ri = null;
5834                ActivityInfo ai = null;
5835
5836                ComponentName comp = sintent.getComponent();
5837                if (comp == null) {
5838                    ri = resolveIntent(
5839                        sintent,
5840                        specificTypes != null ? specificTypes[i] : null,
5841                            flags, userId);
5842                    if (ri == null) {
5843                        continue;
5844                    }
5845                    if (ri == mResolveInfo) {
5846                        // ACK!  Must do something better with this.
5847                    }
5848                    ai = ri.activityInfo;
5849                    comp = new ComponentName(ai.applicationInfo.packageName,
5850                            ai.name);
5851                } else {
5852                    ai = getActivityInfo(comp, flags, userId);
5853                    if (ai == null) {
5854                        continue;
5855                    }
5856                }
5857
5858                // Look for any generic query activities that are duplicates
5859                // of this specific one, and remove them from the results.
5860                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5861                N = results.size();
5862                int j;
5863                for (j=specificsPos; j<N; j++) {
5864                    ResolveInfo sri = results.get(j);
5865                    if ((sri.activityInfo.name.equals(comp.getClassName())
5866                            && sri.activityInfo.applicationInfo.packageName.equals(
5867                                    comp.getPackageName()))
5868                        || (action != null && sri.filter.matchAction(action))) {
5869                        results.remove(j);
5870                        if (DEBUG_INTENT_MATCHING) Log.v(
5871                            TAG, "Removing duplicate item from " + j
5872                            + " due to specific " + specificsPos);
5873                        if (ri == null) {
5874                            ri = sri;
5875                        }
5876                        j--;
5877                        N--;
5878                    }
5879                }
5880
5881                // Add this specific item to its proper place.
5882                if (ri == null) {
5883                    ri = new ResolveInfo();
5884                    ri.activityInfo = ai;
5885                }
5886                results.add(specificsPos, ri);
5887                ri.specificIndex = i;
5888                specificsPos++;
5889            }
5890        }
5891
5892        // Now we go through the remaining generic results and remove any
5893        // duplicate actions that are found here.
5894        N = results.size();
5895        for (int i=specificsPos; i<N-1; i++) {
5896            final ResolveInfo rii = results.get(i);
5897            if (rii.filter == null) {
5898                continue;
5899            }
5900
5901            // Iterate over all of the actions of this result's intent
5902            // filter...  typically this should be just one.
5903            final Iterator<String> it = rii.filter.actionsIterator();
5904            if (it == null) {
5905                continue;
5906            }
5907            while (it.hasNext()) {
5908                final String action = it.next();
5909                if (resultsAction != null && resultsAction.equals(action)) {
5910                    // If this action was explicitly requested, then don't
5911                    // remove things that have it.
5912                    continue;
5913                }
5914                for (int j=i+1; j<N; j++) {
5915                    final ResolveInfo rij = results.get(j);
5916                    if (rij.filter != null && rij.filter.hasAction(action)) {
5917                        results.remove(j);
5918                        if (DEBUG_INTENT_MATCHING) Log.v(
5919                            TAG, "Removing duplicate item from " + j
5920                            + " due to action " + action + " at " + i);
5921                        j--;
5922                        N--;
5923                    }
5924                }
5925            }
5926
5927            // If the caller didn't request filter information, drop it now
5928            // so we don't have to marshall/unmarshall it.
5929            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5930                rii.filter = null;
5931            }
5932        }
5933
5934        // Filter out the caller activity if so requested.
5935        if (caller != null) {
5936            N = results.size();
5937            for (int i=0; i<N; i++) {
5938                ActivityInfo ainfo = results.get(i).activityInfo;
5939                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5940                        && caller.getClassName().equals(ainfo.name)) {
5941                    results.remove(i);
5942                    break;
5943                }
5944            }
5945        }
5946
5947        // If the caller didn't request filter information,
5948        // drop them now so we don't have to
5949        // marshall/unmarshall it.
5950        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5951            N = results.size();
5952            for (int i=0; i<N; i++) {
5953                results.get(i).filter = null;
5954            }
5955        }
5956
5957        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5958        return results;
5959    }
5960
5961    @Override
5962    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5963            String resolvedType, int flags, int userId) {
5964        return new ParceledListSlice<>(
5965                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5966    }
5967
5968    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5969            String resolvedType, int flags, int userId) {
5970        if (!sUserManager.exists(userId)) return Collections.emptyList();
5971        flags = updateFlagsForResolve(flags, userId, intent);
5972        ComponentName comp = intent.getComponent();
5973        if (comp == null) {
5974            if (intent.getSelector() != null) {
5975                intent = intent.getSelector();
5976                comp = intent.getComponent();
5977            }
5978        }
5979        if (comp != null) {
5980            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5981            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5982            if (ai != null) {
5983                ResolveInfo ri = new ResolveInfo();
5984                ri.activityInfo = ai;
5985                list.add(ri);
5986            }
5987            return list;
5988        }
5989
5990        // reader
5991        synchronized (mPackages) {
5992            String pkgName = intent.getPackage();
5993            if (pkgName == null) {
5994                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5995            }
5996            final PackageParser.Package pkg = mPackages.get(pkgName);
5997            if (pkg != null) {
5998                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5999                        userId);
6000            }
6001            return Collections.emptyList();
6002        }
6003    }
6004
6005    @Override
6006    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6007        if (!sUserManager.exists(userId)) return null;
6008        flags = updateFlagsForResolve(flags, userId, intent);
6009        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6010        if (query != null) {
6011            if (query.size() >= 1) {
6012                // If there is more than one service with the same priority,
6013                // just arbitrarily pick the first one.
6014                return query.get(0);
6015            }
6016        }
6017        return null;
6018    }
6019
6020    @Override
6021    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6022            String resolvedType, int flags, int userId) {
6023        return new ParceledListSlice<>(
6024                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6025    }
6026
6027    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6028            String resolvedType, int flags, int userId) {
6029        if (!sUserManager.exists(userId)) return Collections.emptyList();
6030        flags = updateFlagsForResolve(flags, userId, intent);
6031        ComponentName comp = intent.getComponent();
6032        if (comp == null) {
6033            if (intent.getSelector() != null) {
6034                intent = intent.getSelector();
6035                comp = intent.getComponent();
6036            }
6037        }
6038        if (comp != null) {
6039            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6040            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6041            if (si != null) {
6042                final ResolveInfo ri = new ResolveInfo();
6043                ri.serviceInfo = si;
6044                list.add(ri);
6045            }
6046            return list;
6047        }
6048
6049        // reader
6050        synchronized (mPackages) {
6051            String pkgName = intent.getPackage();
6052            if (pkgName == null) {
6053                return mServices.queryIntent(intent, resolvedType, flags, userId);
6054            }
6055            final PackageParser.Package pkg = mPackages.get(pkgName);
6056            if (pkg != null) {
6057                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6058                        userId);
6059            }
6060            return Collections.emptyList();
6061        }
6062    }
6063
6064    @Override
6065    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        return new ParceledListSlice<>(
6068                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6069    }
6070
6071    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6072            Intent intent, String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return Collections.emptyList();
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        ComponentName comp = intent.getComponent();
6076        if (comp == null) {
6077            if (intent.getSelector() != null) {
6078                intent = intent.getSelector();
6079                comp = intent.getComponent();
6080            }
6081        }
6082        if (comp != null) {
6083            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6084            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6085            if (pi != null) {
6086                final ResolveInfo ri = new ResolveInfo();
6087                ri.providerInfo = pi;
6088                list.add(ri);
6089            }
6090            return list;
6091        }
6092
6093        // reader
6094        synchronized (mPackages) {
6095            String pkgName = intent.getPackage();
6096            if (pkgName == null) {
6097                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6098            }
6099            final PackageParser.Package pkg = mPackages.get(pkgName);
6100            if (pkg != null) {
6101                return mProviders.queryIntentForPackage(
6102                        intent, resolvedType, flags, pkg.providers, userId);
6103            }
6104            return Collections.emptyList();
6105        }
6106    }
6107
6108    @Override
6109    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6111        flags = updateFlagsForPackage(flags, userId, null);
6112        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6114                true /* requireFullPermission */, false /* checkShell */,
6115                "get installed packages");
6116
6117        // writer
6118        synchronized (mPackages) {
6119            ArrayList<PackageInfo> list;
6120            if (listUninstalled) {
6121                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6122                for (PackageSetting ps : mSettings.mPackages.values()) {
6123                    final PackageInfo pi;
6124                    if (ps.pkg != null) {
6125                        pi = generatePackageInfo(ps, flags, userId);
6126                    } else {
6127                        pi = generatePackageInfo(ps, flags, userId);
6128                    }
6129                    if (pi != null) {
6130                        list.add(pi);
6131                    }
6132                }
6133            } else {
6134                list = new ArrayList<PackageInfo>(mPackages.size());
6135                for (PackageParser.Package p : mPackages.values()) {
6136                    final PackageInfo pi =
6137                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6138                    if (pi != null) {
6139                        list.add(pi);
6140                    }
6141                }
6142            }
6143
6144            return new ParceledListSlice<PackageInfo>(list);
6145        }
6146    }
6147
6148    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6149            String[] permissions, boolean[] tmp, int flags, int userId) {
6150        int numMatch = 0;
6151        final PermissionsState permissionsState = ps.getPermissionsState();
6152        for (int i=0; i<permissions.length; i++) {
6153            final String permission = permissions[i];
6154            if (permissionsState.hasPermission(permission, userId)) {
6155                tmp[i] = true;
6156                numMatch++;
6157            } else {
6158                tmp[i] = false;
6159            }
6160        }
6161        if (numMatch == 0) {
6162            return;
6163        }
6164        final PackageInfo pi;
6165        if (ps.pkg != null) {
6166            pi = generatePackageInfo(ps, flags, userId);
6167        } else {
6168            pi = generatePackageInfo(ps, flags, userId);
6169        }
6170        // The above might return null in cases of uninstalled apps or install-state
6171        // skew across users/profiles.
6172        if (pi != null) {
6173            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6174                if (numMatch == permissions.length) {
6175                    pi.requestedPermissions = permissions;
6176                } else {
6177                    pi.requestedPermissions = new String[numMatch];
6178                    numMatch = 0;
6179                    for (int i=0; i<permissions.length; i++) {
6180                        if (tmp[i]) {
6181                            pi.requestedPermissions[numMatch] = permissions[i];
6182                            numMatch++;
6183                        }
6184                    }
6185                }
6186            }
6187            list.add(pi);
6188        }
6189    }
6190
6191    @Override
6192    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6193            String[] permissions, int flags, int userId) {
6194        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6195        flags = updateFlagsForPackage(flags, userId, permissions);
6196        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6197
6198        // writer
6199        synchronized (mPackages) {
6200            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6201            boolean[] tmpBools = new boolean[permissions.length];
6202            if (listUninstalled) {
6203                for (PackageSetting ps : mSettings.mPackages.values()) {
6204                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6205                }
6206            } else {
6207                for (PackageParser.Package pkg : mPackages.values()) {
6208                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6209                    if (ps != null) {
6210                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6211                                userId);
6212                    }
6213                }
6214            }
6215
6216            return new ParceledListSlice<PackageInfo>(list);
6217        }
6218    }
6219
6220    @Override
6221    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6222        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6223        flags = updateFlagsForApplication(flags, userId, null);
6224        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6225
6226        // writer
6227        synchronized (mPackages) {
6228            ArrayList<ApplicationInfo> list;
6229            if (listUninstalled) {
6230                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6231                for (PackageSetting ps : mSettings.mPackages.values()) {
6232                    ApplicationInfo ai;
6233                    if (ps.pkg != null) {
6234                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6235                                ps.readUserState(userId), userId);
6236                    } else {
6237                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6238                    }
6239                    if (ai != null) {
6240                        list.add(ai);
6241                    }
6242                }
6243            } else {
6244                list = new ArrayList<ApplicationInfo>(mPackages.size());
6245                for (PackageParser.Package p : mPackages.values()) {
6246                    if (p.mExtras != null) {
6247                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6248                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6249                        if (ai != null) {
6250                            list.add(ai);
6251                        }
6252                    }
6253                }
6254            }
6255
6256            return new ParceledListSlice<ApplicationInfo>(list);
6257        }
6258    }
6259
6260    @Override
6261    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6262        if (DISABLE_EPHEMERAL_APPS) {
6263            return null;
6264        }
6265
6266        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6267                "getEphemeralApplications");
6268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6269                true /* requireFullPermission */, false /* checkShell */,
6270                "getEphemeralApplications");
6271        synchronized (mPackages) {
6272            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6273                    .getEphemeralApplicationsLPw(userId);
6274            if (ephemeralApps != null) {
6275                return new ParceledListSlice<>(ephemeralApps);
6276            }
6277        }
6278        return null;
6279    }
6280
6281    @Override
6282    public boolean isEphemeralApplication(String packageName, int userId) {
6283        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6284                true /* requireFullPermission */, false /* checkShell */,
6285                "isEphemeral");
6286        if (DISABLE_EPHEMERAL_APPS) {
6287            return false;
6288        }
6289
6290        if (!isCallerSameApp(packageName)) {
6291            return false;
6292        }
6293        synchronized (mPackages) {
6294            PackageParser.Package pkg = mPackages.get(packageName);
6295            if (pkg != null) {
6296                return pkg.applicationInfo.isEphemeralApp();
6297            }
6298        }
6299        return false;
6300    }
6301
6302    @Override
6303    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6304        if (DISABLE_EPHEMERAL_APPS) {
6305            return null;
6306        }
6307
6308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6309                true /* requireFullPermission */, false /* checkShell */,
6310                "getCookie");
6311        if (!isCallerSameApp(packageName)) {
6312            return null;
6313        }
6314        synchronized (mPackages) {
6315            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6316                    packageName, userId);
6317        }
6318    }
6319
6320    @Override
6321    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6322        if (DISABLE_EPHEMERAL_APPS) {
6323            return true;
6324        }
6325
6326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6327                true /* requireFullPermission */, true /* checkShell */,
6328                "setCookie");
6329        if (!isCallerSameApp(packageName)) {
6330            return false;
6331        }
6332        synchronized (mPackages) {
6333            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6334                    packageName, cookie, userId);
6335        }
6336    }
6337
6338    @Override
6339    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6340        if (DISABLE_EPHEMERAL_APPS) {
6341            return null;
6342        }
6343
6344        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6345                "getEphemeralApplicationIcon");
6346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6347                true /* requireFullPermission */, false /* checkShell */,
6348                "getEphemeralApplicationIcon");
6349        synchronized (mPackages) {
6350            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6351                    packageName, userId);
6352        }
6353    }
6354
6355    private boolean isCallerSameApp(String packageName) {
6356        PackageParser.Package pkg = mPackages.get(packageName);
6357        return pkg != null
6358                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6359    }
6360
6361    @Override
6362    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6363        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6364    }
6365
6366    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6367        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6368
6369        // reader
6370        synchronized (mPackages) {
6371            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6372            final int userId = UserHandle.getCallingUserId();
6373            while (i.hasNext()) {
6374                final PackageParser.Package p = i.next();
6375                if (p.applicationInfo == null) continue;
6376
6377                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6378                        && !p.applicationInfo.isDirectBootAware();
6379                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6380                        && p.applicationInfo.isDirectBootAware();
6381
6382                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6383                        && (!mSafeMode || isSystemApp(p))
6384                        && (matchesUnaware || matchesAware)) {
6385                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6386                    if (ps != null) {
6387                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6388                                ps.readUserState(userId), userId);
6389                        if (ai != null) {
6390                            finalList.add(ai);
6391                        }
6392                    }
6393                }
6394            }
6395        }
6396
6397        return finalList;
6398    }
6399
6400    @Override
6401    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6402        if (!sUserManager.exists(userId)) return null;
6403        flags = updateFlagsForComponent(flags, userId, name);
6404        // reader
6405        synchronized (mPackages) {
6406            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6407            PackageSetting ps = provider != null
6408                    ? mSettings.mPackages.get(provider.owner.packageName)
6409                    : null;
6410            return ps != null
6411                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6412                    ? PackageParser.generateProviderInfo(provider, flags,
6413                            ps.readUserState(userId), userId)
6414                    : null;
6415        }
6416    }
6417
6418    /**
6419     * @deprecated
6420     */
6421    @Deprecated
6422    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6423        // reader
6424        synchronized (mPackages) {
6425            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6426                    .entrySet().iterator();
6427            final int userId = UserHandle.getCallingUserId();
6428            while (i.hasNext()) {
6429                Map.Entry<String, PackageParser.Provider> entry = i.next();
6430                PackageParser.Provider p = entry.getValue();
6431                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6432
6433                if (ps != null && p.syncable
6434                        && (!mSafeMode || (p.info.applicationInfo.flags
6435                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6436                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6437                            ps.readUserState(userId), userId);
6438                    if (info != null) {
6439                        outNames.add(entry.getKey());
6440                        outInfo.add(info);
6441                    }
6442                }
6443            }
6444        }
6445    }
6446
6447    @Override
6448    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6449            int uid, int flags) {
6450        final int userId = processName != null ? UserHandle.getUserId(uid)
6451                : UserHandle.getCallingUserId();
6452        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6453        flags = updateFlagsForComponent(flags, userId, processName);
6454
6455        ArrayList<ProviderInfo> finalList = null;
6456        // reader
6457        synchronized (mPackages) {
6458            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6459            while (i.hasNext()) {
6460                final PackageParser.Provider p = i.next();
6461                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6462                if (ps != null && p.info.authority != null
6463                        && (processName == null
6464                                || (p.info.processName.equals(processName)
6465                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6466                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6467                    if (finalList == null) {
6468                        finalList = new ArrayList<ProviderInfo>(3);
6469                    }
6470                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6471                            ps.readUserState(userId), userId);
6472                    if (info != null) {
6473                        finalList.add(info);
6474                    }
6475                }
6476            }
6477        }
6478
6479        if (finalList != null) {
6480            Collections.sort(finalList, mProviderInitOrderSorter);
6481            return new ParceledListSlice<ProviderInfo>(finalList);
6482        }
6483
6484        return ParceledListSlice.emptyList();
6485    }
6486
6487    @Override
6488    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6489        // reader
6490        synchronized (mPackages) {
6491            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6492            return PackageParser.generateInstrumentationInfo(i, flags);
6493        }
6494    }
6495
6496    @Override
6497    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6498            String targetPackage, int flags) {
6499        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6500    }
6501
6502    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6503            int flags) {
6504        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6505
6506        // reader
6507        synchronized (mPackages) {
6508            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6509            while (i.hasNext()) {
6510                final PackageParser.Instrumentation p = i.next();
6511                if (targetPackage == null
6512                        || targetPackage.equals(p.info.targetPackage)) {
6513                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6514                            flags);
6515                    if (ii != null) {
6516                        finalList.add(ii);
6517                    }
6518                }
6519            }
6520        }
6521
6522        return finalList;
6523    }
6524
6525    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6526        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6527        if (overlays == null) {
6528            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6529            return;
6530        }
6531        for (PackageParser.Package opkg : overlays.values()) {
6532            // Not much to do if idmap fails: we already logged the error
6533            // and we certainly don't want to abort installation of pkg simply
6534            // because an overlay didn't fit properly. For these reasons,
6535            // ignore the return value of createIdmapForPackagePairLI.
6536            createIdmapForPackagePairLI(pkg, opkg);
6537        }
6538    }
6539
6540    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6541            PackageParser.Package opkg) {
6542        if (!opkg.mTrustedOverlay) {
6543            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6544                    opkg.baseCodePath + ": overlay not trusted");
6545            return false;
6546        }
6547        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6548        if (overlaySet == null) {
6549            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6550                    opkg.baseCodePath + " but target package has no known overlays");
6551            return false;
6552        }
6553        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6554        // TODO: generate idmap for split APKs
6555        try {
6556            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6557        } catch (InstallerException e) {
6558            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6559                    + opkg.baseCodePath);
6560            return false;
6561        }
6562        PackageParser.Package[] overlayArray =
6563            overlaySet.values().toArray(new PackageParser.Package[0]);
6564        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6565            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6566                return p1.mOverlayPriority - p2.mOverlayPriority;
6567            }
6568        };
6569        Arrays.sort(overlayArray, cmp);
6570
6571        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6572        int i = 0;
6573        for (PackageParser.Package p : overlayArray) {
6574            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6575        }
6576        return true;
6577    }
6578
6579    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6581        try {
6582            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6583        } finally {
6584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6585        }
6586    }
6587
6588    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6589        final File[] files = dir.listFiles();
6590        if (ArrayUtils.isEmpty(files)) {
6591            Log.d(TAG, "No files in app dir " + dir);
6592            return;
6593        }
6594
6595        if (DEBUG_PACKAGE_SCANNING) {
6596            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6597                    + " flags=0x" + Integer.toHexString(parseFlags));
6598        }
6599
6600        for (File file : files) {
6601            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6602                    && !PackageInstallerService.isStageName(file.getName());
6603            if (!isPackage) {
6604                // Ignore entries which are not packages
6605                continue;
6606            }
6607            try {
6608                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6609                        scanFlags, currentTime, null);
6610            } catch (PackageManagerException e) {
6611                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6612
6613                // Delete invalid userdata apps
6614                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6615                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6616                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6617                    removeCodePathLI(file);
6618                }
6619            }
6620        }
6621    }
6622
6623    private static File getSettingsProblemFile() {
6624        File dataDir = Environment.getDataDirectory();
6625        File systemDir = new File(dataDir, "system");
6626        File fname = new File(systemDir, "uiderrors.txt");
6627        return fname;
6628    }
6629
6630    static void reportSettingsProblem(int priority, String msg) {
6631        logCriticalInfo(priority, msg);
6632    }
6633
6634    static void logCriticalInfo(int priority, String msg) {
6635        Slog.println(priority, TAG, msg);
6636        EventLogTags.writePmCriticalInfo(msg);
6637        try {
6638            File fname = getSettingsProblemFile();
6639            FileOutputStream out = new FileOutputStream(fname, true);
6640            PrintWriter pw = new FastPrintWriter(out);
6641            SimpleDateFormat formatter = new SimpleDateFormat();
6642            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6643            pw.println(dateString + ": " + msg);
6644            pw.close();
6645            FileUtils.setPermissions(
6646                    fname.toString(),
6647                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6648                    -1, -1);
6649        } catch (java.io.IOException e) {
6650        }
6651    }
6652
6653    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6654            final int policyFlags) throws PackageManagerException {
6655        if (ps != null
6656                && ps.codePath.equals(srcFile)
6657                && ps.timeStamp == srcFile.lastModified()
6658                && !isCompatSignatureUpdateNeeded(pkg)
6659                && !isRecoverSignatureUpdateNeeded(pkg)) {
6660            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6661            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6662            ArraySet<PublicKey> signingKs;
6663            synchronized (mPackages) {
6664                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6665            }
6666            if (ps.signatures.mSignatures != null
6667                    && ps.signatures.mSignatures.length != 0
6668                    && signingKs != null) {
6669                // Optimization: reuse the existing cached certificates
6670                // if the package appears to be unchanged.
6671                pkg.mSignatures = ps.signatures.mSignatures;
6672                pkg.mSigningKeys = signingKs;
6673                return;
6674            }
6675
6676            Slog.w(TAG, "PackageSetting for " + ps.name
6677                    + " is missing signatures.  Collecting certs again to recover them.");
6678        } else {
6679            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6680        }
6681
6682        try {
6683            PackageParser.collectCertificates(pkg, policyFlags);
6684        } catch (PackageParserException e) {
6685            throw PackageManagerException.from(e);
6686        }
6687    }
6688
6689    /**
6690     *  Traces a package scan.
6691     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6692     */
6693    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6694            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6695        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6696        try {
6697            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6698        } finally {
6699            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6700        }
6701    }
6702
6703    /**
6704     *  Scans a package and returns the newly parsed package.
6705     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6706     */
6707    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6708            long currentTime, UserHandle user) throws PackageManagerException {
6709        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6710        PackageParser pp = new PackageParser();
6711        pp.setSeparateProcesses(mSeparateProcesses);
6712        pp.setOnlyCoreApps(mOnlyCore);
6713        pp.setDisplayMetrics(mMetrics);
6714
6715        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6716            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6717        }
6718
6719        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6720        final PackageParser.Package pkg;
6721        try {
6722            pkg = pp.parsePackage(scanFile, parseFlags);
6723        } catch (PackageParserException e) {
6724            throw PackageManagerException.from(e);
6725        } finally {
6726            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6727        }
6728
6729        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6730    }
6731
6732    /**
6733     *  Scans a package and returns the newly parsed package.
6734     *  @throws PackageManagerException on a parse error.
6735     */
6736    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6737            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6738            throws PackageManagerException {
6739        // If the package has children and this is the first dive in the function
6740        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6741        // packages (parent and children) would be successfully scanned before the
6742        // actual scan since scanning mutates internal state and we want to atomically
6743        // install the package and its children.
6744        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6745            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6746                scanFlags |= SCAN_CHECK_ONLY;
6747            }
6748        } else {
6749            scanFlags &= ~SCAN_CHECK_ONLY;
6750        }
6751
6752        // Scan the parent
6753        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6754                scanFlags, currentTime, user);
6755
6756        // Scan the children
6757        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6758        for (int i = 0; i < childCount; i++) {
6759            PackageParser.Package childPackage = pkg.childPackages.get(i);
6760            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6761                    currentTime, user);
6762        }
6763
6764
6765        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6766            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6767        }
6768
6769        return scannedPkg;
6770    }
6771
6772    /**
6773     *  Scans a package and returns the newly parsed package.
6774     *  @throws PackageManagerException on a parse error.
6775     */
6776    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6777            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6778            throws PackageManagerException {
6779        PackageSetting ps = null;
6780        PackageSetting updatedPkg;
6781        // reader
6782        synchronized (mPackages) {
6783            // Look to see if we already know about this package.
6784            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6785            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6786                // This package has been renamed to its original name.  Let's
6787                // use that.
6788                ps = mSettings.peekPackageLPr(oldName);
6789            }
6790            // If there was no original package, see one for the real package name.
6791            if (ps == null) {
6792                ps = mSettings.peekPackageLPr(pkg.packageName);
6793            }
6794            // Check to see if this package could be hiding/updating a system
6795            // package.  Must look for it either under the original or real
6796            // package name depending on our state.
6797            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6798            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6799
6800            // If this is a package we don't know about on the system partition, we
6801            // may need to remove disabled child packages on the system partition
6802            // or may need to not add child packages if the parent apk is updated
6803            // on the data partition and no longer defines this child package.
6804            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6805                // If this is a parent package for an updated system app and this system
6806                // app got an OTA update which no longer defines some of the child packages
6807                // we have to prune them from the disabled system packages.
6808                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6809                if (disabledPs != null) {
6810                    final int scannedChildCount = (pkg.childPackages != null)
6811                            ? pkg.childPackages.size() : 0;
6812                    final int disabledChildCount = disabledPs.childPackageNames != null
6813                            ? disabledPs.childPackageNames.size() : 0;
6814                    for (int i = 0; i < disabledChildCount; i++) {
6815                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6816                        boolean disabledPackageAvailable = false;
6817                        for (int j = 0; j < scannedChildCount; j++) {
6818                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6819                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6820                                disabledPackageAvailable = true;
6821                                break;
6822                            }
6823                         }
6824                         if (!disabledPackageAvailable) {
6825                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6826                         }
6827                    }
6828                }
6829            }
6830        }
6831
6832        boolean updatedPkgBetter = false;
6833        // First check if this is a system package that may involve an update
6834        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6835            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6836            // it needs to drop FLAG_PRIVILEGED.
6837            if (locationIsPrivileged(scanFile)) {
6838                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6839            } else {
6840                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6841            }
6842
6843            if (ps != null && !ps.codePath.equals(scanFile)) {
6844                // The path has changed from what was last scanned...  check the
6845                // version of the new path against what we have stored to determine
6846                // what to do.
6847                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6848                if (pkg.mVersionCode <= ps.versionCode) {
6849                    // The system package has been updated and the code path does not match
6850                    // Ignore entry. Skip it.
6851                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6852                            + " ignored: updated version " + ps.versionCode
6853                            + " better than this " + pkg.mVersionCode);
6854                    if (!updatedPkg.codePath.equals(scanFile)) {
6855                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6856                                + ps.name + " changing from " + updatedPkg.codePathString
6857                                + " to " + scanFile);
6858                        updatedPkg.codePath = scanFile;
6859                        updatedPkg.codePathString = scanFile.toString();
6860                        updatedPkg.resourcePath = scanFile;
6861                        updatedPkg.resourcePathString = scanFile.toString();
6862                    }
6863                    updatedPkg.pkg = pkg;
6864                    updatedPkg.versionCode = pkg.mVersionCode;
6865
6866                    // Update the disabled system child packages to point to the package too.
6867                    final int childCount = updatedPkg.childPackageNames != null
6868                            ? updatedPkg.childPackageNames.size() : 0;
6869                    for (int i = 0; i < childCount; i++) {
6870                        String childPackageName = updatedPkg.childPackageNames.get(i);
6871                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6872                                childPackageName);
6873                        if (updatedChildPkg != null) {
6874                            updatedChildPkg.pkg = pkg;
6875                            updatedChildPkg.versionCode = pkg.mVersionCode;
6876                        }
6877                    }
6878
6879                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6880                            + scanFile + " ignored: updated version " + ps.versionCode
6881                            + " better than this " + pkg.mVersionCode);
6882                } else {
6883                    // The current app on the system partition is better than
6884                    // what we have updated to on the data partition; switch
6885                    // back to the system partition version.
6886                    // At this point, its safely assumed that package installation for
6887                    // apps in system partition will go through. If not there won't be a working
6888                    // version of the app
6889                    // writer
6890                    synchronized (mPackages) {
6891                        // Just remove the loaded entries from package lists.
6892                        mPackages.remove(ps.name);
6893                    }
6894
6895                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6896                            + " reverting from " + ps.codePathString
6897                            + ": new version " + pkg.mVersionCode
6898                            + " better than installed " + ps.versionCode);
6899
6900                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6901                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6902                    synchronized (mInstallLock) {
6903                        args.cleanUpResourcesLI();
6904                    }
6905                    synchronized (mPackages) {
6906                        mSettings.enableSystemPackageLPw(ps.name);
6907                    }
6908                    updatedPkgBetter = true;
6909                }
6910            }
6911        }
6912
6913        if (updatedPkg != null) {
6914            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6915            // initially
6916            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6917
6918            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6919            // flag set initially
6920            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6921                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6922            }
6923        }
6924
6925        // Verify certificates against what was last scanned
6926        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6927
6928        /*
6929         * A new system app appeared, but we already had a non-system one of the
6930         * same name installed earlier.
6931         */
6932        boolean shouldHideSystemApp = false;
6933        if (updatedPkg == null && ps != null
6934                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6935            /*
6936             * Check to make sure the signatures match first. If they don't,
6937             * wipe the installed application and its data.
6938             */
6939            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6940                    != PackageManager.SIGNATURE_MATCH) {
6941                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6942                        + " signatures don't match existing userdata copy; removing");
6943                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6944                        "scanPackageInternalLI")) {
6945                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6946                }
6947                ps = null;
6948            } else {
6949                /*
6950                 * If the newly-added system app is an older version than the
6951                 * already installed version, hide it. It will be scanned later
6952                 * and re-added like an update.
6953                 */
6954                if (pkg.mVersionCode <= ps.versionCode) {
6955                    shouldHideSystemApp = true;
6956                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6957                            + " but new version " + pkg.mVersionCode + " better than installed "
6958                            + ps.versionCode + "; hiding system");
6959                } else {
6960                    /*
6961                     * The newly found system app is a newer version that the
6962                     * one previously installed. Simply remove the
6963                     * already-installed application and replace it with our own
6964                     * while keeping the application data.
6965                     */
6966                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6967                            + " reverting from " + ps.codePathString + ": new version "
6968                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6969                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6970                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6971                    synchronized (mInstallLock) {
6972                        args.cleanUpResourcesLI();
6973                    }
6974                }
6975            }
6976        }
6977
6978        // The apk is forward locked (not public) if its code and resources
6979        // are kept in different files. (except for app in either system or
6980        // vendor path).
6981        // TODO grab this value from PackageSettings
6982        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6983            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6984                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6985            }
6986        }
6987
6988        // TODO: extend to support forward-locked splits
6989        String resourcePath = null;
6990        String baseResourcePath = null;
6991        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6992            if (ps != null && ps.resourcePathString != null) {
6993                resourcePath = ps.resourcePathString;
6994                baseResourcePath = ps.resourcePathString;
6995            } else {
6996                // Should not happen at all. Just log an error.
6997                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6998            }
6999        } else {
7000            resourcePath = pkg.codePath;
7001            baseResourcePath = pkg.baseCodePath;
7002        }
7003
7004        // Set application objects path explicitly.
7005        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7006        pkg.setApplicationInfoCodePath(pkg.codePath);
7007        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7008        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7009        pkg.setApplicationInfoResourcePath(resourcePath);
7010        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7011        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7012
7013        // Note that we invoke the following method only if we are about to unpack an application
7014        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7015                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7016
7017        /*
7018         * If the system app should be overridden by a previously installed
7019         * data, hide the system app now and let the /data/app scan pick it up
7020         * again.
7021         */
7022        if (shouldHideSystemApp) {
7023            synchronized (mPackages) {
7024                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7025            }
7026        }
7027
7028        return scannedPkg;
7029    }
7030
7031    private static String fixProcessName(String defProcessName,
7032            String processName, int uid) {
7033        if (processName == null) {
7034            return defProcessName;
7035        }
7036        return processName;
7037    }
7038
7039    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7040            throws PackageManagerException {
7041        if (pkgSetting.signatures.mSignatures != null) {
7042            // Already existing package. Make sure signatures match
7043            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7044                    == PackageManager.SIGNATURE_MATCH;
7045            if (!match) {
7046                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7047                        == PackageManager.SIGNATURE_MATCH;
7048            }
7049            if (!match) {
7050                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7051                        == PackageManager.SIGNATURE_MATCH;
7052            }
7053            if (!match) {
7054                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7055                        + pkg.packageName + " signatures do not match the "
7056                        + "previously installed version; ignoring!");
7057            }
7058        }
7059
7060        // Check for shared user signatures
7061        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7062            // Already existing package. Make sure signatures match
7063            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7064                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7065            if (!match) {
7066                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7067                        == PackageManager.SIGNATURE_MATCH;
7068            }
7069            if (!match) {
7070                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7071                        == PackageManager.SIGNATURE_MATCH;
7072            }
7073            if (!match) {
7074                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7075                        "Package " + pkg.packageName
7076                        + " has no signatures that match those in shared user "
7077                        + pkgSetting.sharedUser.name + "; ignoring!");
7078            }
7079        }
7080    }
7081
7082    /**
7083     * Enforces that only the system UID or root's UID can call a method exposed
7084     * via Binder.
7085     *
7086     * @param message used as message if SecurityException is thrown
7087     * @throws SecurityException if the caller is not system or root
7088     */
7089    private static final void enforceSystemOrRoot(String message) {
7090        final int uid = Binder.getCallingUid();
7091        if (uid != Process.SYSTEM_UID && uid != 0) {
7092            throw new SecurityException(message);
7093        }
7094    }
7095
7096    @Override
7097    public void performFstrimIfNeeded() {
7098        enforceSystemOrRoot("Only the system can request fstrim");
7099
7100        // Before everything else, see whether we need to fstrim.
7101        try {
7102            IMountService ms = PackageHelper.getMountService();
7103            if (ms != null) {
7104                final boolean isUpgrade = isUpgrade();
7105                boolean doTrim = isUpgrade;
7106                if (doTrim) {
7107                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7108                } else {
7109                    final long interval = android.provider.Settings.Global.getLong(
7110                            mContext.getContentResolver(),
7111                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7112                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7113                    if (interval > 0) {
7114                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7115                        if (timeSinceLast > interval) {
7116                            doTrim = true;
7117                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7118                                    + "; running immediately");
7119                        }
7120                    }
7121                }
7122                if (doTrim) {
7123                    if (!isFirstBoot()) {
7124                        try {
7125                            ActivityManagerNative.getDefault().showBootMessage(
7126                                    mContext.getResources().getString(
7127                                            R.string.android_upgrading_fstrim), true);
7128                        } catch (RemoteException e) {
7129                        }
7130                    }
7131                    ms.runMaintenance();
7132                }
7133            } else {
7134                Slog.e(TAG, "Mount service unavailable!");
7135            }
7136        } catch (RemoteException e) {
7137            // Can't happen; MountService is local
7138        }
7139    }
7140
7141    @Override
7142    public void updatePackagesIfNeeded() {
7143        enforceSystemOrRoot("Only the system can request package update");
7144
7145        // We need to re-extract after an OTA.
7146        boolean causeUpgrade = isUpgrade();
7147
7148        // First boot or factory reset.
7149        // Note: we also handle devices that are upgrading to N right now as if it is their
7150        //       first boot, as they do not have profile data.
7151        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7152
7153        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7154        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7155
7156        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7157            return;
7158        }
7159
7160        List<PackageParser.Package> pkgs;
7161        synchronized (mPackages) {
7162            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7163        }
7164
7165        int curr = 0;
7166        int total = pkgs.size();
7167        for (PackageParser.Package pkg : pkgs) {
7168            curr++;
7169
7170            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7171                if (DEBUG_DEXOPT) {
7172                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7173                }
7174                continue;
7175            }
7176
7177            if (DEBUG_DEXOPT) {
7178                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7179            }
7180
7181            if (!isFirstBoot()) {
7182                try {
7183                    ActivityManagerNative.getDefault().showBootMessage(
7184                            mContext.getResources().getString(R.string.android_upgrading_apk,
7185                                    curr, total), true);
7186                } catch (RemoteException e) {
7187                }
7188            }
7189
7190            performDexOpt(pkg.packageName,
7191                    null /* instructionSet */,
7192                    true /* checkProfiles */,
7193                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7194                    false /* force */);
7195        }
7196    }
7197
7198    @Override
7199    public void notifyPackageUse(String packageName, int reason) {
7200        synchronized (mPackages) {
7201            PackageParser.Package p = mPackages.get(packageName);
7202            if (p == null) {
7203                return;
7204            }
7205            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7206        }
7207    }
7208
7209    // TODO: this is not used nor needed. Delete it.
7210    @Override
7211    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7212        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7213                getFullCompilerFilter(), false /* force */);
7214    }
7215
7216    @Override
7217    public boolean performDexOpt(String packageName, String instructionSet,
7218            boolean checkProfiles, int compileReason, boolean force) {
7219        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7220                getCompilerFilterForReason(compileReason), force);
7221    }
7222
7223    @Override
7224    public boolean performDexOptMode(String packageName, String instructionSet,
7225            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7226        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7227                targetCompilerFilter, force);
7228    }
7229
7230    private boolean performDexOptTraced(String packageName, String instructionSet,
7231                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7232        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7233        try {
7234            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7235                    targetCompilerFilter, force);
7236        } finally {
7237            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7238        }
7239    }
7240
7241    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7242    // if the package can now be considered up to date for the given filter.
7243    private boolean performDexOptInternal(String packageName, String instructionSet,
7244                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7245        PackageParser.Package p;
7246        final String targetInstructionSet;
7247        synchronized (mPackages) {
7248            p = mPackages.get(packageName);
7249            if (p == null) {
7250                return false;
7251            }
7252            mPackageUsage.write(false);
7253
7254            targetInstructionSet = instructionSet != null ? instructionSet :
7255                    getPrimaryInstructionSet(p.applicationInfo);
7256        }
7257        long callingId = Binder.clearCallingIdentity();
7258        try {
7259            synchronized (mInstallLock) {
7260                final String[] instructionSets = new String[] { targetInstructionSet };
7261                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7262                        checkProfiles, targetCompilerFilter, force);
7263                return result != PackageDexOptimizer.DEX_OPT_FAILED;
7264            }
7265        } finally {
7266            Binder.restoreCallingIdentity(callingId);
7267        }
7268    }
7269
7270    public ArraySet<String> getOptimizablePackages() {
7271        ArraySet<String> pkgs = new ArraySet<String>();
7272        synchronized (mPackages) {
7273            for (PackageParser.Package p : mPackages.values()) {
7274                if (PackageDexOptimizer.canOptimizePackage(p)) {
7275                    pkgs.add(p.packageName);
7276                }
7277            }
7278        }
7279        return pkgs;
7280    }
7281
7282    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7283            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7284            boolean force) {
7285        // Select the dex optimizer based on the force parameter.
7286        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7287        //       allocate an object here.
7288        PackageDexOptimizer pdo = force
7289                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7290                : mPackageDexOptimizer;
7291
7292        // Optimize all dependencies first. Note: we ignore the return value and march on
7293        // on errors.
7294        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7295        if (!deps.isEmpty()) {
7296            for (PackageParser.Package depPackage : deps) {
7297                // TODO: Analyze and investigate if we (should) profile libraries.
7298                // Currently this will do a full compilation of the library by default.
7299                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7300                        false /* checkProfiles */,
7301                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7302            }
7303        }
7304
7305        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7306                targetCompilerFilter);
7307    }
7308
7309    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7310        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7311            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7312            Set<String> collectedNames = new HashSet<>();
7313            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7314
7315            retValue.remove(p);
7316
7317            return retValue;
7318        } else {
7319            return Collections.emptyList();
7320        }
7321    }
7322
7323    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7324            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7325        if (!collectedNames.contains(p.packageName)) {
7326            collectedNames.add(p.packageName);
7327            collected.add(p);
7328
7329            if (p.usesLibraries != null) {
7330                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7331            }
7332            if (p.usesOptionalLibraries != null) {
7333                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7334                        collectedNames);
7335            }
7336        }
7337    }
7338
7339    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7340            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7341        for (String libName : libs) {
7342            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7343            if (libPkg != null) {
7344                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7345            }
7346        }
7347    }
7348
7349    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7350        synchronized (mPackages) {
7351            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7352            if (lib != null && lib.apk != null) {
7353                return mPackages.get(lib.apk);
7354            }
7355        }
7356        return null;
7357    }
7358
7359    public void shutdown() {
7360        mPackageUsage.write(true);
7361    }
7362
7363    @Override
7364    public void forceDexOpt(String packageName) {
7365        enforceSystemOrRoot("forceDexOpt");
7366
7367        PackageParser.Package pkg;
7368        synchronized (mPackages) {
7369            pkg = mPackages.get(packageName);
7370            if (pkg == null) {
7371                throw new IllegalArgumentException("Unknown package: " + packageName);
7372            }
7373        }
7374
7375        synchronized (mInstallLock) {
7376            final String[] instructionSets = new String[] {
7377                    getPrimaryInstructionSet(pkg.applicationInfo) };
7378
7379            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7380
7381            // Whoever is calling forceDexOpt wants a fully compiled package.
7382            // Don't use profiles since that may cause compilation to be skipped.
7383            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7384                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7385                    true /* force */);
7386
7387            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7388            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7389                throw new IllegalStateException("Failed to dexopt: " + res);
7390            }
7391        }
7392    }
7393
7394    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7395        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7396            Slog.w(TAG, "Unable to update from " + oldPkg.name
7397                    + " to " + newPkg.packageName
7398                    + ": old package not in system partition");
7399            return false;
7400        } else if (mPackages.get(oldPkg.name) != null) {
7401            Slog.w(TAG, "Unable to update from " + oldPkg.name
7402                    + " to " + newPkg.packageName
7403                    + ": old package still exists");
7404            return false;
7405        }
7406        return true;
7407    }
7408
7409    void removeCodePathLI(File codePath) {
7410        if (codePath.isDirectory()) {
7411            try {
7412                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7413            } catch (InstallerException e) {
7414                Slog.w(TAG, "Failed to remove code path", e);
7415            }
7416        } else {
7417            codePath.delete();
7418        }
7419    }
7420
7421    private int[] resolveUserIds(int userId) {
7422        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7423    }
7424
7425    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7426        if (pkg == null) {
7427            Slog.wtf(TAG, "Package was null!", new Throwable());
7428            return;
7429        }
7430        clearAppDataLeafLIF(pkg, userId, flags);
7431        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7432        for (int i = 0; i < childCount; i++) {
7433            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7434        }
7435    }
7436
7437    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7438        final PackageSetting ps;
7439        synchronized (mPackages) {
7440            ps = mSettings.mPackages.get(pkg.packageName);
7441        }
7442        for (int realUserId : resolveUserIds(userId)) {
7443            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7444            try {
7445                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7446                        ceDataInode);
7447            } catch (InstallerException e) {
7448                Slog.w(TAG, String.valueOf(e));
7449            }
7450        }
7451    }
7452
7453    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7454        if (pkg == null) {
7455            Slog.wtf(TAG, "Package was null!", new Throwable());
7456            return;
7457        }
7458        destroyAppDataLeafLIF(pkg, userId, flags);
7459        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7460        for (int i = 0; i < childCount; i++) {
7461            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7462        }
7463    }
7464
7465    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7466        final PackageSetting ps;
7467        synchronized (mPackages) {
7468            ps = mSettings.mPackages.get(pkg.packageName);
7469        }
7470        for (int realUserId : resolveUserIds(userId)) {
7471            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7472            try {
7473                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7474                        ceDataInode);
7475            } catch (InstallerException e) {
7476                Slog.w(TAG, String.valueOf(e));
7477            }
7478        }
7479    }
7480
7481    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7482        if (pkg == null) {
7483            Slog.wtf(TAG, "Package was null!", new Throwable());
7484            return;
7485        }
7486        destroyAppProfilesLeafLIF(pkg);
7487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7488        for (int i = 0; i < childCount; i++) {
7489            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7490        }
7491    }
7492
7493    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7494        try {
7495            mInstaller.destroyAppProfiles(pkg.packageName);
7496        } catch (InstallerException e) {
7497            Slog.w(TAG, String.valueOf(e));
7498        }
7499    }
7500
7501    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7502        if (pkg == null) {
7503            Slog.wtf(TAG, "Package was null!", new Throwable());
7504            return;
7505        }
7506        clearAppProfilesLeafLIF(pkg);
7507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7508        for (int i = 0; i < childCount; i++) {
7509            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7510        }
7511    }
7512
7513    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7514        try {
7515            mInstaller.clearAppProfiles(pkg.packageName);
7516        } catch (InstallerException e) {
7517            Slog.w(TAG, String.valueOf(e));
7518        }
7519    }
7520
7521    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7522            long lastUpdateTime) {
7523        // Set parent install/update time
7524        PackageSetting ps = (PackageSetting) pkg.mExtras;
7525        if (ps != null) {
7526            ps.firstInstallTime = firstInstallTime;
7527            ps.lastUpdateTime = lastUpdateTime;
7528        }
7529        // Set children install/update time
7530        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7531        for (int i = 0; i < childCount; i++) {
7532            PackageParser.Package childPkg = pkg.childPackages.get(i);
7533            ps = (PackageSetting) childPkg.mExtras;
7534            if (ps != null) {
7535                ps.firstInstallTime = firstInstallTime;
7536                ps.lastUpdateTime = lastUpdateTime;
7537            }
7538        }
7539    }
7540
7541    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7542            PackageParser.Package changingLib) {
7543        if (file.path != null) {
7544            usesLibraryFiles.add(file.path);
7545            return;
7546        }
7547        PackageParser.Package p = mPackages.get(file.apk);
7548        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7549            // If we are doing this while in the middle of updating a library apk,
7550            // then we need to make sure to use that new apk for determining the
7551            // dependencies here.  (We haven't yet finished committing the new apk
7552            // to the package manager state.)
7553            if (p == null || p.packageName.equals(changingLib.packageName)) {
7554                p = changingLib;
7555            }
7556        }
7557        if (p != null) {
7558            usesLibraryFiles.addAll(p.getAllCodePaths());
7559        }
7560    }
7561
7562    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7563            PackageParser.Package changingLib) throws PackageManagerException {
7564        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7565            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7566            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7567            for (int i=0; i<N; i++) {
7568                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7569                if (file == null) {
7570                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7571                            "Package " + pkg.packageName + " requires unavailable shared library "
7572                            + pkg.usesLibraries.get(i) + "; failing!");
7573                }
7574                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7575            }
7576            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7577            for (int i=0; i<N; i++) {
7578                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7579                if (file == null) {
7580                    Slog.w(TAG, "Package " + pkg.packageName
7581                            + " desires unavailable shared library "
7582                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7583                } else {
7584                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7585                }
7586            }
7587            N = usesLibraryFiles.size();
7588            if (N > 0) {
7589                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7590            } else {
7591                pkg.usesLibraryFiles = null;
7592            }
7593        }
7594    }
7595
7596    private static boolean hasString(List<String> list, List<String> which) {
7597        if (list == null) {
7598            return false;
7599        }
7600        for (int i=list.size()-1; i>=0; i--) {
7601            for (int j=which.size()-1; j>=0; j--) {
7602                if (which.get(j).equals(list.get(i))) {
7603                    return true;
7604                }
7605            }
7606        }
7607        return false;
7608    }
7609
7610    private void updateAllSharedLibrariesLPw() {
7611        for (PackageParser.Package pkg : mPackages.values()) {
7612            try {
7613                updateSharedLibrariesLPw(pkg, null);
7614            } catch (PackageManagerException e) {
7615                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7616            }
7617        }
7618    }
7619
7620    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7621            PackageParser.Package changingPkg) {
7622        ArrayList<PackageParser.Package> res = null;
7623        for (PackageParser.Package pkg : mPackages.values()) {
7624            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7625                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7626                if (res == null) {
7627                    res = new ArrayList<PackageParser.Package>();
7628                }
7629                res.add(pkg);
7630                try {
7631                    updateSharedLibrariesLPw(pkg, changingPkg);
7632                } catch (PackageManagerException e) {
7633                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7634                }
7635            }
7636        }
7637        return res;
7638    }
7639
7640    /**
7641     * Derive the value of the {@code cpuAbiOverride} based on the provided
7642     * value and an optional stored value from the package settings.
7643     */
7644    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7645        String cpuAbiOverride = null;
7646
7647        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7648            cpuAbiOverride = null;
7649        } else if (abiOverride != null) {
7650            cpuAbiOverride = abiOverride;
7651        } else if (settings != null) {
7652            cpuAbiOverride = settings.cpuAbiOverrideString;
7653        }
7654
7655        return cpuAbiOverride;
7656    }
7657
7658    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7659            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7660                    throws PackageManagerException {
7661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7662        // If the package has children and this is the first dive in the function
7663        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7664        // whether all packages (parent and children) would be successfully scanned
7665        // before the actual scan since scanning mutates internal state and we want
7666        // to atomically install the package and its children.
7667        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7668            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7669                scanFlags |= SCAN_CHECK_ONLY;
7670            }
7671        } else {
7672            scanFlags &= ~SCAN_CHECK_ONLY;
7673        }
7674
7675        final PackageParser.Package scannedPkg;
7676        try {
7677            // Scan the parent
7678            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7679            // Scan the children
7680            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7681            for (int i = 0; i < childCount; i++) {
7682                PackageParser.Package childPkg = pkg.childPackages.get(i);
7683                scanPackageLI(childPkg, policyFlags,
7684                        scanFlags, currentTime, user);
7685            }
7686        } finally {
7687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7688        }
7689
7690        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7691            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7692        }
7693
7694        return scannedPkg;
7695    }
7696
7697    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7698            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7699        boolean success = false;
7700        try {
7701            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7702                    currentTime, user);
7703            success = true;
7704            return res;
7705        } finally {
7706            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7707                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7708                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7709                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7710                destroyAppProfilesLIF(pkg);
7711            }
7712        }
7713    }
7714
7715    /**
7716     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7717     */
7718    private static boolean apkHasCode(String fileName) {
7719        StrictJarFile jarFile = null;
7720        try {
7721            jarFile = new StrictJarFile(fileName,
7722                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7723            return jarFile.findEntry("classes.dex") != null;
7724        } catch (IOException ignore) {
7725        } finally {
7726            try {
7727                jarFile.close();
7728            } catch (IOException ignore) {}
7729        }
7730        return false;
7731    }
7732
7733    /**
7734     * Enforces code policy for the package. This ensures that if an APK has
7735     * declared hasCode="true" in its manifest that the APK actually contains
7736     * code.
7737     *
7738     * @throws PackageManagerException If bytecode could not be found when it should exist
7739     */
7740    private static void enforceCodePolicy(PackageParser.Package pkg)
7741            throws PackageManagerException {
7742        final boolean shouldHaveCode =
7743                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7744        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7745            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7746                    "Package " + pkg.baseCodePath + " code is missing");
7747        }
7748
7749        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7750            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7751                final boolean splitShouldHaveCode =
7752                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7753                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7754                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7755                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7756                }
7757            }
7758        }
7759    }
7760
7761    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7762            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7763            throws PackageManagerException {
7764        final File scanFile = new File(pkg.codePath);
7765        if (pkg.applicationInfo.getCodePath() == null ||
7766                pkg.applicationInfo.getResourcePath() == null) {
7767            // Bail out. The resource and code paths haven't been set.
7768            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7769                    "Code and resource paths haven't been set correctly");
7770        }
7771
7772        // Apply policy
7773        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7774            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7775            if (pkg.applicationInfo.isDirectBootAware()) {
7776                // we're direct boot aware; set for all components
7777                for (PackageParser.Service s : pkg.services) {
7778                    s.info.encryptionAware = s.info.directBootAware = true;
7779                }
7780                for (PackageParser.Provider p : pkg.providers) {
7781                    p.info.encryptionAware = p.info.directBootAware = true;
7782                }
7783                for (PackageParser.Activity a : pkg.activities) {
7784                    a.info.encryptionAware = a.info.directBootAware = true;
7785                }
7786                for (PackageParser.Activity r : pkg.receivers) {
7787                    r.info.encryptionAware = r.info.directBootAware = true;
7788                }
7789            }
7790        } else {
7791            // Only allow system apps to be flagged as core apps.
7792            pkg.coreApp = false;
7793            // clear flags not applicable to regular apps
7794            pkg.applicationInfo.privateFlags &=
7795                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7796            pkg.applicationInfo.privateFlags &=
7797                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7798        }
7799        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7800
7801        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7802            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7803        }
7804
7805        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7806            enforceCodePolicy(pkg);
7807        }
7808
7809        if (mCustomResolverComponentName != null &&
7810                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7811            setUpCustomResolverActivity(pkg);
7812        }
7813
7814        if (pkg.packageName.equals("android")) {
7815            synchronized (mPackages) {
7816                if (mAndroidApplication != null) {
7817                    Slog.w(TAG, "*************************************************");
7818                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7819                    Slog.w(TAG, " file=" + scanFile);
7820                    Slog.w(TAG, "*************************************************");
7821                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7822                            "Core android package being redefined.  Skipping.");
7823                }
7824
7825                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7826                    // Set up information for our fall-back user intent resolution activity.
7827                    mPlatformPackage = pkg;
7828                    pkg.mVersionCode = mSdkVersion;
7829                    mAndroidApplication = pkg.applicationInfo;
7830
7831                    if (!mResolverReplaced) {
7832                        mResolveActivity.applicationInfo = mAndroidApplication;
7833                        mResolveActivity.name = ResolverActivity.class.getName();
7834                        mResolveActivity.packageName = mAndroidApplication.packageName;
7835                        mResolveActivity.processName = "system:ui";
7836                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7837                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7838                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7839                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7840                        mResolveActivity.exported = true;
7841                        mResolveActivity.enabled = true;
7842                        mResolveInfo.activityInfo = mResolveActivity;
7843                        mResolveInfo.priority = 0;
7844                        mResolveInfo.preferredOrder = 0;
7845                        mResolveInfo.match = 0;
7846                        mResolveComponentName = new ComponentName(
7847                                mAndroidApplication.packageName, mResolveActivity.name);
7848                    }
7849                }
7850            }
7851        }
7852
7853        if (DEBUG_PACKAGE_SCANNING) {
7854            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7855                Log.d(TAG, "Scanning package " + pkg.packageName);
7856        }
7857
7858        synchronized (mPackages) {
7859            if (mPackages.containsKey(pkg.packageName)
7860                    || mSharedLibraries.containsKey(pkg.packageName)) {
7861                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7862                        "Application package " + pkg.packageName
7863                                + " already installed.  Skipping duplicate.");
7864            }
7865
7866            // If we're only installing presumed-existing packages, require that the
7867            // scanned APK is both already known and at the path previously established
7868            // for it.  Previously unknown packages we pick up normally, but if we have an
7869            // a priori expectation about this package's install presence, enforce it.
7870            // With a singular exception for new system packages. When an OTA contains
7871            // a new system package, we allow the codepath to change from a system location
7872            // to the user-installed location. If we don't allow this change, any newer,
7873            // user-installed version of the application will be ignored.
7874            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7875                if (mExpectingBetter.containsKey(pkg.packageName)) {
7876                    logCriticalInfo(Log.WARN,
7877                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7878                } else {
7879                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7880                    if (known != null) {
7881                        if (DEBUG_PACKAGE_SCANNING) {
7882                            Log.d(TAG, "Examining " + pkg.codePath
7883                                    + " and requiring known paths " + known.codePathString
7884                                    + " & " + known.resourcePathString);
7885                        }
7886                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7887                                || !pkg.applicationInfo.getResourcePath().equals(
7888                                known.resourcePathString)) {
7889                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7890                                    "Application package " + pkg.packageName
7891                                            + " found at " + pkg.applicationInfo.getCodePath()
7892                                            + " but expected at " + known.codePathString
7893                                            + "; ignoring.");
7894                        }
7895                    }
7896                }
7897            }
7898        }
7899
7900        // Initialize package source and resource directories
7901        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7902        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7903
7904        SharedUserSetting suid = null;
7905        PackageSetting pkgSetting = null;
7906
7907        if (!isSystemApp(pkg)) {
7908            // Only system apps can use these features.
7909            pkg.mOriginalPackages = null;
7910            pkg.mRealPackage = null;
7911            pkg.mAdoptPermissions = null;
7912        }
7913
7914        // Getting the package setting may have a side-effect, so if we
7915        // are only checking if scan would succeed, stash a copy of the
7916        // old setting to restore at the end.
7917        PackageSetting nonMutatedPs = null;
7918
7919        // writer
7920        synchronized (mPackages) {
7921            if (pkg.mSharedUserId != null) {
7922                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7923                if (suid == null) {
7924                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7925                            "Creating application package " + pkg.packageName
7926                            + " for shared user failed");
7927                }
7928                if (DEBUG_PACKAGE_SCANNING) {
7929                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7930                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7931                                + "): packages=" + suid.packages);
7932                }
7933            }
7934
7935            // Check if we are renaming from an original package name.
7936            PackageSetting origPackage = null;
7937            String realName = null;
7938            if (pkg.mOriginalPackages != null) {
7939                // This package may need to be renamed to a previously
7940                // installed name.  Let's check on that...
7941                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7942                if (pkg.mOriginalPackages.contains(renamed)) {
7943                    // This package had originally been installed as the
7944                    // original name, and we have already taken care of
7945                    // transitioning to the new one.  Just update the new
7946                    // one to continue using the old name.
7947                    realName = pkg.mRealPackage;
7948                    if (!pkg.packageName.equals(renamed)) {
7949                        // Callers into this function may have already taken
7950                        // care of renaming the package; only do it here if
7951                        // it is not already done.
7952                        pkg.setPackageName(renamed);
7953                    }
7954
7955                } else {
7956                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7957                        if ((origPackage = mSettings.peekPackageLPr(
7958                                pkg.mOriginalPackages.get(i))) != null) {
7959                            // We do have the package already installed under its
7960                            // original name...  should we use it?
7961                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7962                                // New package is not compatible with original.
7963                                origPackage = null;
7964                                continue;
7965                            } else if (origPackage.sharedUser != null) {
7966                                // Make sure uid is compatible between packages.
7967                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7968                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7969                                            + " to " + pkg.packageName + ": old uid "
7970                                            + origPackage.sharedUser.name
7971                                            + " differs from " + pkg.mSharedUserId);
7972                                    origPackage = null;
7973                                    continue;
7974                                }
7975                                // TODO: Add case when shared user id is added [b/28144775]
7976                            } else {
7977                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7978                                        + pkg.packageName + " to old name " + origPackage.name);
7979                            }
7980                            break;
7981                        }
7982                    }
7983                }
7984            }
7985
7986            if (mTransferedPackages.contains(pkg.packageName)) {
7987                Slog.w(TAG, "Package " + pkg.packageName
7988                        + " was transferred to another, but its .apk remains");
7989            }
7990
7991            // See comments in nonMutatedPs declaration
7992            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7993                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7994                if (foundPs != null) {
7995                    nonMutatedPs = new PackageSetting(foundPs);
7996                }
7997            }
7998
7999            // Just create the setting, don't add it yet. For already existing packages
8000            // the PkgSetting exists already and doesn't have to be created.
8001            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8002                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8003                    pkg.applicationInfo.primaryCpuAbi,
8004                    pkg.applicationInfo.secondaryCpuAbi,
8005                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8006                    user, false);
8007            if (pkgSetting == null) {
8008                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8009                        "Creating application package " + pkg.packageName + " failed");
8010            }
8011
8012            if (pkgSetting.origPackage != null) {
8013                // If we are first transitioning from an original package,
8014                // fix up the new package's name now.  We need to do this after
8015                // looking up the package under its new name, so getPackageLP
8016                // can take care of fiddling things correctly.
8017                pkg.setPackageName(origPackage.name);
8018
8019                // File a report about this.
8020                String msg = "New package " + pkgSetting.realName
8021                        + " renamed to replace old package " + pkgSetting.name;
8022                reportSettingsProblem(Log.WARN, msg);
8023
8024                // Make a note of it.
8025                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8026                    mTransferedPackages.add(origPackage.name);
8027                }
8028
8029                // No longer need to retain this.
8030                pkgSetting.origPackage = null;
8031            }
8032
8033            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8034                // Make a note of it.
8035                mTransferedPackages.add(pkg.packageName);
8036            }
8037
8038            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8039                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8040            }
8041
8042            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8043                // Check all shared libraries and map to their actual file path.
8044                // We only do this here for apps not on a system dir, because those
8045                // are the only ones that can fail an install due to this.  We
8046                // will take care of the system apps by updating all of their
8047                // library paths after the scan is done.
8048                updateSharedLibrariesLPw(pkg, null);
8049            }
8050
8051            if (mFoundPolicyFile) {
8052                SELinuxMMAC.assignSeinfoValue(pkg);
8053            }
8054
8055            pkg.applicationInfo.uid = pkgSetting.appId;
8056            pkg.mExtras = pkgSetting;
8057            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8058                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8059                    // We just determined the app is signed correctly, so bring
8060                    // over the latest parsed certs.
8061                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8062                } else {
8063                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8064                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8065                                "Package " + pkg.packageName + " upgrade keys do not match the "
8066                                + "previously installed version");
8067                    } else {
8068                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8069                        String msg = "System package " + pkg.packageName
8070                            + " signature changed; retaining data.";
8071                        reportSettingsProblem(Log.WARN, msg);
8072                    }
8073                }
8074            } else {
8075                try {
8076                    verifySignaturesLP(pkgSetting, pkg);
8077                    // We just determined the app is signed correctly, so bring
8078                    // over the latest parsed certs.
8079                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8080                } catch (PackageManagerException e) {
8081                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8082                        throw e;
8083                    }
8084                    // The signature has changed, but this package is in the system
8085                    // image...  let's recover!
8086                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8087                    // However...  if this package is part of a shared user, but it
8088                    // doesn't match the signature of the shared user, let's fail.
8089                    // What this means is that you can't change the signatures
8090                    // associated with an overall shared user, which doesn't seem all
8091                    // that unreasonable.
8092                    if (pkgSetting.sharedUser != null) {
8093                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8094                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8095                            throw new PackageManagerException(
8096                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8097                                            "Signature mismatch for shared user: "
8098                                            + pkgSetting.sharedUser);
8099                        }
8100                    }
8101                    // File a report about this.
8102                    String msg = "System package " + pkg.packageName
8103                        + " signature changed; retaining data.";
8104                    reportSettingsProblem(Log.WARN, msg);
8105                }
8106            }
8107            // Verify that this new package doesn't have any content providers
8108            // that conflict with existing packages.  Only do this if the
8109            // package isn't already installed, since we don't want to break
8110            // things that are installed.
8111            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8112                final int N = pkg.providers.size();
8113                int i;
8114                for (i=0; i<N; i++) {
8115                    PackageParser.Provider p = pkg.providers.get(i);
8116                    if (p.info.authority != null) {
8117                        String names[] = p.info.authority.split(";");
8118                        for (int j = 0; j < names.length; j++) {
8119                            if (mProvidersByAuthority.containsKey(names[j])) {
8120                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8121                                final String otherPackageName =
8122                                        ((other != null && other.getComponentName() != null) ?
8123                                                other.getComponentName().getPackageName() : "?");
8124                                throw new PackageManagerException(
8125                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8126                                                "Can't install because provider name " + names[j]
8127                                                + " (in package " + pkg.applicationInfo.packageName
8128                                                + ") is already used by " + otherPackageName);
8129                            }
8130                        }
8131                    }
8132                }
8133            }
8134
8135            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8136                // This package wants to adopt ownership of permissions from
8137                // another package.
8138                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8139                    final String origName = pkg.mAdoptPermissions.get(i);
8140                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8141                    if (orig != null) {
8142                        if (verifyPackageUpdateLPr(orig, pkg)) {
8143                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8144                                    + pkg.packageName);
8145                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8146                        }
8147                    }
8148                }
8149            }
8150        }
8151
8152        final String pkgName = pkg.packageName;
8153
8154        final long scanFileTime = scanFile.lastModified();
8155        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8156        pkg.applicationInfo.processName = fixProcessName(
8157                pkg.applicationInfo.packageName,
8158                pkg.applicationInfo.processName,
8159                pkg.applicationInfo.uid);
8160
8161        if (pkg != mPlatformPackage) {
8162            // Get all of our default paths setup
8163            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8164        }
8165
8166        final String path = scanFile.getPath();
8167        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8168
8169        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8170            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8171
8172            // Some system apps still use directory structure for native libraries
8173            // in which case we might end up not detecting abi solely based on apk
8174            // structure. Try to detect abi based on directory structure.
8175            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8176                    pkg.applicationInfo.primaryCpuAbi == null) {
8177                setBundledAppAbisAndRoots(pkg, pkgSetting);
8178                setNativeLibraryPaths(pkg);
8179            }
8180
8181        } else {
8182            if ((scanFlags & SCAN_MOVE) != 0) {
8183                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8184                // but we already have this packages package info in the PackageSetting. We just
8185                // use that and derive the native library path based on the new codepath.
8186                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8187                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8188            }
8189
8190            // Set native library paths again. For moves, the path will be updated based on the
8191            // ABIs we've determined above. For non-moves, the path will be updated based on the
8192            // ABIs we determined during compilation, but the path will depend on the final
8193            // package path (after the rename away from the stage path).
8194            setNativeLibraryPaths(pkg);
8195        }
8196
8197        // This is a special case for the "system" package, where the ABI is
8198        // dictated by the zygote configuration (and init.rc). We should keep track
8199        // of this ABI so that we can deal with "normal" applications that run under
8200        // the same UID correctly.
8201        if (mPlatformPackage == pkg) {
8202            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8203                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8204        }
8205
8206        // If there's a mismatch between the abi-override in the package setting
8207        // and the abiOverride specified for the install. Warn about this because we
8208        // would've already compiled the app without taking the package setting into
8209        // account.
8210        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8211            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8212                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8213                        " for package " + pkg.packageName);
8214            }
8215        }
8216
8217        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8218        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8219        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8220
8221        // Copy the derived override back to the parsed package, so that we can
8222        // update the package settings accordingly.
8223        pkg.cpuAbiOverride = cpuAbiOverride;
8224
8225        if (DEBUG_ABI_SELECTION) {
8226            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8227                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8228                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8229        }
8230
8231        // Push the derived path down into PackageSettings so we know what to
8232        // clean up at uninstall time.
8233        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8234
8235        if (DEBUG_ABI_SELECTION) {
8236            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8237                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8238                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8239        }
8240
8241        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8242            // We don't do this here during boot because we can do it all
8243            // at once after scanning all existing packages.
8244            //
8245            // We also do this *before* we perform dexopt on this package, so that
8246            // we can avoid redundant dexopts, and also to make sure we've got the
8247            // code and package path correct.
8248            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8249                    pkg, true /* boot complete */);
8250        }
8251
8252        if (mFactoryTest && pkg.requestedPermissions.contains(
8253                android.Manifest.permission.FACTORY_TEST)) {
8254            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8255        }
8256
8257        ArrayList<PackageParser.Package> clientLibPkgs = null;
8258
8259        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8260            if (nonMutatedPs != null) {
8261                synchronized (mPackages) {
8262                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8263                }
8264            }
8265            return pkg;
8266        }
8267
8268        // Only privileged apps and updated privileged apps can add child packages.
8269        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8270            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8271                throw new PackageManagerException("Only privileged apps and updated "
8272                        + "privileged apps can add child packages. Ignoring package "
8273                        + pkg.packageName);
8274            }
8275            final int childCount = pkg.childPackages.size();
8276            for (int i = 0; i < childCount; i++) {
8277                PackageParser.Package childPkg = pkg.childPackages.get(i);
8278                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8279                        childPkg.packageName)) {
8280                    throw new PackageManagerException("Cannot override a child package of "
8281                            + "another disabled system app. Ignoring package " + pkg.packageName);
8282                }
8283            }
8284        }
8285
8286        // writer
8287        synchronized (mPackages) {
8288            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8289                // Only system apps can add new shared libraries.
8290                if (pkg.libraryNames != null) {
8291                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8292                        String name = pkg.libraryNames.get(i);
8293                        boolean allowed = false;
8294                        if (pkg.isUpdatedSystemApp()) {
8295                            // New library entries can only be added through the
8296                            // system image.  This is important to get rid of a lot
8297                            // of nasty edge cases: for example if we allowed a non-
8298                            // system update of the app to add a library, then uninstalling
8299                            // the update would make the library go away, and assumptions
8300                            // we made such as through app install filtering would now
8301                            // have allowed apps on the device which aren't compatible
8302                            // with it.  Better to just have the restriction here, be
8303                            // conservative, and create many fewer cases that can negatively
8304                            // impact the user experience.
8305                            final PackageSetting sysPs = mSettings
8306                                    .getDisabledSystemPkgLPr(pkg.packageName);
8307                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8308                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8309                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8310                                        allowed = true;
8311                                        break;
8312                                    }
8313                                }
8314                            }
8315                        } else {
8316                            allowed = true;
8317                        }
8318                        if (allowed) {
8319                            if (!mSharedLibraries.containsKey(name)) {
8320                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8321                            } else if (!name.equals(pkg.packageName)) {
8322                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8323                                        + name + " already exists; skipping");
8324                            }
8325                        } else {
8326                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8327                                    + name + " that is not declared on system image; skipping");
8328                        }
8329                    }
8330                    if ((scanFlags & SCAN_BOOTING) == 0) {
8331                        // If we are not booting, we need to update any applications
8332                        // that are clients of our shared library.  If we are booting,
8333                        // this will all be done once the scan is complete.
8334                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8335                    }
8336                }
8337            }
8338        }
8339
8340        if ((scanFlags & SCAN_BOOTING) != 0) {
8341            // No apps can run during boot scan, so they don't need to be frozen
8342        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8343            // Caller asked to not kill app, so it's probably not frozen
8344        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8345            // Caller asked us to ignore frozen check for some reason; they
8346            // probably didn't know the package name
8347        } else {
8348            // We're doing major surgery on this package, so it better be frozen
8349            // right now to keep it from launching
8350            checkPackageFrozen(pkgName);
8351        }
8352
8353        // Also need to kill any apps that are dependent on the library.
8354        if (clientLibPkgs != null) {
8355            for (int i=0; i<clientLibPkgs.size(); i++) {
8356                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8357                killApplication(clientPkg.applicationInfo.packageName,
8358                        clientPkg.applicationInfo.uid, "update lib");
8359            }
8360        }
8361
8362        // Make sure we're not adding any bogus keyset info
8363        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8364        ksms.assertScannedPackageValid(pkg);
8365
8366        // writer
8367        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8368
8369        boolean createIdmapFailed = false;
8370        synchronized (mPackages) {
8371            // We don't expect installation to fail beyond this point
8372
8373            // Add the new setting to mSettings
8374            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8375            // Add the new setting to mPackages
8376            mPackages.put(pkg.applicationInfo.packageName, pkg);
8377            // Make sure we don't accidentally delete its data.
8378            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8379            while (iter.hasNext()) {
8380                PackageCleanItem item = iter.next();
8381                if (pkgName.equals(item.packageName)) {
8382                    iter.remove();
8383                }
8384            }
8385
8386            // Take care of first install / last update times.
8387            if (currentTime != 0) {
8388                if (pkgSetting.firstInstallTime == 0) {
8389                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8390                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8391                    pkgSetting.lastUpdateTime = currentTime;
8392                }
8393            } else if (pkgSetting.firstInstallTime == 0) {
8394                // We need *something*.  Take time time stamp of the file.
8395                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8396            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8397                if (scanFileTime != pkgSetting.timeStamp) {
8398                    // A package on the system image has changed; consider this
8399                    // to be an update.
8400                    pkgSetting.lastUpdateTime = scanFileTime;
8401                }
8402            }
8403
8404            // Add the package's KeySets to the global KeySetManagerService
8405            ksms.addScannedPackageLPw(pkg);
8406
8407            int N = pkg.providers.size();
8408            StringBuilder r = null;
8409            int i;
8410            for (i=0; i<N; i++) {
8411                PackageParser.Provider p = pkg.providers.get(i);
8412                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8413                        p.info.processName, pkg.applicationInfo.uid);
8414                mProviders.addProvider(p);
8415                p.syncable = p.info.isSyncable;
8416                if (p.info.authority != null) {
8417                    String names[] = p.info.authority.split(";");
8418                    p.info.authority = null;
8419                    for (int j = 0; j < names.length; j++) {
8420                        if (j == 1 && p.syncable) {
8421                            // We only want the first authority for a provider to possibly be
8422                            // syncable, so if we already added this provider using a different
8423                            // authority clear the syncable flag. We copy the provider before
8424                            // changing it because the mProviders object contains a reference
8425                            // to a provider that we don't want to change.
8426                            // Only do this for the second authority since the resulting provider
8427                            // object can be the same for all future authorities for this provider.
8428                            p = new PackageParser.Provider(p);
8429                            p.syncable = false;
8430                        }
8431                        if (!mProvidersByAuthority.containsKey(names[j])) {
8432                            mProvidersByAuthority.put(names[j], p);
8433                            if (p.info.authority == null) {
8434                                p.info.authority = names[j];
8435                            } else {
8436                                p.info.authority = p.info.authority + ";" + names[j];
8437                            }
8438                            if (DEBUG_PACKAGE_SCANNING) {
8439                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8440                                    Log.d(TAG, "Registered content provider: " + names[j]
8441                                            + ", className = " + p.info.name + ", isSyncable = "
8442                                            + p.info.isSyncable);
8443                            }
8444                        } else {
8445                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8446                            Slog.w(TAG, "Skipping provider name " + names[j] +
8447                                    " (in package " + pkg.applicationInfo.packageName +
8448                                    "): name already used by "
8449                                    + ((other != null && other.getComponentName() != null)
8450                                            ? other.getComponentName().getPackageName() : "?"));
8451                        }
8452                    }
8453                }
8454                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8455                    if (r == null) {
8456                        r = new StringBuilder(256);
8457                    } else {
8458                        r.append(' ');
8459                    }
8460                    r.append(p.info.name);
8461                }
8462            }
8463            if (r != null) {
8464                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8465            }
8466
8467            N = pkg.services.size();
8468            r = null;
8469            for (i=0; i<N; i++) {
8470                PackageParser.Service s = pkg.services.get(i);
8471                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8472                        s.info.processName, pkg.applicationInfo.uid);
8473                mServices.addService(s);
8474                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8475                    if (r == null) {
8476                        r = new StringBuilder(256);
8477                    } else {
8478                        r.append(' ');
8479                    }
8480                    r.append(s.info.name);
8481                }
8482            }
8483            if (r != null) {
8484                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8485            }
8486
8487            N = pkg.receivers.size();
8488            r = null;
8489            for (i=0; i<N; i++) {
8490                PackageParser.Activity a = pkg.receivers.get(i);
8491                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8492                        a.info.processName, pkg.applicationInfo.uid);
8493                mReceivers.addActivity(a, "receiver");
8494                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8495                    if (r == null) {
8496                        r = new StringBuilder(256);
8497                    } else {
8498                        r.append(' ');
8499                    }
8500                    r.append(a.info.name);
8501                }
8502            }
8503            if (r != null) {
8504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8505            }
8506
8507            N = pkg.activities.size();
8508            r = null;
8509            for (i=0; i<N; i++) {
8510                PackageParser.Activity a = pkg.activities.get(i);
8511                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8512                        a.info.processName, pkg.applicationInfo.uid);
8513                mActivities.addActivity(a, "activity");
8514                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8515                    if (r == null) {
8516                        r = new StringBuilder(256);
8517                    } else {
8518                        r.append(' ');
8519                    }
8520                    r.append(a.info.name);
8521                }
8522            }
8523            if (r != null) {
8524                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8525            }
8526
8527            N = pkg.permissionGroups.size();
8528            r = null;
8529            for (i=0; i<N; i++) {
8530                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8531                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8532                if (cur == null) {
8533                    mPermissionGroups.put(pg.info.name, pg);
8534                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8535                        if (r == null) {
8536                            r = new StringBuilder(256);
8537                        } else {
8538                            r.append(' ');
8539                        }
8540                        r.append(pg.info.name);
8541                    }
8542                } else {
8543                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8544                            + pg.info.packageName + " ignored: original from "
8545                            + cur.info.packageName);
8546                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8547                        if (r == null) {
8548                            r = new StringBuilder(256);
8549                        } else {
8550                            r.append(' ');
8551                        }
8552                        r.append("DUP:");
8553                        r.append(pg.info.name);
8554                    }
8555                }
8556            }
8557            if (r != null) {
8558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8559            }
8560
8561            N = pkg.permissions.size();
8562            r = null;
8563            for (i=0; i<N; i++) {
8564                PackageParser.Permission p = pkg.permissions.get(i);
8565
8566                // Assume by default that we did not install this permission into the system.
8567                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8568
8569                // Now that permission groups have a special meaning, we ignore permission
8570                // groups for legacy apps to prevent unexpected behavior. In particular,
8571                // permissions for one app being granted to someone just becase they happen
8572                // to be in a group defined by another app (before this had no implications).
8573                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8574                    p.group = mPermissionGroups.get(p.info.group);
8575                    // Warn for a permission in an unknown group.
8576                    if (p.info.group != null && p.group == null) {
8577                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8578                                + p.info.packageName + " in an unknown group " + p.info.group);
8579                    }
8580                }
8581
8582                ArrayMap<String, BasePermission> permissionMap =
8583                        p.tree ? mSettings.mPermissionTrees
8584                                : mSettings.mPermissions;
8585                BasePermission bp = permissionMap.get(p.info.name);
8586
8587                // Allow system apps to redefine non-system permissions
8588                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8589                    final boolean currentOwnerIsSystem = (bp.perm != null
8590                            && isSystemApp(bp.perm.owner));
8591                    if (isSystemApp(p.owner)) {
8592                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8593                            // It's a built-in permission and no owner, take ownership now
8594                            bp.packageSetting = pkgSetting;
8595                            bp.perm = p;
8596                            bp.uid = pkg.applicationInfo.uid;
8597                            bp.sourcePackage = p.info.packageName;
8598                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8599                        } else if (!currentOwnerIsSystem) {
8600                            String msg = "New decl " + p.owner + " of permission  "
8601                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8602                            reportSettingsProblem(Log.WARN, msg);
8603                            bp = null;
8604                        }
8605                    }
8606                }
8607
8608                if (bp == null) {
8609                    bp = new BasePermission(p.info.name, p.info.packageName,
8610                            BasePermission.TYPE_NORMAL);
8611                    permissionMap.put(p.info.name, bp);
8612                }
8613
8614                if (bp.perm == null) {
8615                    if (bp.sourcePackage == null
8616                            || bp.sourcePackage.equals(p.info.packageName)) {
8617                        BasePermission tree = findPermissionTreeLP(p.info.name);
8618                        if (tree == null
8619                                || tree.sourcePackage.equals(p.info.packageName)) {
8620                            bp.packageSetting = pkgSetting;
8621                            bp.perm = p;
8622                            bp.uid = pkg.applicationInfo.uid;
8623                            bp.sourcePackage = p.info.packageName;
8624                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8625                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8626                                if (r == null) {
8627                                    r = new StringBuilder(256);
8628                                } else {
8629                                    r.append(' ');
8630                                }
8631                                r.append(p.info.name);
8632                            }
8633                        } else {
8634                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8635                                    + p.info.packageName + " ignored: base tree "
8636                                    + tree.name + " is from package "
8637                                    + tree.sourcePackage);
8638                        }
8639                    } else {
8640                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8641                                + p.info.packageName + " ignored: original from "
8642                                + bp.sourcePackage);
8643                    }
8644                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8645                    if (r == null) {
8646                        r = new StringBuilder(256);
8647                    } else {
8648                        r.append(' ');
8649                    }
8650                    r.append("DUP:");
8651                    r.append(p.info.name);
8652                }
8653                if (bp.perm == p) {
8654                    bp.protectionLevel = p.info.protectionLevel;
8655                }
8656            }
8657
8658            if (r != null) {
8659                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8660            }
8661
8662            N = pkg.instrumentation.size();
8663            r = null;
8664            for (i=0; i<N; i++) {
8665                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8666                a.info.packageName = pkg.applicationInfo.packageName;
8667                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8668                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8669                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8670                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8671                a.info.dataDir = pkg.applicationInfo.dataDir;
8672                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8673                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8674
8675                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8676                // need other information about the application, like the ABI and what not ?
8677                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8678                mInstrumentation.put(a.getComponentName(), a);
8679                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8680                    if (r == null) {
8681                        r = new StringBuilder(256);
8682                    } else {
8683                        r.append(' ');
8684                    }
8685                    r.append(a.info.name);
8686                }
8687            }
8688            if (r != null) {
8689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8690            }
8691
8692            if (pkg.protectedBroadcasts != null) {
8693                N = pkg.protectedBroadcasts.size();
8694                for (i=0; i<N; i++) {
8695                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8696                }
8697            }
8698
8699            pkgSetting.setTimeStamp(scanFileTime);
8700
8701            // Create idmap files for pairs of (packages, overlay packages).
8702            // Note: "android", ie framework-res.apk, is handled by native layers.
8703            if (pkg.mOverlayTarget != null) {
8704                // This is an overlay package.
8705                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8706                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8707                        mOverlays.put(pkg.mOverlayTarget,
8708                                new ArrayMap<String, PackageParser.Package>());
8709                    }
8710                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8711                    map.put(pkg.packageName, pkg);
8712                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8713                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8714                        createIdmapFailed = true;
8715                    }
8716                }
8717            } else if (mOverlays.containsKey(pkg.packageName) &&
8718                    !pkg.packageName.equals("android")) {
8719                // This is a regular package, with one or more known overlay packages.
8720                createIdmapsForPackageLI(pkg);
8721            }
8722        }
8723
8724        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8725
8726        if (createIdmapFailed) {
8727            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8728                    "scanPackageLI failed to createIdmap");
8729        }
8730        return pkg;
8731    }
8732
8733    /**
8734     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8735     * is derived purely on the basis of the contents of {@code scanFile} and
8736     * {@code cpuAbiOverride}.
8737     *
8738     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8739     */
8740    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8741                                 String cpuAbiOverride, boolean extractLibs)
8742            throws PackageManagerException {
8743        // TODO: We can probably be smarter about this stuff. For installed apps,
8744        // we can calculate this information at install time once and for all. For
8745        // system apps, we can probably assume that this information doesn't change
8746        // after the first boot scan. As things stand, we do lots of unnecessary work.
8747
8748        // Give ourselves some initial paths; we'll come back for another
8749        // pass once we've determined ABI below.
8750        setNativeLibraryPaths(pkg);
8751
8752        // We would never need to extract libs for forward-locked and external packages,
8753        // since the container service will do it for us. We shouldn't attempt to
8754        // extract libs from system app when it was not updated.
8755        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8756                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8757            extractLibs = false;
8758        }
8759
8760        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8761        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8762
8763        NativeLibraryHelper.Handle handle = null;
8764        try {
8765            handle = NativeLibraryHelper.Handle.create(pkg);
8766            // TODO(multiArch): This can be null for apps that didn't go through the
8767            // usual installation process. We can calculate it again, like we
8768            // do during install time.
8769            //
8770            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8771            // unnecessary.
8772            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8773
8774            // Null out the abis so that they can be recalculated.
8775            pkg.applicationInfo.primaryCpuAbi = null;
8776            pkg.applicationInfo.secondaryCpuAbi = null;
8777            if (isMultiArch(pkg.applicationInfo)) {
8778                // Warn if we've set an abiOverride for multi-lib packages..
8779                // By definition, we need to copy both 32 and 64 bit libraries for
8780                // such packages.
8781                if (pkg.cpuAbiOverride != null
8782                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8783                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8784                }
8785
8786                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8787                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8788                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8789                    if (extractLibs) {
8790                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8791                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8792                                useIsaSpecificSubdirs);
8793                    } else {
8794                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8795                    }
8796                }
8797
8798                maybeThrowExceptionForMultiArchCopy(
8799                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8800
8801                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8802                    if (extractLibs) {
8803                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8804                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8805                                useIsaSpecificSubdirs);
8806                    } else {
8807                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8808                    }
8809                }
8810
8811                maybeThrowExceptionForMultiArchCopy(
8812                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8813
8814                if (abi64 >= 0) {
8815                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8816                }
8817
8818                if (abi32 >= 0) {
8819                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8820                    if (abi64 >= 0) {
8821                        if (pkg.use32bitAbi) {
8822                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8823                            pkg.applicationInfo.primaryCpuAbi = abi;
8824                        } else {
8825                            pkg.applicationInfo.secondaryCpuAbi = abi;
8826                        }
8827                    } else {
8828                        pkg.applicationInfo.primaryCpuAbi = abi;
8829                    }
8830                }
8831
8832            } else {
8833                String[] abiList = (cpuAbiOverride != null) ?
8834                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8835
8836                // Enable gross and lame hacks for apps that are built with old
8837                // SDK tools. We must scan their APKs for renderscript bitcode and
8838                // not launch them if it's present. Don't bother checking on devices
8839                // that don't have 64 bit support.
8840                boolean needsRenderScriptOverride = false;
8841                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8842                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8843                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8844                    needsRenderScriptOverride = true;
8845                }
8846
8847                final int copyRet;
8848                if (extractLibs) {
8849                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8850                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8851                } else {
8852                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8853                }
8854
8855                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8856                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8857                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8858                }
8859
8860                if (copyRet >= 0) {
8861                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8862                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8863                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8864                } else if (needsRenderScriptOverride) {
8865                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8866                }
8867            }
8868        } catch (IOException ioe) {
8869            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8870        } finally {
8871            IoUtils.closeQuietly(handle);
8872        }
8873
8874        // Now that we've calculated the ABIs and determined if it's an internal app,
8875        // we will go ahead and populate the nativeLibraryPath.
8876        setNativeLibraryPaths(pkg);
8877    }
8878
8879    /**
8880     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8881     * i.e, so that all packages can be run inside a single process if required.
8882     *
8883     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8884     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8885     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8886     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8887     * updating a package that belongs to a shared user.
8888     *
8889     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8890     * adds unnecessary complexity.
8891     */
8892    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8893            PackageParser.Package scannedPackage, boolean bootComplete) {
8894        String requiredInstructionSet = null;
8895        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8896            requiredInstructionSet = VMRuntime.getInstructionSet(
8897                     scannedPackage.applicationInfo.primaryCpuAbi);
8898        }
8899
8900        PackageSetting requirer = null;
8901        for (PackageSetting ps : packagesForUser) {
8902            // If packagesForUser contains scannedPackage, we skip it. This will happen
8903            // when scannedPackage is an update of an existing package. Without this check,
8904            // we will never be able to change the ABI of any package belonging to a shared
8905            // user, even if it's compatible with other packages.
8906            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8907                if (ps.primaryCpuAbiString == null) {
8908                    continue;
8909                }
8910
8911                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8912                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8913                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8914                    // this but there's not much we can do.
8915                    String errorMessage = "Instruction set mismatch, "
8916                            + ((requirer == null) ? "[caller]" : requirer)
8917                            + " requires " + requiredInstructionSet + " whereas " + ps
8918                            + " requires " + instructionSet;
8919                    Slog.w(TAG, errorMessage);
8920                }
8921
8922                if (requiredInstructionSet == null) {
8923                    requiredInstructionSet = instructionSet;
8924                    requirer = ps;
8925                }
8926            }
8927        }
8928
8929        if (requiredInstructionSet != null) {
8930            String adjustedAbi;
8931            if (requirer != null) {
8932                // requirer != null implies that either scannedPackage was null or that scannedPackage
8933                // did not require an ABI, in which case we have to adjust scannedPackage to match
8934                // the ABI of the set (which is the same as requirer's ABI)
8935                adjustedAbi = requirer.primaryCpuAbiString;
8936                if (scannedPackage != null) {
8937                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8938                }
8939            } else {
8940                // requirer == null implies that we're updating all ABIs in the set to
8941                // match scannedPackage.
8942                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8943            }
8944
8945            for (PackageSetting ps : packagesForUser) {
8946                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8947                    if (ps.primaryCpuAbiString != null) {
8948                        continue;
8949                    }
8950
8951                    ps.primaryCpuAbiString = adjustedAbi;
8952                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8953                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8954                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8955                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8956                                + " (requirer="
8957                                + (requirer == null ? "null" : requirer.pkg.packageName)
8958                                + ", scannedPackage="
8959                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8960                                + ")");
8961                        try {
8962                            mInstaller.rmdex(ps.codePathString,
8963                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8964                        } catch (InstallerException ignored) {
8965                        }
8966                    }
8967                }
8968            }
8969        }
8970    }
8971
8972    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8973        synchronized (mPackages) {
8974            mResolverReplaced = true;
8975            // Set up information for custom user intent resolution activity.
8976            mResolveActivity.applicationInfo = pkg.applicationInfo;
8977            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8978            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8979            mResolveActivity.processName = pkg.applicationInfo.packageName;
8980            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8981            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8982                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8983            mResolveActivity.theme = 0;
8984            mResolveActivity.exported = true;
8985            mResolveActivity.enabled = true;
8986            mResolveInfo.activityInfo = mResolveActivity;
8987            mResolveInfo.priority = 0;
8988            mResolveInfo.preferredOrder = 0;
8989            mResolveInfo.match = 0;
8990            mResolveComponentName = mCustomResolverComponentName;
8991            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8992                    mResolveComponentName);
8993        }
8994    }
8995
8996    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8997        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8998
8999        // Set up information for ephemeral installer activity
9000        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9001        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9002        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9003        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9004        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9005        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9006                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9007        mEphemeralInstallerActivity.theme = 0;
9008        mEphemeralInstallerActivity.exported = true;
9009        mEphemeralInstallerActivity.enabled = true;
9010        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9011        mEphemeralInstallerInfo.priority = 0;
9012        mEphemeralInstallerInfo.preferredOrder = 0;
9013        mEphemeralInstallerInfo.match = 0;
9014
9015        if (DEBUG_EPHEMERAL) {
9016            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9017        }
9018    }
9019
9020    private static String calculateBundledApkRoot(final String codePathString) {
9021        final File codePath = new File(codePathString);
9022        final File codeRoot;
9023        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9024            codeRoot = Environment.getRootDirectory();
9025        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9026            codeRoot = Environment.getOemDirectory();
9027        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9028            codeRoot = Environment.getVendorDirectory();
9029        } else {
9030            // Unrecognized code path; take its top real segment as the apk root:
9031            // e.g. /something/app/blah.apk => /something
9032            try {
9033                File f = codePath.getCanonicalFile();
9034                File parent = f.getParentFile();    // non-null because codePath is a file
9035                File tmp;
9036                while ((tmp = parent.getParentFile()) != null) {
9037                    f = parent;
9038                    parent = tmp;
9039                }
9040                codeRoot = f;
9041                Slog.w(TAG, "Unrecognized code path "
9042                        + codePath + " - using " + codeRoot);
9043            } catch (IOException e) {
9044                // Can't canonicalize the code path -- shenanigans?
9045                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9046                return Environment.getRootDirectory().getPath();
9047            }
9048        }
9049        return codeRoot.getPath();
9050    }
9051
9052    /**
9053     * Derive and set the location of native libraries for the given package,
9054     * which varies depending on where and how the package was installed.
9055     */
9056    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9057        final ApplicationInfo info = pkg.applicationInfo;
9058        final String codePath = pkg.codePath;
9059        final File codeFile = new File(codePath);
9060        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9061        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9062
9063        info.nativeLibraryRootDir = null;
9064        info.nativeLibraryRootRequiresIsa = false;
9065        info.nativeLibraryDir = null;
9066        info.secondaryNativeLibraryDir = null;
9067
9068        if (isApkFile(codeFile)) {
9069            // Monolithic install
9070            if (bundledApp) {
9071                // If "/system/lib64/apkname" exists, assume that is the per-package
9072                // native library directory to use; otherwise use "/system/lib/apkname".
9073                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9074                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9075                        getPrimaryInstructionSet(info));
9076
9077                // This is a bundled system app so choose the path based on the ABI.
9078                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9079                // is just the default path.
9080                final String apkName = deriveCodePathName(codePath);
9081                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9082                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9083                        apkName).getAbsolutePath();
9084
9085                if (info.secondaryCpuAbi != null) {
9086                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9087                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9088                            secondaryLibDir, apkName).getAbsolutePath();
9089                }
9090            } else if (asecApp) {
9091                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9092                        .getAbsolutePath();
9093            } else {
9094                final String apkName = deriveCodePathName(codePath);
9095                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9096                        .getAbsolutePath();
9097            }
9098
9099            info.nativeLibraryRootRequiresIsa = false;
9100            info.nativeLibraryDir = info.nativeLibraryRootDir;
9101        } else {
9102            // Cluster install
9103            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9104            info.nativeLibraryRootRequiresIsa = true;
9105
9106            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9107                    getPrimaryInstructionSet(info)).getAbsolutePath();
9108
9109            if (info.secondaryCpuAbi != null) {
9110                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9111                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9112            }
9113        }
9114    }
9115
9116    /**
9117     * Calculate the abis and roots for a bundled app. These can uniquely
9118     * be determined from the contents of the system partition, i.e whether
9119     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9120     * of this information, and instead assume that the system was built
9121     * sensibly.
9122     */
9123    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9124                                           PackageSetting pkgSetting) {
9125        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9126
9127        // If "/system/lib64/apkname" exists, assume that is the per-package
9128        // native library directory to use; otherwise use "/system/lib/apkname".
9129        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9130        setBundledAppAbi(pkg, apkRoot, apkName);
9131        // pkgSetting might be null during rescan following uninstall of updates
9132        // to a bundled app, so accommodate that possibility.  The settings in
9133        // that case will be established later from the parsed package.
9134        //
9135        // If the settings aren't null, sync them up with what we've just derived.
9136        // note that apkRoot isn't stored in the package settings.
9137        if (pkgSetting != null) {
9138            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9139            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9140        }
9141    }
9142
9143    /**
9144     * Deduces the ABI of a bundled app and sets the relevant fields on the
9145     * parsed pkg object.
9146     *
9147     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9148     *        under which system libraries are installed.
9149     * @param apkName the name of the installed package.
9150     */
9151    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9152        final File codeFile = new File(pkg.codePath);
9153
9154        final boolean has64BitLibs;
9155        final boolean has32BitLibs;
9156        if (isApkFile(codeFile)) {
9157            // Monolithic install
9158            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9159            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9160        } else {
9161            // Cluster install
9162            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9163            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9164                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9165                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9166                has64BitLibs = (new File(rootDir, isa)).exists();
9167            } else {
9168                has64BitLibs = false;
9169            }
9170            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9171                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9172                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9173                has32BitLibs = (new File(rootDir, isa)).exists();
9174            } else {
9175                has32BitLibs = false;
9176            }
9177        }
9178
9179        if (has64BitLibs && !has32BitLibs) {
9180            // The package has 64 bit libs, but not 32 bit libs. Its primary
9181            // ABI should be 64 bit. We can safely assume here that the bundled
9182            // native libraries correspond to the most preferred ABI in the list.
9183
9184            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9185            pkg.applicationInfo.secondaryCpuAbi = null;
9186        } else if (has32BitLibs && !has64BitLibs) {
9187            // The package has 32 bit libs but not 64 bit libs. Its primary
9188            // ABI should be 32 bit.
9189
9190            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9191            pkg.applicationInfo.secondaryCpuAbi = null;
9192        } else if (has32BitLibs && has64BitLibs) {
9193            // The application has both 64 and 32 bit bundled libraries. We check
9194            // here that the app declares multiArch support, and warn if it doesn't.
9195            //
9196            // We will be lenient here and record both ABIs. The primary will be the
9197            // ABI that's higher on the list, i.e, a device that's configured to prefer
9198            // 64 bit apps will see a 64 bit primary ABI,
9199
9200            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9201                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9202            }
9203
9204            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9205                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9206                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9207            } else {
9208                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9209                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9210            }
9211        } else {
9212            pkg.applicationInfo.primaryCpuAbi = null;
9213            pkg.applicationInfo.secondaryCpuAbi = null;
9214        }
9215    }
9216
9217    private void killApplication(String pkgName, int appId, String reason) {
9218        // Request the ActivityManager to kill the process(only for existing packages)
9219        // so that we do not end up in a confused state while the user is still using the older
9220        // version of the application while the new one gets installed.
9221        final long token = Binder.clearCallingIdentity();
9222        try {
9223            IActivityManager am = ActivityManagerNative.getDefault();
9224            if (am != null) {
9225                try {
9226                    am.killApplicationWithAppId(pkgName, appId, reason);
9227                } catch (RemoteException e) {
9228                }
9229            }
9230        } finally {
9231            Binder.restoreCallingIdentity(token);
9232        }
9233    }
9234
9235    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9236        // Remove the parent package setting
9237        PackageSetting ps = (PackageSetting) pkg.mExtras;
9238        if (ps != null) {
9239            removePackageLI(ps, chatty);
9240        }
9241        // Remove the child package setting
9242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9243        for (int i = 0; i < childCount; i++) {
9244            PackageParser.Package childPkg = pkg.childPackages.get(i);
9245            ps = (PackageSetting) childPkg.mExtras;
9246            if (ps != null) {
9247                removePackageLI(ps, chatty);
9248            }
9249        }
9250    }
9251
9252    void removePackageLI(PackageSetting ps, boolean chatty) {
9253        if (DEBUG_INSTALL) {
9254            if (chatty)
9255                Log.d(TAG, "Removing package " + ps.name);
9256        }
9257
9258        // writer
9259        synchronized (mPackages) {
9260            mPackages.remove(ps.name);
9261            final PackageParser.Package pkg = ps.pkg;
9262            if (pkg != null) {
9263                cleanPackageDataStructuresLILPw(pkg, chatty);
9264            }
9265        }
9266    }
9267
9268    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9269        if (DEBUG_INSTALL) {
9270            if (chatty)
9271                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9272        }
9273
9274        // writer
9275        synchronized (mPackages) {
9276            // Remove the parent package
9277            mPackages.remove(pkg.applicationInfo.packageName);
9278            cleanPackageDataStructuresLILPw(pkg, chatty);
9279
9280            // Remove the child packages
9281            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9282            for (int i = 0; i < childCount; i++) {
9283                PackageParser.Package childPkg = pkg.childPackages.get(i);
9284                mPackages.remove(childPkg.applicationInfo.packageName);
9285                cleanPackageDataStructuresLILPw(childPkg, chatty);
9286            }
9287        }
9288    }
9289
9290    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9291        int N = pkg.providers.size();
9292        StringBuilder r = null;
9293        int i;
9294        for (i=0; i<N; i++) {
9295            PackageParser.Provider p = pkg.providers.get(i);
9296            mProviders.removeProvider(p);
9297            if (p.info.authority == null) {
9298
9299                /* There was another ContentProvider with this authority when
9300                 * this app was installed so this authority is null,
9301                 * Ignore it as we don't have to unregister the provider.
9302                 */
9303                continue;
9304            }
9305            String names[] = p.info.authority.split(";");
9306            for (int j = 0; j < names.length; j++) {
9307                if (mProvidersByAuthority.get(names[j]) == p) {
9308                    mProvidersByAuthority.remove(names[j]);
9309                    if (DEBUG_REMOVE) {
9310                        if (chatty)
9311                            Log.d(TAG, "Unregistered content provider: " + names[j]
9312                                    + ", className = " + p.info.name + ", isSyncable = "
9313                                    + p.info.isSyncable);
9314                    }
9315                }
9316            }
9317            if (DEBUG_REMOVE && chatty) {
9318                if (r == null) {
9319                    r = new StringBuilder(256);
9320                } else {
9321                    r.append(' ');
9322                }
9323                r.append(p.info.name);
9324            }
9325        }
9326        if (r != null) {
9327            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9328        }
9329
9330        N = pkg.services.size();
9331        r = null;
9332        for (i=0; i<N; i++) {
9333            PackageParser.Service s = pkg.services.get(i);
9334            mServices.removeService(s);
9335            if (chatty) {
9336                if (r == null) {
9337                    r = new StringBuilder(256);
9338                } else {
9339                    r.append(' ');
9340                }
9341                r.append(s.info.name);
9342            }
9343        }
9344        if (r != null) {
9345            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9346        }
9347
9348        N = pkg.receivers.size();
9349        r = null;
9350        for (i=0; i<N; i++) {
9351            PackageParser.Activity a = pkg.receivers.get(i);
9352            mReceivers.removeActivity(a, "receiver");
9353            if (DEBUG_REMOVE && chatty) {
9354                if (r == null) {
9355                    r = new StringBuilder(256);
9356                } else {
9357                    r.append(' ');
9358                }
9359                r.append(a.info.name);
9360            }
9361        }
9362        if (r != null) {
9363            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9364        }
9365
9366        N = pkg.activities.size();
9367        r = null;
9368        for (i=0; i<N; i++) {
9369            PackageParser.Activity a = pkg.activities.get(i);
9370            mActivities.removeActivity(a, "activity");
9371            if (DEBUG_REMOVE && chatty) {
9372                if (r == null) {
9373                    r = new StringBuilder(256);
9374                } else {
9375                    r.append(' ');
9376                }
9377                r.append(a.info.name);
9378            }
9379        }
9380        if (r != null) {
9381            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9382        }
9383
9384        N = pkg.permissions.size();
9385        r = null;
9386        for (i=0; i<N; i++) {
9387            PackageParser.Permission p = pkg.permissions.get(i);
9388            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9389            if (bp == null) {
9390                bp = mSettings.mPermissionTrees.get(p.info.name);
9391            }
9392            if (bp != null && bp.perm == p) {
9393                bp.perm = null;
9394                if (DEBUG_REMOVE && chatty) {
9395                    if (r == null) {
9396                        r = new StringBuilder(256);
9397                    } else {
9398                        r.append(' ');
9399                    }
9400                    r.append(p.info.name);
9401                }
9402            }
9403            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9404                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9405                if (appOpPkgs != null) {
9406                    appOpPkgs.remove(pkg.packageName);
9407                }
9408            }
9409        }
9410        if (r != null) {
9411            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9412        }
9413
9414        N = pkg.requestedPermissions.size();
9415        r = null;
9416        for (i=0; i<N; i++) {
9417            String perm = pkg.requestedPermissions.get(i);
9418            BasePermission bp = mSettings.mPermissions.get(perm);
9419            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9420                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9421                if (appOpPkgs != null) {
9422                    appOpPkgs.remove(pkg.packageName);
9423                    if (appOpPkgs.isEmpty()) {
9424                        mAppOpPermissionPackages.remove(perm);
9425                    }
9426                }
9427            }
9428        }
9429        if (r != null) {
9430            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9431        }
9432
9433        N = pkg.instrumentation.size();
9434        r = null;
9435        for (i=0; i<N; i++) {
9436            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9437            mInstrumentation.remove(a.getComponentName());
9438            if (DEBUG_REMOVE && chatty) {
9439                if (r == null) {
9440                    r = new StringBuilder(256);
9441                } else {
9442                    r.append(' ');
9443                }
9444                r.append(a.info.name);
9445            }
9446        }
9447        if (r != null) {
9448            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9449        }
9450
9451        r = null;
9452        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9453            // Only system apps can hold shared libraries.
9454            if (pkg.libraryNames != null) {
9455                for (i=0; i<pkg.libraryNames.size(); i++) {
9456                    String name = pkg.libraryNames.get(i);
9457                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9458                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9459                        mSharedLibraries.remove(name);
9460                        if (DEBUG_REMOVE && chatty) {
9461                            if (r == null) {
9462                                r = new StringBuilder(256);
9463                            } else {
9464                                r.append(' ');
9465                            }
9466                            r.append(name);
9467                        }
9468                    }
9469                }
9470            }
9471        }
9472        if (r != null) {
9473            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9474        }
9475    }
9476
9477    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9478        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9479            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9480                return true;
9481            }
9482        }
9483        return false;
9484    }
9485
9486    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9487    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9488    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9489
9490    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9491        // Update the parent permissions
9492        updatePermissionsLPw(pkg.packageName, pkg, flags);
9493        // Update the child permissions
9494        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9495        for (int i = 0; i < childCount; i++) {
9496            PackageParser.Package childPkg = pkg.childPackages.get(i);
9497            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9498        }
9499    }
9500
9501    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9502            int flags) {
9503        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9504        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9505    }
9506
9507    private void updatePermissionsLPw(String changingPkg,
9508            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9509        // Make sure there are no dangling permission trees.
9510        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9511        while (it.hasNext()) {
9512            final BasePermission bp = it.next();
9513            if (bp.packageSetting == null) {
9514                // We may not yet have parsed the package, so just see if
9515                // we still know about its settings.
9516                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9517            }
9518            if (bp.packageSetting == null) {
9519                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9520                        + " from package " + bp.sourcePackage);
9521                it.remove();
9522            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9523                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9524                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9525                            + " from package " + bp.sourcePackage);
9526                    flags |= UPDATE_PERMISSIONS_ALL;
9527                    it.remove();
9528                }
9529            }
9530        }
9531
9532        // Make sure all dynamic permissions have been assigned to a package,
9533        // and make sure there are no dangling permissions.
9534        it = mSettings.mPermissions.values().iterator();
9535        while (it.hasNext()) {
9536            final BasePermission bp = it.next();
9537            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9538                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9539                        + bp.name + " pkg=" + bp.sourcePackage
9540                        + " info=" + bp.pendingInfo);
9541                if (bp.packageSetting == null && bp.pendingInfo != null) {
9542                    final BasePermission tree = findPermissionTreeLP(bp.name);
9543                    if (tree != null && tree.perm != null) {
9544                        bp.packageSetting = tree.packageSetting;
9545                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9546                                new PermissionInfo(bp.pendingInfo));
9547                        bp.perm.info.packageName = tree.perm.info.packageName;
9548                        bp.perm.info.name = bp.name;
9549                        bp.uid = tree.uid;
9550                    }
9551                }
9552            }
9553            if (bp.packageSetting == null) {
9554                // We may not yet have parsed the package, so just see if
9555                // we still know about its settings.
9556                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9557            }
9558            if (bp.packageSetting == null) {
9559                Slog.w(TAG, "Removing dangling permission: " + bp.name
9560                        + " from package " + bp.sourcePackage);
9561                it.remove();
9562            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9563                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9564                    Slog.i(TAG, "Removing old permission: " + bp.name
9565                            + " from package " + bp.sourcePackage);
9566                    flags |= UPDATE_PERMISSIONS_ALL;
9567                    it.remove();
9568                }
9569            }
9570        }
9571
9572        // Now update the permissions for all packages, in particular
9573        // replace the granted permissions of the system packages.
9574        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9575            for (PackageParser.Package pkg : mPackages.values()) {
9576                if (pkg != pkgInfo) {
9577                    // Only replace for packages on requested volume
9578                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9579                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9580                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9581                    grantPermissionsLPw(pkg, replace, changingPkg);
9582                }
9583            }
9584        }
9585
9586        if (pkgInfo != null) {
9587            // Only replace for packages on requested volume
9588            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9589            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9590                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9591            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9592        }
9593    }
9594
9595    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9596            String packageOfInterest) {
9597        // IMPORTANT: There are two types of permissions: install and runtime.
9598        // Install time permissions are granted when the app is installed to
9599        // all device users and users added in the future. Runtime permissions
9600        // are granted at runtime explicitly to specific users. Normal and signature
9601        // protected permissions are install time permissions. Dangerous permissions
9602        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9603        // otherwise they are runtime permissions. This function does not manage
9604        // runtime permissions except for the case an app targeting Lollipop MR1
9605        // being upgraded to target a newer SDK, in which case dangerous permissions
9606        // are transformed from install time to runtime ones.
9607
9608        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9609        if (ps == null) {
9610            return;
9611        }
9612
9613        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9614
9615        PermissionsState permissionsState = ps.getPermissionsState();
9616        PermissionsState origPermissions = permissionsState;
9617
9618        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9619
9620        boolean runtimePermissionsRevoked = false;
9621        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9622
9623        boolean changedInstallPermission = false;
9624
9625        if (replace) {
9626            ps.installPermissionsFixed = false;
9627            if (!ps.isSharedUser()) {
9628                origPermissions = new PermissionsState(permissionsState);
9629                permissionsState.reset();
9630            } else {
9631                // We need to know only about runtime permission changes since the
9632                // calling code always writes the install permissions state but
9633                // the runtime ones are written only if changed. The only cases of
9634                // changed runtime permissions here are promotion of an install to
9635                // runtime and revocation of a runtime from a shared user.
9636                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9637                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9638                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9639                    runtimePermissionsRevoked = true;
9640                }
9641            }
9642        }
9643
9644        permissionsState.setGlobalGids(mGlobalGids);
9645
9646        final int N = pkg.requestedPermissions.size();
9647        for (int i=0; i<N; i++) {
9648            final String name = pkg.requestedPermissions.get(i);
9649            final BasePermission bp = mSettings.mPermissions.get(name);
9650
9651            if (DEBUG_INSTALL) {
9652                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9653            }
9654
9655            if (bp == null || bp.packageSetting == null) {
9656                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9657                    Slog.w(TAG, "Unknown permission " + name
9658                            + " in package " + pkg.packageName);
9659                }
9660                continue;
9661            }
9662
9663            final String perm = bp.name;
9664            boolean allowedSig = false;
9665            int grant = GRANT_DENIED;
9666
9667            // Keep track of app op permissions.
9668            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9669                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9670                if (pkgs == null) {
9671                    pkgs = new ArraySet<>();
9672                    mAppOpPermissionPackages.put(bp.name, pkgs);
9673                }
9674                pkgs.add(pkg.packageName);
9675            }
9676
9677            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9678            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9679                    >= Build.VERSION_CODES.M;
9680            switch (level) {
9681                case PermissionInfo.PROTECTION_NORMAL: {
9682                    // For all apps normal permissions are install time ones.
9683                    grant = GRANT_INSTALL;
9684                } break;
9685
9686                case PermissionInfo.PROTECTION_DANGEROUS: {
9687                    // If a permission review is required for legacy apps we represent
9688                    // their permissions as always granted runtime ones since we need
9689                    // to keep the review required permission flag per user while an
9690                    // install permission's state is shared across all users.
9691                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9692                        // For legacy apps dangerous permissions are install time ones.
9693                        grant = GRANT_INSTALL;
9694                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9695                        // For legacy apps that became modern, install becomes runtime.
9696                        grant = GRANT_UPGRADE;
9697                    } else if (mPromoteSystemApps
9698                            && isSystemApp(ps)
9699                            && mExistingSystemPackages.contains(ps.name)) {
9700                        // For legacy system apps, install becomes runtime.
9701                        // We cannot check hasInstallPermission() for system apps since those
9702                        // permissions were granted implicitly and not persisted pre-M.
9703                        grant = GRANT_UPGRADE;
9704                    } else {
9705                        // For modern apps keep runtime permissions unchanged.
9706                        grant = GRANT_RUNTIME;
9707                    }
9708                } break;
9709
9710                case PermissionInfo.PROTECTION_SIGNATURE: {
9711                    // For all apps signature permissions are install time ones.
9712                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9713                    if (allowedSig) {
9714                        grant = GRANT_INSTALL;
9715                    }
9716                } break;
9717            }
9718
9719            if (DEBUG_INSTALL) {
9720                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9721            }
9722
9723            if (grant != GRANT_DENIED) {
9724                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9725                    // If this is an existing, non-system package, then
9726                    // we can't add any new permissions to it.
9727                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9728                        // Except...  if this is a permission that was added
9729                        // to the platform (note: need to only do this when
9730                        // updating the platform).
9731                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9732                            grant = GRANT_DENIED;
9733                        }
9734                    }
9735                }
9736
9737                switch (grant) {
9738                    case GRANT_INSTALL: {
9739                        // Revoke this as runtime permission to handle the case of
9740                        // a runtime permission being downgraded to an install one.
9741                        // Also in permission review mode we keep dangerous permissions
9742                        // for legacy apps
9743                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9744                            if (origPermissions.getRuntimePermissionState(
9745                                    bp.name, userId) != null) {
9746                                // Revoke the runtime permission and clear the flags.
9747                                origPermissions.revokeRuntimePermission(bp, userId);
9748                                origPermissions.updatePermissionFlags(bp, userId,
9749                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9750                                // If we revoked a permission permission, we have to write.
9751                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9752                                        changedRuntimePermissionUserIds, userId);
9753                            }
9754                        }
9755                        // Grant an install permission.
9756                        if (permissionsState.grantInstallPermission(bp) !=
9757                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9758                            changedInstallPermission = true;
9759                        }
9760                    } break;
9761
9762                    case GRANT_RUNTIME: {
9763                        // Grant previously granted runtime permissions.
9764                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9765                            PermissionState permissionState = origPermissions
9766                                    .getRuntimePermissionState(bp.name, userId);
9767                            int flags = permissionState != null
9768                                    ? permissionState.getFlags() : 0;
9769                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9770                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9771                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9772                                    // If we cannot put the permission as it was, we have to write.
9773                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9774                                            changedRuntimePermissionUserIds, userId);
9775                                }
9776                                // If the app supports runtime permissions no need for a review.
9777                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9778                                        && appSupportsRuntimePermissions
9779                                        && (flags & PackageManager
9780                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9781                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9782                                    // Since we changed the flags, we have to write.
9783                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9784                                            changedRuntimePermissionUserIds, userId);
9785                                }
9786                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9787                                    && !appSupportsRuntimePermissions) {
9788                                // For legacy apps that need a permission review, every new
9789                                // runtime permission is granted but it is pending a review.
9790                                // We also need to review only platform defined runtime
9791                                // permissions as these are the only ones the platform knows
9792                                // how to disable the API to simulate revocation as legacy
9793                                // apps don't expect to run with revoked permissions.
9794                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9795                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9796                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9797                                        // We changed the flags, hence have to write.
9798                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9799                                                changedRuntimePermissionUserIds, userId);
9800                                    }
9801                                }
9802                                if (permissionsState.grantRuntimePermission(bp, userId)
9803                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9804                                    // We changed the permission, hence have to write.
9805                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9806                                            changedRuntimePermissionUserIds, userId);
9807                                }
9808                            }
9809                            // Propagate the permission flags.
9810                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9811                        }
9812                    } break;
9813
9814                    case GRANT_UPGRADE: {
9815                        // Grant runtime permissions for a previously held install permission.
9816                        PermissionState permissionState = origPermissions
9817                                .getInstallPermissionState(bp.name);
9818                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9819
9820                        if (origPermissions.revokeInstallPermission(bp)
9821                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9822                            // We will be transferring the permission flags, so clear them.
9823                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9824                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9825                            changedInstallPermission = true;
9826                        }
9827
9828                        // If the permission is not to be promoted to runtime we ignore it and
9829                        // also its other flags as they are not applicable to install permissions.
9830                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9831                            for (int userId : currentUserIds) {
9832                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9833                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9834                                    // Transfer the permission flags.
9835                                    permissionsState.updatePermissionFlags(bp, userId,
9836                                            flags, flags);
9837                                    // If we granted the permission, we have to write.
9838                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9839                                            changedRuntimePermissionUserIds, userId);
9840                                }
9841                            }
9842                        }
9843                    } break;
9844
9845                    default: {
9846                        if (packageOfInterest == null
9847                                || packageOfInterest.equals(pkg.packageName)) {
9848                            Slog.w(TAG, "Not granting permission " + perm
9849                                    + " to package " + pkg.packageName
9850                                    + " because it was previously installed without");
9851                        }
9852                    } break;
9853                }
9854            } else {
9855                if (permissionsState.revokeInstallPermission(bp) !=
9856                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9857                    // Also drop the permission flags.
9858                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9859                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9860                    changedInstallPermission = true;
9861                    Slog.i(TAG, "Un-granting permission " + perm
9862                            + " from package " + pkg.packageName
9863                            + " (protectionLevel=" + bp.protectionLevel
9864                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9865                            + ")");
9866                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9867                    // Don't print warning for app op permissions, since it is fine for them
9868                    // not to be granted, there is a UI for the user to decide.
9869                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9870                        Slog.w(TAG, "Not granting permission " + perm
9871                                + " to package " + pkg.packageName
9872                                + " (protectionLevel=" + bp.protectionLevel
9873                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9874                                + ")");
9875                    }
9876                }
9877            }
9878        }
9879
9880        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9881                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9882            // This is the first that we have heard about this package, so the
9883            // permissions we have now selected are fixed until explicitly
9884            // changed.
9885            ps.installPermissionsFixed = true;
9886        }
9887
9888        // Persist the runtime permissions state for users with changes. If permissions
9889        // were revoked because no app in the shared user declares them we have to
9890        // write synchronously to avoid losing runtime permissions state.
9891        for (int userId : changedRuntimePermissionUserIds) {
9892            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9893        }
9894
9895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9896    }
9897
9898    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9899        boolean allowed = false;
9900        final int NP = PackageParser.NEW_PERMISSIONS.length;
9901        for (int ip=0; ip<NP; ip++) {
9902            final PackageParser.NewPermissionInfo npi
9903                    = PackageParser.NEW_PERMISSIONS[ip];
9904            if (npi.name.equals(perm)
9905                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9906                allowed = true;
9907                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9908                        + pkg.packageName);
9909                break;
9910            }
9911        }
9912        return allowed;
9913    }
9914
9915    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9916            BasePermission bp, PermissionsState origPermissions) {
9917        boolean allowed;
9918        allowed = (compareSignatures(
9919                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9920                        == PackageManager.SIGNATURE_MATCH)
9921                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9922                        == PackageManager.SIGNATURE_MATCH);
9923        if (!allowed && (bp.protectionLevel
9924                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9925            if (isSystemApp(pkg)) {
9926                // For updated system applications, a system permission
9927                // is granted only if it had been defined by the original application.
9928                if (pkg.isUpdatedSystemApp()) {
9929                    final PackageSetting sysPs = mSettings
9930                            .getDisabledSystemPkgLPr(pkg.packageName);
9931                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9932                        // If the original was granted this permission, we take
9933                        // that grant decision as read and propagate it to the
9934                        // update.
9935                        if (sysPs.isPrivileged()) {
9936                            allowed = true;
9937                        }
9938                    } else {
9939                        // The system apk may have been updated with an older
9940                        // version of the one on the data partition, but which
9941                        // granted a new system permission that it didn't have
9942                        // before.  In this case we do want to allow the app to
9943                        // now get the new permission if the ancestral apk is
9944                        // privileged to get it.
9945                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9946                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9947                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9948                                    allowed = true;
9949                                    break;
9950                                }
9951                            }
9952                        }
9953                        // Also if a privileged parent package on the system image or any of
9954                        // its children requested a privileged permission, the updated child
9955                        // packages can also get the permission.
9956                        if (pkg.parentPackage != null) {
9957                            final PackageSetting disabledSysParentPs = mSettings
9958                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9959                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9960                                    && disabledSysParentPs.isPrivileged()) {
9961                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9962                                    allowed = true;
9963                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9964                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9965                                    for (int i = 0; i < count; i++) {
9966                                        PackageParser.Package disabledSysChildPkg =
9967                                                disabledSysParentPs.pkg.childPackages.get(i);
9968                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9969                                                perm)) {
9970                                            allowed = true;
9971                                            break;
9972                                        }
9973                                    }
9974                                }
9975                            }
9976                        }
9977                    }
9978                } else {
9979                    allowed = isPrivilegedApp(pkg);
9980                }
9981            }
9982        }
9983        if (!allowed) {
9984            if (!allowed && (bp.protectionLevel
9985                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9986                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9987                // If this was a previously normal/dangerous permission that got moved
9988                // to a system permission as part of the runtime permission redesign, then
9989                // we still want to blindly grant it to old apps.
9990                allowed = true;
9991            }
9992            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9993                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9994                // If this permission is to be granted to the system installer and
9995                // this app is an installer, then it gets the permission.
9996                allowed = true;
9997            }
9998            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9999                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10000                // If this permission is to be granted to the system verifier and
10001                // this app is a verifier, then it gets the permission.
10002                allowed = true;
10003            }
10004            if (!allowed && (bp.protectionLevel
10005                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10006                    && isSystemApp(pkg)) {
10007                // Any pre-installed system app is allowed to get this permission.
10008                allowed = true;
10009            }
10010            if (!allowed && (bp.protectionLevel
10011                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10012                // For development permissions, a development permission
10013                // is granted only if it was already granted.
10014                allowed = origPermissions.hasInstallPermission(perm);
10015            }
10016            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10017                    && pkg.packageName.equals(mSetupWizardPackage)) {
10018                // If this permission is to be granted to the system setup wizard and
10019                // this app is a setup wizard, then it gets the permission.
10020                allowed = true;
10021            }
10022        }
10023        return allowed;
10024    }
10025
10026    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10027        final int permCount = pkg.requestedPermissions.size();
10028        for (int j = 0; j < permCount; j++) {
10029            String requestedPermission = pkg.requestedPermissions.get(j);
10030            if (permission.equals(requestedPermission)) {
10031                return true;
10032            }
10033        }
10034        return false;
10035    }
10036
10037    final class ActivityIntentResolver
10038            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10039        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10040                boolean defaultOnly, int userId) {
10041            if (!sUserManager.exists(userId)) return null;
10042            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10043            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10044        }
10045
10046        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10047                int userId) {
10048            if (!sUserManager.exists(userId)) return null;
10049            mFlags = flags;
10050            return super.queryIntent(intent, resolvedType,
10051                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10052        }
10053
10054        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10055                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10056            if (!sUserManager.exists(userId)) return null;
10057            if (packageActivities == null) {
10058                return null;
10059            }
10060            mFlags = flags;
10061            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10062            final int N = packageActivities.size();
10063            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10064                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10065
10066            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10067            for (int i = 0; i < N; ++i) {
10068                intentFilters = packageActivities.get(i).intents;
10069                if (intentFilters != null && intentFilters.size() > 0) {
10070                    PackageParser.ActivityIntentInfo[] array =
10071                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10072                    intentFilters.toArray(array);
10073                    listCut.add(array);
10074                }
10075            }
10076            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10077        }
10078
10079        /**
10080         * Finds a privileged activity that matches the specified activity names.
10081         */
10082        private PackageParser.Activity findMatchingActivity(
10083                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10084            for (PackageParser.Activity sysActivity : activityList) {
10085                if (sysActivity.info.name.equals(activityInfo.name)) {
10086                    return sysActivity;
10087                }
10088                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10089                    return sysActivity;
10090                }
10091                if (sysActivity.info.targetActivity != null) {
10092                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10093                        return sysActivity;
10094                    }
10095                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10096                        return sysActivity;
10097                    }
10098                }
10099            }
10100            return null;
10101        }
10102
10103        public class IterGenerator<E> {
10104            public Iterator<E> generate(ActivityIntentInfo info) {
10105                return null;
10106            }
10107        }
10108
10109        public class ActionIterGenerator extends IterGenerator<String> {
10110            @Override
10111            public Iterator<String> generate(ActivityIntentInfo info) {
10112                return info.actionsIterator();
10113            }
10114        }
10115
10116        public class CategoriesIterGenerator extends IterGenerator<String> {
10117            @Override
10118            public Iterator<String> generate(ActivityIntentInfo info) {
10119                return info.categoriesIterator();
10120            }
10121        }
10122
10123        public class SchemesIterGenerator extends IterGenerator<String> {
10124            @Override
10125            public Iterator<String> generate(ActivityIntentInfo info) {
10126                return info.schemesIterator();
10127            }
10128        }
10129
10130        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10131            @Override
10132            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10133                return info.authoritiesIterator();
10134            }
10135        }
10136
10137        /**
10138         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10139         * MODIFIED. Do not pass in a list that should not be changed.
10140         */
10141        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10142                IterGenerator<T> generator, Iterator<T> searchIterator) {
10143            // loop through the set of actions; every one must be found in the intent filter
10144            while (searchIterator.hasNext()) {
10145                // we must have at least one filter in the list to consider a match
10146                if (intentList.size() == 0) {
10147                    break;
10148                }
10149
10150                final T searchAction = searchIterator.next();
10151
10152                // loop through the set of intent filters
10153                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10154                while (intentIter.hasNext()) {
10155                    final ActivityIntentInfo intentInfo = intentIter.next();
10156                    boolean selectionFound = false;
10157
10158                    // loop through the intent filter's selection criteria; at least one
10159                    // of them must match the searched criteria
10160                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10161                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10162                        final T intentSelection = intentSelectionIter.next();
10163                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10164                            selectionFound = true;
10165                            break;
10166                        }
10167                    }
10168
10169                    // the selection criteria wasn't found in this filter's set; this filter
10170                    // is not a potential match
10171                    if (!selectionFound) {
10172                        intentIter.remove();
10173                    }
10174                }
10175            }
10176        }
10177
10178        private boolean isProtectedAction(ActivityIntentInfo filter) {
10179            final Iterator<String> actionsIter = filter.actionsIterator();
10180            while (actionsIter != null && actionsIter.hasNext()) {
10181                final String filterAction = actionsIter.next();
10182                if (PROTECTED_ACTIONS.contains(filterAction)) {
10183                    return true;
10184                }
10185            }
10186            return false;
10187        }
10188
10189        /**
10190         * Adjusts the priority of the given intent filter according to policy.
10191         * <p>
10192         * <ul>
10193         * <li>The priority for non privileged applications is capped to '0'</li>
10194         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10195         * <li>The priority for unbundled updates to privileged applications is capped to the
10196         *      priority defined on the system partition</li>
10197         * </ul>
10198         * <p>
10199         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10200         * allowed to obtain any priority on any action.
10201         */
10202        private void adjustPriority(
10203                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10204            // nothing to do; priority is fine as-is
10205            if (intent.getPriority() <= 0) {
10206                return;
10207            }
10208
10209            final ActivityInfo activityInfo = intent.activity.info;
10210            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10211
10212            final boolean privilegedApp =
10213                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10214            if (!privilegedApp) {
10215                // non-privileged applications can never define a priority >0
10216                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10217                        + " package: " + applicationInfo.packageName
10218                        + " activity: " + intent.activity.className
10219                        + " origPrio: " + intent.getPriority());
10220                intent.setPriority(0);
10221                return;
10222            }
10223
10224            if (systemActivities == null) {
10225                // the system package is not disabled; we're parsing the system partition
10226                if (isProtectedAction(intent)) {
10227                    if (mDeferProtectedFilters) {
10228                        // We can't deal with these just yet. No component should ever obtain a
10229                        // >0 priority for a protected actions, with ONE exception -- the setup
10230                        // wizard. The setup wizard, however, cannot be known until we're able to
10231                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10232                        // until all intent filters have been processed. Chicken, meet egg.
10233                        // Let the filter temporarily have a high priority and rectify the
10234                        // priorities after all system packages have been scanned.
10235                        mProtectedFilters.add(intent);
10236                        if (DEBUG_FILTERS) {
10237                            Slog.i(TAG, "Protected action; save for later;"
10238                                    + " package: " + applicationInfo.packageName
10239                                    + " activity: " + intent.activity.className
10240                                    + " origPrio: " + intent.getPriority());
10241                        }
10242                        return;
10243                    } else {
10244                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10245                            Slog.i(TAG, "No setup wizard;"
10246                                + " All protected intents capped to priority 0");
10247                        }
10248                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10249                            if (DEBUG_FILTERS) {
10250                                Slog.i(TAG, "Found setup wizard;"
10251                                    + " allow priority " + intent.getPriority() + ";"
10252                                    + " package: " + intent.activity.info.packageName
10253                                    + " activity: " + intent.activity.className
10254                                    + " priority: " + intent.getPriority());
10255                            }
10256                            // setup wizard gets whatever it wants
10257                            return;
10258                        }
10259                        Slog.w(TAG, "Protected action; cap priority to 0;"
10260                                + " package: " + intent.activity.info.packageName
10261                                + " activity: " + intent.activity.className
10262                                + " origPrio: " + intent.getPriority());
10263                        intent.setPriority(0);
10264                        return;
10265                    }
10266                }
10267                // privileged apps on the system image get whatever priority they request
10268                return;
10269            }
10270
10271            // privileged app unbundled update ... try to find the same activity
10272            final PackageParser.Activity foundActivity =
10273                    findMatchingActivity(systemActivities, activityInfo);
10274            if (foundActivity == null) {
10275                // this is a new activity; it cannot obtain >0 priority
10276                if (DEBUG_FILTERS) {
10277                    Slog.i(TAG, "New activity; cap priority to 0;"
10278                            + " package: " + applicationInfo.packageName
10279                            + " activity: " + intent.activity.className
10280                            + " origPrio: " + intent.getPriority());
10281                }
10282                intent.setPriority(0);
10283                return;
10284            }
10285
10286            // found activity, now check for filter equivalence
10287
10288            // a shallow copy is enough; we modify the list, not its contents
10289            final List<ActivityIntentInfo> intentListCopy =
10290                    new ArrayList<>(foundActivity.intents);
10291            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10292
10293            // find matching action subsets
10294            final Iterator<String> actionsIterator = intent.actionsIterator();
10295            if (actionsIterator != null) {
10296                getIntentListSubset(
10297                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10298                if (intentListCopy.size() == 0) {
10299                    // no more intents to match; we're not equivalent
10300                    if (DEBUG_FILTERS) {
10301                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10302                                + " package: " + applicationInfo.packageName
10303                                + " activity: " + intent.activity.className
10304                                + " origPrio: " + intent.getPriority());
10305                    }
10306                    intent.setPriority(0);
10307                    return;
10308                }
10309            }
10310
10311            // find matching category subsets
10312            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10313            if (categoriesIterator != null) {
10314                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10315                        categoriesIterator);
10316                if (intentListCopy.size() == 0) {
10317                    // no more intents to match; we're not equivalent
10318                    if (DEBUG_FILTERS) {
10319                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10320                                + " package: " + applicationInfo.packageName
10321                                + " activity: " + intent.activity.className
10322                                + " origPrio: " + intent.getPriority());
10323                    }
10324                    intent.setPriority(0);
10325                    return;
10326                }
10327            }
10328
10329            // find matching schemes subsets
10330            final Iterator<String> schemesIterator = intent.schemesIterator();
10331            if (schemesIterator != null) {
10332                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10333                        schemesIterator);
10334                if (intentListCopy.size() == 0) {
10335                    // no more intents to match; we're not equivalent
10336                    if (DEBUG_FILTERS) {
10337                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10338                                + " package: " + applicationInfo.packageName
10339                                + " activity: " + intent.activity.className
10340                                + " origPrio: " + intent.getPriority());
10341                    }
10342                    intent.setPriority(0);
10343                    return;
10344                }
10345            }
10346
10347            // find matching authorities subsets
10348            final Iterator<IntentFilter.AuthorityEntry>
10349                    authoritiesIterator = intent.authoritiesIterator();
10350            if (authoritiesIterator != null) {
10351                getIntentListSubset(intentListCopy,
10352                        new AuthoritiesIterGenerator(),
10353                        authoritiesIterator);
10354                if (intentListCopy.size() == 0) {
10355                    // no more intents to match; we're not equivalent
10356                    if (DEBUG_FILTERS) {
10357                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10358                                + " package: " + applicationInfo.packageName
10359                                + " activity: " + intent.activity.className
10360                                + " origPrio: " + intent.getPriority());
10361                    }
10362                    intent.setPriority(0);
10363                    return;
10364                }
10365            }
10366
10367            // we found matching filter(s); app gets the max priority of all intents
10368            int cappedPriority = 0;
10369            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10370                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10371            }
10372            if (intent.getPriority() > cappedPriority) {
10373                if (DEBUG_FILTERS) {
10374                    Slog.i(TAG, "Found matching filter(s);"
10375                            + " cap priority to " + cappedPriority + ";"
10376                            + " package: " + applicationInfo.packageName
10377                            + " activity: " + intent.activity.className
10378                            + " origPrio: " + intent.getPriority());
10379                }
10380                intent.setPriority(cappedPriority);
10381                return;
10382            }
10383            // all this for nothing; the requested priority was <= what was on the system
10384        }
10385
10386        public final void addActivity(PackageParser.Activity a, String type) {
10387            mActivities.put(a.getComponentName(), a);
10388            if (DEBUG_SHOW_INFO)
10389                Log.v(
10390                TAG, "  " + type + " " +
10391                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10392            if (DEBUG_SHOW_INFO)
10393                Log.v(TAG, "    Class=" + a.info.name);
10394            final int NI = a.intents.size();
10395            for (int j=0; j<NI; j++) {
10396                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10397                if ("activity".equals(type)) {
10398                    final PackageSetting ps =
10399                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10400                    final List<PackageParser.Activity> systemActivities =
10401                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10402                    adjustPriority(systemActivities, intent);
10403                }
10404                if (DEBUG_SHOW_INFO) {
10405                    Log.v(TAG, "    IntentFilter:");
10406                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10407                }
10408                if (!intent.debugCheck()) {
10409                    Log.w(TAG, "==> For Activity " + a.info.name);
10410                }
10411                addFilter(intent);
10412            }
10413        }
10414
10415        public final void removeActivity(PackageParser.Activity a, String type) {
10416            mActivities.remove(a.getComponentName());
10417            if (DEBUG_SHOW_INFO) {
10418                Log.v(TAG, "  " + type + " "
10419                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10420                                : a.info.name) + ":");
10421                Log.v(TAG, "    Class=" + a.info.name);
10422            }
10423            final int NI = a.intents.size();
10424            for (int j=0; j<NI; j++) {
10425                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10426                if (DEBUG_SHOW_INFO) {
10427                    Log.v(TAG, "    IntentFilter:");
10428                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10429                }
10430                removeFilter(intent);
10431            }
10432        }
10433
10434        @Override
10435        protected boolean allowFilterResult(
10436                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10437            ActivityInfo filterAi = filter.activity.info;
10438            for (int i=dest.size()-1; i>=0; i--) {
10439                ActivityInfo destAi = dest.get(i).activityInfo;
10440                if (destAi.name == filterAi.name
10441                        && destAi.packageName == filterAi.packageName) {
10442                    return false;
10443                }
10444            }
10445            return true;
10446        }
10447
10448        @Override
10449        protected ActivityIntentInfo[] newArray(int size) {
10450            return new ActivityIntentInfo[size];
10451        }
10452
10453        @Override
10454        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10455            if (!sUserManager.exists(userId)) return true;
10456            PackageParser.Package p = filter.activity.owner;
10457            if (p != null) {
10458                PackageSetting ps = (PackageSetting)p.mExtras;
10459                if (ps != null) {
10460                    // System apps are never considered stopped for purposes of
10461                    // filtering, because there may be no way for the user to
10462                    // actually re-launch them.
10463                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10464                            && ps.getStopped(userId);
10465                }
10466            }
10467            return false;
10468        }
10469
10470        @Override
10471        protected boolean isPackageForFilter(String packageName,
10472                PackageParser.ActivityIntentInfo info) {
10473            return packageName.equals(info.activity.owner.packageName);
10474        }
10475
10476        @Override
10477        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10478                int match, int userId) {
10479            if (!sUserManager.exists(userId)) return null;
10480            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10481                return null;
10482            }
10483            final PackageParser.Activity activity = info.activity;
10484            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10485            if (ps == null) {
10486                return null;
10487            }
10488            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10489                    ps.readUserState(userId), userId);
10490            if (ai == null) {
10491                return null;
10492            }
10493            final ResolveInfo res = new ResolveInfo();
10494            res.activityInfo = ai;
10495            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10496                res.filter = info;
10497            }
10498            if (info != null) {
10499                res.handleAllWebDataURI = info.handleAllWebDataURI();
10500            }
10501            res.priority = info.getPriority();
10502            res.preferredOrder = activity.owner.mPreferredOrder;
10503            //System.out.println("Result: " + res.activityInfo.className +
10504            //                   " = " + res.priority);
10505            res.match = match;
10506            res.isDefault = info.hasDefault;
10507            res.labelRes = info.labelRes;
10508            res.nonLocalizedLabel = info.nonLocalizedLabel;
10509            if (userNeedsBadging(userId)) {
10510                res.noResourceId = true;
10511            } else {
10512                res.icon = info.icon;
10513            }
10514            res.iconResourceId = info.icon;
10515            res.system = res.activityInfo.applicationInfo.isSystemApp();
10516            return res;
10517        }
10518
10519        @Override
10520        protected void sortResults(List<ResolveInfo> results) {
10521            Collections.sort(results, mResolvePrioritySorter);
10522        }
10523
10524        @Override
10525        protected void dumpFilter(PrintWriter out, String prefix,
10526                PackageParser.ActivityIntentInfo filter) {
10527            out.print(prefix); out.print(
10528                    Integer.toHexString(System.identityHashCode(filter.activity)));
10529                    out.print(' ');
10530                    filter.activity.printComponentShortName(out);
10531                    out.print(" filter ");
10532                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10533        }
10534
10535        @Override
10536        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10537            return filter.activity;
10538        }
10539
10540        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10541            PackageParser.Activity activity = (PackageParser.Activity)label;
10542            out.print(prefix); out.print(
10543                    Integer.toHexString(System.identityHashCode(activity)));
10544                    out.print(' ');
10545                    activity.printComponentShortName(out);
10546            if (count > 1) {
10547                out.print(" ("); out.print(count); out.print(" filters)");
10548            }
10549            out.println();
10550        }
10551
10552        // Keys are String (activity class name), values are Activity.
10553        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10554                = new ArrayMap<ComponentName, PackageParser.Activity>();
10555        private int mFlags;
10556    }
10557
10558    private final class ServiceIntentResolver
10559            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10560        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10561                boolean defaultOnly, int userId) {
10562            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10563            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10564        }
10565
10566        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10567                int userId) {
10568            if (!sUserManager.exists(userId)) return null;
10569            mFlags = flags;
10570            return super.queryIntent(intent, resolvedType,
10571                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10572        }
10573
10574        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10575                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10576            if (!sUserManager.exists(userId)) return null;
10577            if (packageServices == null) {
10578                return null;
10579            }
10580            mFlags = flags;
10581            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10582            final int N = packageServices.size();
10583            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10584                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10585
10586            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10587            for (int i = 0; i < N; ++i) {
10588                intentFilters = packageServices.get(i).intents;
10589                if (intentFilters != null && intentFilters.size() > 0) {
10590                    PackageParser.ServiceIntentInfo[] array =
10591                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10592                    intentFilters.toArray(array);
10593                    listCut.add(array);
10594                }
10595            }
10596            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10597        }
10598
10599        public final void addService(PackageParser.Service s) {
10600            mServices.put(s.getComponentName(), s);
10601            if (DEBUG_SHOW_INFO) {
10602                Log.v(TAG, "  "
10603                        + (s.info.nonLocalizedLabel != null
10604                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10605                Log.v(TAG, "    Class=" + s.info.name);
10606            }
10607            final int NI = s.intents.size();
10608            int j;
10609            for (j=0; j<NI; j++) {
10610                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10611                if (DEBUG_SHOW_INFO) {
10612                    Log.v(TAG, "    IntentFilter:");
10613                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10614                }
10615                if (!intent.debugCheck()) {
10616                    Log.w(TAG, "==> For Service " + s.info.name);
10617                }
10618                addFilter(intent);
10619            }
10620        }
10621
10622        public final void removeService(PackageParser.Service s) {
10623            mServices.remove(s.getComponentName());
10624            if (DEBUG_SHOW_INFO) {
10625                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10626                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10627                Log.v(TAG, "    Class=" + s.info.name);
10628            }
10629            final int NI = s.intents.size();
10630            int j;
10631            for (j=0; j<NI; j++) {
10632                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10633                if (DEBUG_SHOW_INFO) {
10634                    Log.v(TAG, "    IntentFilter:");
10635                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10636                }
10637                removeFilter(intent);
10638            }
10639        }
10640
10641        @Override
10642        protected boolean allowFilterResult(
10643                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10644            ServiceInfo filterSi = filter.service.info;
10645            for (int i=dest.size()-1; i>=0; i--) {
10646                ServiceInfo destAi = dest.get(i).serviceInfo;
10647                if (destAi.name == filterSi.name
10648                        && destAi.packageName == filterSi.packageName) {
10649                    return false;
10650                }
10651            }
10652            return true;
10653        }
10654
10655        @Override
10656        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10657            return new PackageParser.ServiceIntentInfo[size];
10658        }
10659
10660        @Override
10661        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10662            if (!sUserManager.exists(userId)) return true;
10663            PackageParser.Package p = filter.service.owner;
10664            if (p != null) {
10665                PackageSetting ps = (PackageSetting)p.mExtras;
10666                if (ps != null) {
10667                    // System apps are never considered stopped for purposes of
10668                    // filtering, because there may be no way for the user to
10669                    // actually re-launch them.
10670                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10671                            && ps.getStopped(userId);
10672                }
10673            }
10674            return false;
10675        }
10676
10677        @Override
10678        protected boolean isPackageForFilter(String packageName,
10679                PackageParser.ServiceIntentInfo info) {
10680            return packageName.equals(info.service.owner.packageName);
10681        }
10682
10683        @Override
10684        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10685                int match, int userId) {
10686            if (!sUserManager.exists(userId)) return null;
10687            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10688            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10689                return null;
10690            }
10691            final PackageParser.Service service = info.service;
10692            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10693            if (ps == null) {
10694                return null;
10695            }
10696            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10697                    ps.readUserState(userId), userId);
10698            if (si == null) {
10699                return null;
10700            }
10701            final ResolveInfo res = new ResolveInfo();
10702            res.serviceInfo = si;
10703            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10704                res.filter = filter;
10705            }
10706            res.priority = info.getPriority();
10707            res.preferredOrder = service.owner.mPreferredOrder;
10708            res.match = match;
10709            res.isDefault = info.hasDefault;
10710            res.labelRes = info.labelRes;
10711            res.nonLocalizedLabel = info.nonLocalizedLabel;
10712            res.icon = info.icon;
10713            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10714            return res;
10715        }
10716
10717        @Override
10718        protected void sortResults(List<ResolveInfo> results) {
10719            Collections.sort(results, mResolvePrioritySorter);
10720        }
10721
10722        @Override
10723        protected void dumpFilter(PrintWriter out, String prefix,
10724                PackageParser.ServiceIntentInfo filter) {
10725            out.print(prefix); out.print(
10726                    Integer.toHexString(System.identityHashCode(filter.service)));
10727                    out.print(' ');
10728                    filter.service.printComponentShortName(out);
10729                    out.print(" filter ");
10730                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10731        }
10732
10733        @Override
10734        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10735            return filter.service;
10736        }
10737
10738        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10739            PackageParser.Service service = (PackageParser.Service)label;
10740            out.print(prefix); out.print(
10741                    Integer.toHexString(System.identityHashCode(service)));
10742                    out.print(' ');
10743                    service.printComponentShortName(out);
10744            if (count > 1) {
10745                out.print(" ("); out.print(count); out.print(" filters)");
10746            }
10747            out.println();
10748        }
10749
10750//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10751//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10752//            final List<ResolveInfo> retList = Lists.newArrayList();
10753//            while (i.hasNext()) {
10754//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10755//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10756//                    retList.add(resolveInfo);
10757//                }
10758//            }
10759//            return retList;
10760//        }
10761
10762        // Keys are String (activity class name), values are Activity.
10763        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10764                = new ArrayMap<ComponentName, PackageParser.Service>();
10765        private int mFlags;
10766    };
10767
10768    private final class ProviderIntentResolver
10769            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10770        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10771                boolean defaultOnly, int userId) {
10772            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10773            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10774        }
10775
10776        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10777                int userId) {
10778            if (!sUserManager.exists(userId))
10779                return null;
10780            mFlags = flags;
10781            return super.queryIntent(intent, resolvedType,
10782                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10783        }
10784
10785        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10786                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10787            if (!sUserManager.exists(userId))
10788                return null;
10789            if (packageProviders == null) {
10790                return null;
10791            }
10792            mFlags = flags;
10793            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10794            final int N = packageProviders.size();
10795            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10796                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10797
10798            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10799            for (int i = 0; i < N; ++i) {
10800                intentFilters = packageProviders.get(i).intents;
10801                if (intentFilters != null && intentFilters.size() > 0) {
10802                    PackageParser.ProviderIntentInfo[] array =
10803                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10804                    intentFilters.toArray(array);
10805                    listCut.add(array);
10806                }
10807            }
10808            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10809        }
10810
10811        public final void addProvider(PackageParser.Provider p) {
10812            if (mProviders.containsKey(p.getComponentName())) {
10813                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10814                return;
10815            }
10816
10817            mProviders.put(p.getComponentName(), p);
10818            if (DEBUG_SHOW_INFO) {
10819                Log.v(TAG, "  "
10820                        + (p.info.nonLocalizedLabel != null
10821                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10822                Log.v(TAG, "    Class=" + p.info.name);
10823            }
10824            final int NI = p.intents.size();
10825            int j;
10826            for (j = 0; j < NI; j++) {
10827                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10828                if (DEBUG_SHOW_INFO) {
10829                    Log.v(TAG, "    IntentFilter:");
10830                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10831                }
10832                if (!intent.debugCheck()) {
10833                    Log.w(TAG, "==> For Provider " + p.info.name);
10834                }
10835                addFilter(intent);
10836            }
10837        }
10838
10839        public final void removeProvider(PackageParser.Provider p) {
10840            mProviders.remove(p.getComponentName());
10841            if (DEBUG_SHOW_INFO) {
10842                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10843                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10844                Log.v(TAG, "    Class=" + p.info.name);
10845            }
10846            final int NI = p.intents.size();
10847            int j;
10848            for (j = 0; j < NI; j++) {
10849                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10850                if (DEBUG_SHOW_INFO) {
10851                    Log.v(TAG, "    IntentFilter:");
10852                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10853                }
10854                removeFilter(intent);
10855            }
10856        }
10857
10858        @Override
10859        protected boolean allowFilterResult(
10860                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10861            ProviderInfo filterPi = filter.provider.info;
10862            for (int i = dest.size() - 1; i >= 0; i--) {
10863                ProviderInfo destPi = dest.get(i).providerInfo;
10864                if (destPi.name == filterPi.name
10865                        && destPi.packageName == filterPi.packageName) {
10866                    return false;
10867                }
10868            }
10869            return true;
10870        }
10871
10872        @Override
10873        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10874            return new PackageParser.ProviderIntentInfo[size];
10875        }
10876
10877        @Override
10878        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10879            if (!sUserManager.exists(userId))
10880                return true;
10881            PackageParser.Package p = filter.provider.owner;
10882            if (p != null) {
10883                PackageSetting ps = (PackageSetting) p.mExtras;
10884                if (ps != null) {
10885                    // System apps are never considered stopped for purposes of
10886                    // filtering, because there may be no way for the user to
10887                    // actually re-launch them.
10888                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10889                            && ps.getStopped(userId);
10890                }
10891            }
10892            return false;
10893        }
10894
10895        @Override
10896        protected boolean isPackageForFilter(String packageName,
10897                PackageParser.ProviderIntentInfo info) {
10898            return packageName.equals(info.provider.owner.packageName);
10899        }
10900
10901        @Override
10902        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10903                int match, int userId) {
10904            if (!sUserManager.exists(userId))
10905                return null;
10906            final PackageParser.ProviderIntentInfo info = filter;
10907            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10908                return null;
10909            }
10910            final PackageParser.Provider provider = info.provider;
10911            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10912            if (ps == null) {
10913                return null;
10914            }
10915            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10916                    ps.readUserState(userId), userId);
10917            if (pi == null) {
10918                return null;
10919            }
10920            final ResolveInfo res = new ResolveInfo();
10921            res.providerInfo = pi;
10922            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10923                res.filter = filter;
10924            }
10925            res.priority = info.getPriority();
10926            res.preferredOrder = provider.owner.mPreferredOrder;
10927            res.match = match;
10928            res.isDefault = info.hasDefault;
10929            res.labelRes = info.labelRes;
10930            res.nonLocalizedLabel = info.nonLocalizedLabel;
10931            res.icon = info.icon;
10932            res.system = res.providerInfo.applicationInfo.isSystemApp();
10933            return res;
10934        }
10935
10936        @Override
10937        protected void sortResults(List<ResolveInfo> results) {
10938            Collections.sort(results, mResolvePrioritySorter);
10939        }
10940
10941        @Override
10942        protected void dumpFilter(PrintWriter out, String prefix,
10943                PackageParser.ProviderIntentInfo filter) {
10944            out.print(prefix);
10945            out.print(
10946                    Integer.toHexString(System.identityHashCode(filter.provider)));
10947            out.print(' ');
10948            filter.provider.printComponentShortName(out);
10949            out.print(" filter ");
10950            out.println(Integer.toHexString(System.identityHashCode(filter)));
10951        }
10952
10953        @Override
10954        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10955            return filter.provider;
10956        }
10957
10958        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10959            PackageParser.Provider provider = (PackageParser.Provider)label;
10960            out.print(prefix); out.print(
10961                    Integer.toHexString(System.identityHashCode(provider)));
10962                    out.print(' ');
10963                    provider.printComponentShortName(out);
10964            if (count > 1) {
10965                out.print(" ("); out.print(count); out.print(" filters)");
10966            }
10967            out.println();
10968        }
10969
10970        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10971                = new ArrayMap<ComponentName, PackageParser.Provider>();
10972        private int mFlags;
10973    }
10974
10975    private static final class EphemeralIntentResolver
10976            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10977        @Override
10978        protected EphemeralResolveIntentInfo[] newArray(int size) {
10979            return new EphemeralResolveIntentInfo[size];
10980        }
10981
10982        @Override
10983        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10984            return true;
10985        }
10986
10987        @Override
10988        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10989                int userId) {
10990            if (!sUserManager.exists(userId)) {
10991                return null;
10992            }
10993            return info.getEphemeralResolveInfo();
10994        }
10995    }
10996
10997    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10998            new Comparator<ResolveInfo>() {
10999        public int compare(ResolveInfo r1, ResolveInfo r2) {
11000            int v1 = r1.priority;
11001            int v2 = r2.priority;
11002            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11003            if (v1 != v2) {
11004                return (v1 > v2) ? -1 : 1;
11005            }
11006            v1 = r1.preferredOrder;
11007            v2 = r2.preferredOrder;
11008            if (v1 != v2) {
11009                return (v1 > v2) ? -1 : 1;
11010            }
11011            if (r1.isDefault != r2.isDefault) {
11012                return r1.isDefault ? -1 : 1;
11013            }
11014            v1 = r1.match;
11015            v2 = r2.match;
11016            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11017            if (v1 != v2) {
11018                return (v1 > v2) ? -1 : 1;
11019            }
11020            if (r1.system != r2.system) {
11021                return r1.system ? -1 : 1;
11022            }
11023            if (r1.activityInfo != null) {
11024                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11025            }
11026            if (r1.serviceInfo != null) {
11027                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11028            }
11029            if (r1.providerInfo != null) {
11030                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11031            }
11032            return 0;
11033        }
11034    };
11035
11036    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11037            new Comparator<ProviderInfo>() {
11038        public int compare(ProviderInfo p1, ProviderInfo p2) {
11039            final int v1 = p1.initOrder;
11040            final int v2 = p2.initOrder;
11041            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11042        }
11043    };
11044
11045    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11046            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11047            final int[] userIds) {
11048        mHandler.post(new Runnable() {
11049            @Override
11050            public void run() {
11051                try {
11052                    final IActivityManager am = ActivityManagerNative.getDefault();
11053                    if (am == null) return;
11054                    final int[] resolvedUserIds;
11055                    if (userIds == null) {
11056                        resolvedUserIds = am.getRunningUserIds();
11057                    } else {
11058                        resolvedUserIds = userIds;
11059                    }
11060                    for (int id : resolvedUserIds) {
11061                        final Intent intent = new Intent(action,
11062                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11063                        if (extras != null) {
11064                            intent.putExtras(extras);
11065                        }
11066                        if (targetPkg != null) {
11067                            intent.setPackage(targetPkg);
11068                        }
11069                        // Modify the UID when posting to other users
11070                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11071                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11072                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11073                            intent.putExtra(Intent.EXTRA_UID, uid);
11074                        }
11075                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11076                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11077                        if (DEBUG_BROADCASTS) {
11078                            RuntimeException here = new RuntimeException("here");
11079                            here.fillInStackTrace();
11080                            Slog.d(TAG, "Sending to user " + id + ": "
11081                                    + intent.toShortString(false, true, false, false)
11082                                    + " " + intent.getExtras(), here);
11083                        }
11084                        am.broadcastIntent(null, intent, null, finishedReceiver,
11085                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11086                                null, finishedReceiver != null, false, id);
11087                    }
11088                } catch (RemoteException ex) {
11089                }
11090            }
11091        });
11092    }
11093
11094    /**
11095     * Check if the external storage media is available. This is true if there
11096     * is a mounted external storage medium or if the external storage is
11097     * emulated.
11098     */
11099    private boolean isExternalMediaAvailable() {
11100        return mMediaMounted || Environment.isExternalStorageEmulated();
11101    }
11102
11103    @Override
11104    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11105        // writer
11106        synchronized (mPackages) {
11107            if (!isExternalMediaAvailable()) {
11108                // If the external storage is no longer mounted at this point,
11109                // the caller may not have been able to delete all of this
11110                // packages files and can not delete any more.  Bail.
11111                return null;
11112            }
11113            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11114            if (lastPackage != null) {
11115                pkgs.remove(lastPackage);
11116            }
11117            if (pkgs.size() > 0) {
11118                return pkgs.get(0);
11119            }
11120        }
11121        return null;
11122    }
11123
11124    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11125        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11126                userId, andCode ? 1 : 0, packageName);
11127        if (mSystemReady) {
11128            msg.sendToTarget();
11129        } else {
11130            if (mPostSystemReadyMessages == null) {
11131                mPostSystemReadyMessages = new ArrayList<>();
11132            }
11133            mPostSystemReadyMessages.add(msg);
11134        }
11135    }
11136
11137    void startCleaningPackages() {
11138        // reader
11139        if (!isExternalMediaAvailable()) {
11140            return;
11141        }
11142        synchronized (mPackages) {
11143            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11144                return;
11145            }
11146        }
11147        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11148        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11149        IActivityManager am = ActivityManagerNative.getDefault();
11150        if (am != null) {
11151            try {
11152                am.startService(null, intent, null, mContext.getOpPackageName(),
11153                        UserHandle.USER_SYSTEM);
11154            } catch (RemoteException e) {
11155            }
11156        }
11157    }
11158
11159    @Override
11160    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11161            int installFlags, String installerPackageName, int userId) {
11162        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11163
11164        final int callingUid = Binder.getCallingUid();
11165        enforceCrossUserPermission(callingUid, userId,
11166                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11167
11168        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11169            try {
11170                if (observer != null) {
11171                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11172                }
11173            } catch (RemoteException re) {
11174            }
11175            return;
11176        }
11177
11178        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11179            installFlags |= PackageManager.INSTALL_FROM_ADB;
11180
11181        } else {
11182            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11183            // about installerPackageName.
11184
11185            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11186            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11187        }
11188
11189        UserHandle user;
11190        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11191            user = UserHandle.ALL;
11192        } else {
11193            user = new UserHandle(userId);
11194        }
11195
11196        // Only system components can circumvent runtime permissions when installing.
11197        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11198                && mContext.checkCallingOrSelfPermission(Manifest.permission
11199                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11200            throw new SecurityException("You need the "
11201                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11202                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11203        }
11204
11205        final File originFile = new File(originPath);
11206        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11207
11208        final Message msg = mHandler.obtainMessage(INIT_COPY);
11209        final VerificationInfo verificationInfo = new VerificationInfo(
11210                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11211        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11212                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11213                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11214                null /*certificates*/);
11215        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11216        msg.obj = params;
11217
11218        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11219                System.identityHashCode(msg.obj));
11220        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11221                System.identityHashCode(msg.obj));
11222
11223        mHandler.sendMessage(msg);
11224    }
11225
11226    void installStage(String packageName, File stagedDir, String stagedCid,
11227            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11228            String installerPackageName, int installerUid, UserHandle user,
11229            Certificate[][] certificates) {
11230        if (DEBUG_EPHEMERAL) {
11231            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11232                Slog.d(TAG, "Ephemeral install of " + packageName);
11233            }
11234        }
11235        final VerificationInfo verificationInfo = new VerificationInfo(
11236                sessionParams.originatingUri, sessionParams.referrerUri,
11237                sessionParams.originatingUid, installerUid);
11238
11239        final OriginInfo origin;
11240        if (stagedDir != null) {
11241            origin = OriginInfo.fromStagedFile(stagedDir);
11242        } else {
11243            origin = OriginInfo.fromStagedContainer(stagedCid);
11244        }
11245
11246        final Message msg = mHandler.obtainMessage(INIT_COPY);
11247        final InstallParams params = new InstallParams(origin, null, observer,
11248                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11249                verificationInfo, user, sessionParams.abiOverride,
11250                sessionParams.grantedRuntimePermissions, certificates);
11251        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11252        msg.obj = params;
11253
11254        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11255                System.identityHashCode(msg.obj));
11256        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11257                System.identityHashCode(msg.obj));
11258
11259        mHandler.sendMessage(msg);
11260    }
11261
11262    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11263            int userId) {
11264        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11265        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11266    }
11267
11268    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11269            int appId, int userId) {
11270        Bundle extras = new Bundle(1);
11271        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11272
11273        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11274                packageName, extras, 0, null, null, new int[] {userId});
11275        try {
11276            IActivityManager am = ActivityManagerNative.getDefault();
11277            if (isSystem && am.isUserRunning(userId, 0)) {
11278                // The just-installed/enabled app is bundled on the system, so presumed
11279                // to be able to run automatically without needing an explicit launch.
11280                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11281                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11282                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11283                        .setPackage(packageName);
11284                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11285                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11286            }
11287        } catch (RemoteException e) {
11288            // shouldn't happen
11289            Slog.w(TAG, "Unable to bootstrap installed package", e);
11290        }
11291    }
11292
11293    @Override
11294    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11295            int userId) {
11296        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11297        PackageSetting pkgSetting;
11298        final int uid = Binder.getCallingUid();
11299        enforceCrossUserPermission(uid, userId,
11300                true /* requireFullPermission */, true /* checkShell */,
11301                "setApplicationHiddenSetting for user " + userId);
11302
11303        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11304            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11305            return false;
11306        }
11307
11308        long callingId = Binder.clearCallingIdentity();
11309        try {
11310            boolean sendAdded = false;
11311            boolean sendRemoved = false;
11312            // writer
11313            synchronized (mPackages) {
11314                pkgSetting = mSettings.mPackages.get(packageName);
11315                if (pkgSetting == null) {
11316                    return false;
11317                }
11318                if (pkgSetting.getHidden(userId) != hidden) {
11319                    pkgSetting.setHidden(hidden, userId);
11320                    mSettings.writePackageRestrictionsLPr(userId);
11321                    if (hidden) {
11322                        sendRemoved = true;
11323                    } else {
11324                        sendAdded = true;
11325                    }
11326                }
11327            }
11328            if (sendAdded) {
11329                sendPackageAddedForUser(packageName, pkgSetting, userId);
11330                return true;
11331            }
11332            if (sendRemoved) {
11333                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11334                        "hiding pkg");
11335                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11336                return true;
11337            }
11338        } finally {
11339            Binder.restoreCallingIdentity(callingId);
11340        }
11341        return false;
11342    }
11343
11344    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11345            int userId) {
11346        final PackageRemovedInfo info = new PackageRemovedInfo();
11347        info.removedPackage = packageName;
11348        info.removedUsers = new int[] {userId};
11349        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11350        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11351    }
11352
11353    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11354        if (pkgList.length > 0) {
11355            Bundle extras = new Bundle(1);
11356            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11357
11358            sendPackageBroadcast(
11359                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11360                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11361                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11362                    new int[] {userId});
11363        }
11364    }
11365
11366    /**
11367     * Returns true if application is not found or there was an error. Otherwise it returns
11368     * the hidden state of the package for the given user.
11369     */
11370    @Override
11371    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11372        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11373        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11374                true /* requireFullPermission */, false /* checkShell */,
11375                "getApplicationHidden for user " + userId);
11376        PackageSetting pkgSetting;
11377        long callingId = Binder.clearCallingIdentity();
11378        try {
11379            // writer
11380            synchronized (mPackages) {
11381                pkgSetting = mSettings.mPackages.get(packageName);
11382                if (pkgSetting == null) {
11383                    return true;
11384                }
11385                return pkgSetting.getHidden(userId);
11386            }
11387        } finally {
11388            Binder.restoreCallingIdentity(callingId);
11389        }
11390    }
11391
11392    /**
11393     * @hide
11394     */
11395    @Override
11396    public int installExistingPackageAsUser(String packageName, int userId) {
11397        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11398                null);
11399        PackageSetting pkgSetting;
11400        final int uid = Binder.getCallingUid();
11401        enforceCrossUserPermission(uid, userId,
11402                true /* requireFullPermission */, true /* checkShell */,
11403                "installExistingPackage for user " + userId);
11404        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11405            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11406        }
11407
11408        long callingId = Binder.clearCallingIdentity();
11409        try {
11410            boolean installed = false;
11411
11412            // writer
11413            synchronized (mPackages) {
11414                pkgSetting = mSettings.mPackages.get(packageName);
11415                if (pkgSetting == null) {
11416                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11417                }
11418                if (!pkgSetting.getInstalled(userId)) {
11419                    pkgSetting.setInstalled(true, userId);
11420                    pkgSetting.setHidden(false, userId);
11421                    mSettings.writePackageRestrictionsLPr(userId);
11422                    installed = true;
11423                }
11424            }
11425
11426            if (installed) {
11427                if (pkgSetting.pkg != null) {
11428                    synchronized (mInstallLock) {
11429                        // We don't need to freeze for a brand new install
11430                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11431                    }
11432                }
11433                sendPackageAddedForUser(packageName, pkgSetting, userId);
11434            }
11435        } finally {
11436            Binder.restoreCallingIdentity(callingId);
11437        }
11438
11439        return PackageManager.INSTALL_SUCCEEDED;
11440    }
11441
11442    boolean isUserRestricted(int userId, String restrictionKey) {
11443        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11444        if (restrictions.getBoolean(restrictionKey, false)) {
11445            Log.w(TAG, "User is restricted: " + restrictionKey);
11446            return true;
11447        }
11448        return false;
11449    }
11450
11451    @Override
11452    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11453            int userId) {
11454        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11455        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11456                true /* requireFullPermission */, true /* checkShell */,
11457                "setPackagesSuspended for user " + userId);
11458
11459        if (ArrayUtils.isEmpty(packageNames)) {
11460            return packageNames;
11461        }
11462
11463        // List of package names for whom the suspended state has changed.
11464        List<String> changedPackages = new ArrayList<>(packageNames.length);
11465        // List of package names for whom the suspended state is not set as requested in this
11466        // method.
11467        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11468        for (int i = 0; i < packageNames.length; i++) {
11469            String packageName = packageNames[i];
11470            long callingId = Binder.clearCallingIdentity();
11471            try {
11472                boolean changed = false;
11473                final int appId;
11474                synchronized (mPackages) {
11475                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11476                    if (pkgSetting == null) {
11477                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11478                                + "\". Skipping suspending/un-suspending.");
11479                        unactionedPackages.add(packageName);
11480                        continue;
11481                    }
11482                    appId = pkgSetting.appId;
11483                    if (pkgSetting.getSuspended(userId) != suspended) {
11484                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11485                            unactionedPackages.add(packageName);
11486                            continue;
11487                        }
11488                        pkgSetting.setSuspended(suspended, userId);
11489                        mSettings.writePackageRestrictionsLPr(userId);
11490                        changed = true;
11491                        changedPackages.add(packageName);
11492                    }
11493                }
11494
11495                if (changed && suspended) {
11496                    killApplication(packageName, UserHandle.getUid(userId, appId),
11497                            "suspending package");
11498                }
11499            } finally {
11500                Binder.restoreCallingIdentity(callingId);
11501            }
11502        }
11503
11504        if (!changedPackages.isEmpty()) {
11505            sendPackagesSuspendedForUser(changedPackages.toArray(
11506                    new String[changedPackages.size()]), userId, suspended);
11507        }
11508
11509        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11510    }
11511
11512    @Override
11513    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11514        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11515                true /* requireFullPermission */, false /* checkShell */,
11516                "isPackageSuspendedForUser for user " + userId);
11517        synchronized (mPackages) {
11518            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11519            if (pkgSetting == null) {
11520                throw new IllegalArgumentException("Unknown target package: " + packageName);
11521            }
11522            return pkgSetting.getSuspended(userId);
11523        }
11524    }
11525
11526    /**
11527     * TODO: cache and disallow blocking the active dialer.
11528     *
11529     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11530     */
11531    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11532        if (isPackageDeviceAdmin(packageName, userId)) {
11533            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11534                    + "\": has an active device admin");
11535            return false;
11536        }
11537
11538        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11539        if (packageName.equals(activeLauncherPackageName)) {
11540            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11541                    + "\": contains the active launcher");
11542            return false;
11543        }
11544
11545        if (packageName.equals(mRequiredInstallerPackage)) {
11546            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11547                    + "\": required for package installation");
11548            return false;
11549        }
11550
11551        if (packageName.equals(mRequiredVerifierPackage)) {
11552            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11553                    + "\": required for package verification");
11554            return false;
11555        }
11556
11557        final PackageParser.Package pkg = mPackages.get(packageName);
11558        if (pkg != null && isPrivilegedApp(pkg)) {
11559            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11560                    + "\": is a privileged app");
11561            return false;
11562        }
11563
11564        return true;
11565    }
11566
11567    private String getActiveLauncherPackageName(int userId) {
11568        Intent intent = new Intent(Intent.ACTION_MAIN);
11569        intent.addCategory(Intent.CATEGORY_HOME);
11570        ResolveInfo resolveInfo = resolveIntent(
11571                intent,
11572                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11573                PackageManager.MATCH_DEFAULT_ONLY,
11574                userId);
11575
11576        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11577    }
11578
11579    @Override
11580    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11581        mContext.enforceCallingOrSelfPermission(
11582                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11583                "Only package verification agents can verify applications");
11584
11585        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11586        final PackageVerificationResponse response = new PackageVerificationResponse(
11587                verificationCode, Binder.getCallingUid());
11588        msg.arg1 = id;
11589        msg.obj = response;
11590        mHandler.sendMessage(msg);
11591    }
11592
11593    @Override
11594    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11595            long millisecondsToDelay) {
11596        mContext.enforceCallingOrSelfPermission(
11597                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11598                "Only package verification agents can extend verification timeouts");
11599
11600        final PackageVerificationState state = mPendingVerification.get(id);
11601        final PackageVerificationResponse response = new PackageVerificationResponse(
11602                verificationCodeAtTimeout, Binder.getCallingUid());
11603
11604        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11605            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11606        }
11607        if (millisecondsToDelay < 0) {
11608            millisecondsToDelay = 0;
11609        }
11610        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11611                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11612            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11613        }
11614
11615        if ((state != null) && !state.timeoutExtended()) {
11616            state.extendTimeout();
11617
11618            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11619            msg.arg1 = id;
11620            msg.obj = response;
11621            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11622        }
11623    }
11624
11625    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11626            int verificationCode, UserHandle user) {
11627        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11628        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11629        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11630        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11631        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11632
11633        mContext.sendBroadcastAsUser(intent, user,
11634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11635    }
11636
11637    private ComponentName matchComponentForVerifier(String packageName,
11638            List<ResolveInfo> receivers) {
11639        ActivityInfo targetReceiver = null;
11640
11641        final int NR = receivers.size();
11642        for (int i = 0; i < NR; i++) {
11643            final ResolveInfo info = receivers.get(i);
11644            if (info.activityInfo == null) {
11645                continue;
11646            }
11647
11648            if (packageName.equals(info.activityInfo.packageName)) {
11649                targetReceiver = info.activityInfo;
11650                break;
11651            }
11652        }
11653
11654        if (targetReceiver == null) {
11655            return null;
11656        }
11657
11658        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11659    }
11660
11661    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11662            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11663        if (pkgInfo.verifiers.length == 0) {
11664            return null;
11665        }
11666
11667        final int N = pkgInfo.verifiers.length;
11668        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11669        for (int i = 0; i < N; i++) {
11670            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11671
11672            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11673                    receivers);
11674            if (comp == null) {
11675                continue;
11676            }
11677
11678            final int verifierUid = getUidForVerifier(verifierInfo);
11679            if (verifierUid == -1) {
11680                continue;
11681            }
11682
11683            if (DEBUG_VERIFY) {
11684                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11685                        + " with the correct signature");
11686            }
11687            sufficientVerifiers.add(comp);
11688            verificationState.addSufficientVerifier(verifierUid);
11689        }
11690
11691        return sufficientVerifiers;
11692    }
11693
11694    private int getUidForVerifier(VerifierInfo verifierInfo) {
11695        synchronized (mPackages) {
11696            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11697            if (pkg == null) {
11698                return -1;
11699            } else if (pkg.mSignatures.length != 1) {
11700                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11701                        + " has more than one signature; ignoring");
11702                return -1;
11703            }
11704
11705            /*
11706             * If the public key of the package's signature does not match
11707             * our expected public key, then this is a different package and
11708             * we should skip.
11709             */
11710
11711            final byte[] expectedPublicKey;
11712            try {
11713                final Signature verifierSig = pkg.mSignatures[0];
11714                final PublicKey publicKey = verifierSig.getPublicKey();
11715                expectedPublicKey = publicKey.getEncoded();
11716            } catch (CertificateException e) {
11717                return -1;
11718            }
11719
11720            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11721
11722            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11723                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11724                        + " does not have the expected public key; ignoring");
11725                return -1;
11726            }
11727
11728            return pkg.applicationInfo.uid;
11729        }
11730    }
11731
11732    @Override
11733    public void finishPackageInstall(int token, boolean didLaunch) {
11734        enforceSystemOrRoot("Only the system is allowed to finish installs");
11735
11736        if (DEBUG_INSTALL) {
11737            Slog.v(TAG, "BM finishing package install for " + token);
11738        }
11739        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11740
11741        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11742        mHandler.sendMessage(msg);
11743    }
11744
11745    /**
11746     * Get the verification agent timeout.
11747     *
11748     * @return verification timeout in milliseconds
11749     */
11750    private long getVerificationTimeout() {
11751        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11752                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11753                DEFAULT_VERIFICATION_TIMEOUT);
11754    }
11755
11756    /**
11757     * Get the default verification agent response code.
11758     *
11759     * @return default verification response code
11760     */
11761    private int getDefaultVerificationResponse() {
11762        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11763                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11764                DEFAULT_VERIFICATION_RESPONSE);
11765    }
11766
11767    /**
11768     * Check whether or not package verification has been enabled.
11769     *
11770     * @return true if verification should be performed
11771     */
11772    private boolean isVerificationEnabled(int userId, int installFlags) {
11773        if (!DEFAULT_VERIFY_ENABLE) {
11774            return false;
11775        }
11776        // Ephemeral apps don't get the full verification treatment
11777        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11778            if (DEBUG_EPHEMERAL) {
11779                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11780            }
11781            return false;
11782        }
11783
11784        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11785
11786        // Check if installing from ADB
11787        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11788            // Do not run verification in a test harness environment
11789            if (ActivityManager.isRunningInTestHarness()) {
11790                return false;
11791            }
11792            if (ensureVerifyAppsEnabled) {
11793                return true;
11794            }
11795            // Check if the developer does not want package verification for ADB installs
11796            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11797                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11798                return false;
11799            }
11800        }
11801
11802        if (ensureVerifyAppsEnabled) {
11803            return true;
11804        }
11805
11806        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11807                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11808    }
11809
11810    @Override
11811    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11812            throws RemoteException {
11813        mContext.enforceCallingOrSelfPermission(
11814                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11815                "Only intentfilter verification agents can verify applications");
11816
11817        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11818        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11819                Binder.getCallingUid(), verificationCode, failedDomains);
11820        msg.arg1 = id;
11821        msg.obj = response;
11822        mHandler.sendMessage(msg);
11823    }
11824
11825    @Override
11826    public int getIntentVerificationStatus(String packageName, int userId) {
11827        synchronized (mPackages) {
11828            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11829        }
11830    }
11831
11832    @Override
11833    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11834        mContext.enforceCallingOrSelfPermission(
11835                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11836
11837        boolean result = false;
11838        synchronized (mPackages) {
11839            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11840        }
11841        if (result) {
11842            scheduleWritePackageRestrictionsLocked(userId);
11843        }
11844        return result;
11845    }
11846
11847    @Override
11848    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11849            String packageName) {
11850        synchronized (mPackages) {
11851            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11852        }
11853    }
11854
11855    @Override
11856    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11857        if (TextUtils.isEmpty(packageName)) {
11858            return ParceledListSlice.emptyList();
11859        }
11860        synchronized (mPackages) {
11861            PackageParser.Package pkg = mPackages.get(packageName);
11862            if (pkg == null || pkg.activities == null) {
11863                return ParceledListSlice.emptyList();
11864            }
11865            final int count = pkg.activities.size();
11866            ArrayList<IntentFilter> result = new ArrayList<>();
11867            for (int n=0; n<count; n++) {
11868                PackageParser.Activity activity = pkg.activities.get(n);
11869                if (activity.intents != null && activity.intents.size() > 0) {
11870                    result.addAll(activity.intents);
11871                }
11872            }
11873            return new ParceledListSlice<>(result);
11874        }
11875    }
11876
11877    @Override
11878    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11879        mContext.enforceCallingOrSelfPermission(
11880                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11881
11882        synchronized (mPackages) {
11883            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11884            if (packageName != null) {
11885                result |= updateIntentVerificationStatus(packageName,
11886                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11887                        userId);
11888                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11889                        packageName, userId);
11890            }
11891            return result;
11892        }
11893    }
11894
11895    @Override
11896    public String getDefaultBrowserPackageName(int userId) {
11897        synchronized (mPackages) {
11898            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11899        }
11900    }
11901
11902    /**
11903     * Get the "allow unknown sources" setting.
11904     *
11905     * @return the current "allow unknown sources" setting
11906     */
11907    private int getUnknownSourcesSettings() {
11908        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11909                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11910                -1);
11911    }
11912
11913    @Override
11914    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11915        final int uid = Binder.getCallingUid();
11916        // writer
11917        synchronized (mPackages) {
11918            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11919            if (targetPackageSetting == null) {
11920                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11921            }
11922
11923            PackageSetting installerPackageSetting;
11924            if (installerPackageName != null) {
11925                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11926                if (installerPackageSetting == null) {
11927                    throw new IllegalArgumentException("Unknown installer package: "
11928                            + installerPackageName);
11929                }
11930            } else {
11931                installerPackageSetting = null;
11932            }
11933
11934            Signature[] callerSignature;
11935            Object obj = mSettings.getUserIdLPr(uid);
11936            if (obj != null) {
11937                if (obj instanceof SharedUserSetting) {
11938                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11939                } else if (obj instanceof PackageSetting) {
11940                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11941                } else {
11942                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11943                }
11944            } else {
11945                throw new SecurityException("Unknown calling UID: " + uid);
11946            }
11947
11948            // Verify: can't set installerPackageName to a package that is
11949            // not signed with the same cert as the caller.
11950            if (installerPackageSetting != null) {
11951                if (compareSignatures(callerSignature,
11952                        installerPackageSetting.signatures.mSignatures)
11953                        != PackageManager.SIGNATURE_MATCH) {
11954                    throw new SecurityException(
11955                            "Caller does not have same cert as new installer package "
11956                            + installerPackageName);
11957                }
11958            }
11959
11960            // Verify: if target already has an installer package, it must
11961            // be signed with the same cert as the caller.
11962            if (targetPackageSetting.installerPackageName != null) {
11963                PackageSetting setting = mSettings.mPackages.get(
11964                        targetPackageSetting.installerPackageName);
11965                // If the currently set package isn't valid, then it's always
11966                // okay to change it.
11967                if (setting != null) {
11968                    if (compareSignatures(callerSignature,
11969                            setting.signatures.mSignatures)
11970                            != PackageManager.SIGNATURE_MATCH) {
11971                        throw new SecurityException(
11972                                "Caller does not have same cert as old installer package "
11973                                + targetPackageSetting.installerPackageName);
11974                    }
11975                }
11976            }
11977
11978            // Okay!
11979            targetPackageSetting.installerPackageName = installerPackageName;
11980            if (installerPackageName != null) {
11981                mSettings.mInstallerPackages.add(installerPackageName);
11982            }
11983            scheduleWriteSettingsLocked();
11984        }
11985    }
11986
11987    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11988        // Queue up an async operation since the package installation may take a little while.
11989        mHandler.post(new Runnable() {
11990            public void run() {
11991                mHandler.removeCallbacks(this);
11992                 // Result object to be returned
11993                PackageInstalledInfo res = new PackageInstalledInfo();
11994                res.setReturnCode(currentStatus);
11995                res.uid = -1;
11996                res.pkg = null;
11997                res.removedInfo = null;
11998                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11999                    args.doPreInstall(res.returnCode);
12000                    synchronized (mInstallLock) {
12001                        installPackageTracedLI(args, res);
12002                    }
12003                    args.doPostInstall(res.returnCode, res.uid);
12004                }
12005
12006                // A restore should be performed at this point if (a) the install
12007                // succeeded, (b) the operation is not an update, and (c) the new
12008                // package has not opted out of backup participation.
12009                final boolean update = res.removedInfo != null
12010                        && res.removedInfo.removedPackage != null;
12011                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12012                boolean doRestore = !update
12013                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12014
12015                // Set up the post-install work request bookkeeping.  This will be used
12016                // and cleaned up by the post-install event handling regardless of whether
12017                // there's a restore pass performed.  Token values are >= 1.
12018                int token;
12019                if (mNextInstallToken < 0) mNextInstallToken = 1;
12020                token = mNextInstallToken++;
12021
12022                PostInstallData data = new PostInstallData(args, res);
12023                mRunningInstalls.put(token, data);
12024                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12025
12026                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12027                    // Pass responsibility to the Backup Manager.  It will perform a
12028                    // restore if appropriate, then pass responsibility back to the
12029                    // Package Manager to run the post-install observer callbacks
12030                    // and broadcasts.
12031                    IBackupManager bm = IBackupManager.Stub.asInterface(
12032                            ServiceManager.getService(Context.BACKUP_SERVICE));
12033                    if (bm != null) {
12034                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12035                                + " to BM for possible restore");
12036                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12037                        try {
12038                            // TODO: http://b/22388012
12039                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12040                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12041                            } else {
12042                                doRestore = false;
12043                            }
12044                        } catch (RemoteException e) {
12045                            // can't happen; the backup manager is local
12046                        } catch (Exception e) {
12047                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12048                            doRestore = false;
12049                        }
12050                    } else {
12051                        Slog.e(TAG, "Backup Manager not found!");
12052                        doRestore = false;
12053                    }
12054                }
12055
12056                if (!doRestore) {
12057                    // No restore possible, or the Backup Manager was mysteriously not
12058                    // available -- just fire the post-install work request directly.
12059                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12060
12061                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12062
12063                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12064                    mHandler.sendMessage(msg);
12065                }
12066            }
12067        });
12068    }
12069
12070    /**
12071     * Callback from PackageSettings whenever an app is first transitioned out of the
12072     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12073     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12074     * here whether the app is the target of an ongoing install, and only send the
12075     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12076     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12077     * handling.
12078     */
12079    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12080        // Serialize this with the rest of the install-process message chain.  In the
12081        // restore-at-install case, this Runnable will necessarily run before the
12082        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12083        // are coherent.  In the non-restore case, the app has already completed install
12084        // and been launched through some other means, so it is not in a problematic
12085        // state for observers to see the FIRST_LAUNCH signal.
12086        mHandler.post(new Runnable() {
12087            @Override
12088            public void run() {
12089                for (int i = 0; i < mRunningInstalls.size(); i++) {
12090                    final PostInstallData data = mRunningInstalls.valueAt(i);
12091                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12092                        // right package; but is it for the right user?
12093                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12094                            if (userId == data.res.newUsers[uIndex]) {
12095                                if (DEBUG_BACKUP) {
12096                                    Slog.i(TAG, "Package " + pkgName
12097                                            + " being restored so deferring FIRST_LAUNCH");
12098                                }
12099                                return;
12100                            }
12101                        }
12102                    }
12103                }
12104                // didn't find it, so not being restored
12105                if (DEBUG_BACKUP) {
12106                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12107                }
12108                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12109            }
12110        });
12111    }
12112
12113    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12114        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12115                installerPkg, null, userIds);
12116    }
12117
12118    private abstract class HandlerParams {
12119        private static final int MAX_RETRIES = 4;
12120
12121        /**
12122         * Number of times startCopy() has been attempted and had a non-fatal
12123         * error.
12124         */
12125        private int mRetries = 0;
12126
12127        /** User handle for the user requesting the information or installation. */
12128        private final UserHandle mUser;
12129        String traceMethod;
12130        int traceCookie;
12131
12132        HandlerParams(UserHandle user) {
12133            mUser = user;
12134        }
12135
12136        UserHandle getUser() {
12137            return mUser;
12138        }
12139
12140        HandlerParams setTraceMethod(String traceMethod) {
12141            this.traceMethod = traceMethod;
12142            return this;
12143        }
12144
12145        HandlerParams setTraceCookie(int traceCookie) {
12146            this.traceCookie = traceCookie;
12147            return this;
12148        }
12149
12150        final boolean startCopy() {
12151            boolean res;
12152            try {
12153                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12154
12155                if (++mRetries > MAX_RETRIES) {
12156                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12157                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12158                    handleServiceError();
12159                    return false;
12160                } else {
12161                    handleStartCopy();
12162                    res = true;
12163                }
12164            } catch (RemoteException e) {
12165                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12166                mHandler.sendEmptyMessage(MCS_RECONNECT);
12167                res = false;
12168            }
12169            handleReturnCode();
12170            return res;
12171        }
12172
12173        final void serviceError() {
12174            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12175            handleServiceError();
12176            handleReturnCode();
12177        }
12178
12179        abstract void handleStartCopy() throws RemoteException;
12180        abstract void handleServiceError();
12181        abstract void handleReturnCode();
12182    }
12183
12184    class MeasureParams extends HandlerParams {
12185        private final PackageStats mStats;
12186        private boolean mSuccess;
12187
12188        private final IPackageStatsObserver mObserver;
12189
12190        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12191            super(new UserHandle(stats.userHandle));
12192            mObserver = observer;
12193            mStats = stats;
12194        }
12195
12196        @Override
12197        public String toString() {
12198            return "MeasureParams{"
12199                + Integer.toHexString(System.identityHashCode(this))
12200                + " " + mStats.packageName + "}";
12201        }
12202
12203        @Override
12204        void handleStartCopy() throws RemoteException {
12205            synchronized (mInstallLock) {
12206                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12207            }
12208
12209            if (mSuccess) {
12210                final boolean mounted;
12211                if (Environment.isExternalStorageEmulated()) {
12212                    mounted = true;
12213                } else {
12214                    final String status = Environment.getExternalStorageState();
12215                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12216                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12217                }
12218
12219                if (mounted) {
12220                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12221
12222                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12223                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12224
12225                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12226                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12227
12228                    // Always subtract cache size, since it's a subdirectory
12229                    mStats.externalDataSize -= mStats.externalCacheSize;
12230
12231                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12232                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12233
12234                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12235                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12236                }
12237            }
12238        }
12239
12240        @Override
12241        void handleReturnCode() {
12242            if (mObserver != null) {
12243                try {
12244                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12245                } catch (RemoteException e) {
12246                    Slog.i(TAG, "Observer no longer exists.");
12247                }
12248            }
12249        }
12250
12251        @Override
12252        void handleServiceError() {
12253            Slog.e(TAG, "Could not measure application " + mStats.packageName
12254                            + " external storage");
12255        }
12256    }
12257
12258    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12259            throws RemoteException {
12260        long result = 0;
12261        for (File path : paths) {
12262            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12263        }
12264        return result;
12265    }
12266
12267    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12268        for (File path : paths) {
12269            try {
12270                mcs.clearDirectory(path.getAbsolutePath());
12271            } catch (RemoteException e) {
12272            }
12273        }
12274    }
12275
12276    static class OriginInfo {
12277        /**
12278         * Location where install is coming from, before it has been
12279         * copied/renamed into place. This could be a single monolithic APK
12280         * file, or a cluster directory. This location may be untrusted.
12281         */
12282        final File file;
12283        final String cid;
12284
12285        /**
12286         * Flag indicating that {@link #file} or {@link #cid} has already been
12287         * staged, meaning downstream users don't need to defensively copy the
12288         * contents.
12289         */
12290        final boolean staged;
12291
12292        /**
12293         * Flag indicating that {@link #file} or {@link #cid} is an already
12294         * installed app that is being moved.
12295         */
12296        final boolean existing;
12297
12298        final String resolvedPath;
12299        final File resolvedFile;
12300
12301        static OriginInfo fromNothing() {
12302            return new OriginInfo(null, null, false, false);
12303        }
12304
12305        static OriginInfo fromUntrustedFile(File file) {
12306            return new OriginInfo(file, null, false, false);
12307        }
12308
12309        static OriginInfo fromExistingFile(File file) {
12310            return new OriginInfo(file, null, false, true);
12311        }
12312
12313        static OriginInfo fromStagedFile(File file) {
12314            return new OriginInfo(file, null, true, false);
12315        }
12316
12317        static OriginInfo fromStagedContainer(String cid) {
12318            return new OriginInfo(null, cid, true, false);
12319        }
12320
12321        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12322            this.file = file;
12323            this.cid = cid;
12324            this.staged = staged;
12325            this.existing = existing;
12326
12327            if (cid != null) {
12328                resolvedPath = PackageHelper.getSdDir(cid);
12329                resolvedFile = new File(resolvedPath);
12330            } else if (file != null) {
12331                resolvedPath = file.getAbsolutePath();
12332                resolvedFile = file;
12333            } else {
12334                resolvedPath = null;
12335                resolvedFile = null;
12336            }
12337        }
12338    }
12339
12340    static class MoveInfo {
12341        final int moveId;
12342        final String fromUuid;
12343        final String toUuid;
12344        final String packageName;
12345        final String dataAppName;
12346        final int appId;
12347        final String seinfo;
12348        final int targetSdkVersion;
12349
12350        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12351                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12352            this.moveId = moveId;
12353            this.fromUuid = fromUuid;
12354            this.toUuid = toUuid;
12355            this.packageName = packageName;
12356            this.dataAppName = dataAppName;
12357            this.appId = appId;
12358            this.seinfo = seinfo;
12359            this.targetSdkVersion = targetSdkVersion;
12360        }
12361    }
12362
12363    static class VerificationInfo {
12364        /** A constant used to indicate that a uid value is not present. */
12365        public static final int NO_UID = -1;
12366
12367        /** URI referencing where the package was downloaded from. */
12368        final Uri originatingUri;
12369
12370        /** HTTP referrer URI associated with the originatingURI. */
12371        final Uri referrer;
12372
12373        /** UID of the application that the install request originated from. */
12374        final int originatingUid;
12375
12376        /** UID of application requesting the install */
12377        final int installerUid;
12378
12379        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12380            this.originatingUri = originatingUri;
12381            this.referrer = referrer;
12382            this.originatingUid = originatingUid;
12383            this.installerUid = installerUid;
12384        }
12385    }
12386
12387    class InstallParams extends HandlerParams {
12388        final OriginInfo origin;
12389        final MoveInfo move;
12390        final IPackageInstallObserver2 observer;
12391        int installFlags;
12392        final String installerPackageName;
12393        final String volumeUuid;
12394        private InstallArgs mArgs;
12395        private int mRet;
12396        final String packageAbiOverride;
12397        final String[] grantedRuntimePermissions;
12398        final VerificationInfo verificationInfo;
12399        final Certificate[][] certificates;
12400
12401        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12402                int installFlags, String installerPackageName, String volumeUuid,
12403                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12404                String[] grantedPermissions, Certificate[][] certificates) {
12405            super(user);
12406            this.origin = origin;
12407            this.move = move;
12408            this.observer = observer;
12409            this.installFlags = installFlags;
12410            this.installerPackageName = installerPackageName;
12411            this.volumeUuid = volumeUuid;
12412            this.verificationInfo = verificationInfo;
12413            this.packageAbiOverride = packageAbiOverride;
12414            this.grantedRuntimePermissions = grantedPermissions;
12415            this.certificates = certificates;
12416        }
12417
12418        @Override
12419        public String toString() {
12420            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12421                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12422        }
12423
12424        private int installLocationPolicy(PackageInfoLite pkgLite) {
12425            String packageName = pkgLite.packageName;
12426            int installLocation = pkgLite.installLocation;
12427            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12428            // reader
12429            synchronized (mPackages) {
12430                // Currently installed package which the new package is attempting to replace or
12431                // null if no such package is installed.
12432                PackageParser.Package installedPkg = mPackages.get(packageName);
12433                // Package which currently owns the data which the new package will own if installed.
12434                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12435                // will be null whereas dataOwnerPkg will contain information about the package
12436                // which was uninstalled while keeping its data.
12437                PackageParser.Package dataOwnerPkg = installedPkg;
12438                if (dataOwnerPkg  == null) {
12439                    PackageSetting ps = mSettings.mPackages.get(packageName);
12440                    if (ps != null) {
12441                        dataOwnerPkg = ps.pkg;
12442                    }
12443                }
12444
12445                if (dataOwnerPkg != null) {
12446                    // If installed, the package will get access to data left on the device by its
12447                    // predecessor. As a security measure, this is permited only if this is not a
12448                    // version downgrade or if the predecessor package is marked as debuggable and
12449                    // a downgrade is explicitly requested.
12450                    //
12451                    // On debuggable platform builds, downgrades are permitted even for
12452                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12453                    // not offer security guarantees and thus it's OK to disable some security
12454                    // mechanisms to make debugging/testing easier on those builds. However, even on
12455                    // debuggable builds downgrades of packages are permitted only if requested via
12456                    // installFlags. This is because we aim to keep the behavior of debuggable
12457                    // platform builds as close as possible to the behavior of non-debuggable
12458                    // platform builds.
12459                    final boolean downgradeRequested =
12460                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12461                    final boolean packageDebuggable =
12462                                (dataOwnerPkg.applicationInfo.flags
12463                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12464                    final boolean downgradePermitted =
12465                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12466                    if (!downgradePermitted) {
12467                        try {
12468                            checkDowngrade(dataOwnerPkg, pkgLite);
12469                        } catch (PackageManagerException e) {
12470                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12471                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12472                        }
12473                    }
12474                }
12475
12476                if (installedPkg != null) {
12477                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12478                        // Check for updated system application.
12479                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12480                            if (onSd) {
12481                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12482                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12483                            }
12484                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12485                        } else {
12486                            if (onSd) {
12487                                // Install flag overrides everything.
12488                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12489                            }
12490                            // If current upgrade specifies particular preference
12491                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12492                                // Application explicitly specified internal.
12493                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12494                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12495                                // App explictly prefers external. Let policy decide
12496                            } else {
12497                                // Prefer previous location
12498                                if (isExternal(installedPkg)) {
12499                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12500                                }
12501                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12502                            }
12503                        }
12504                    } else {
12505                        // Invalid install. Return error code
12506                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12507                    }
12508                }
12509            }
12510            // All the special cases have been taken care of.
12511            // Return result based on recommended install location.
12512            if (onSd) {
12513                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12514            }
12515            return pkgLite.recommendedInstallLocation;
12516        }
12517
12518        /*
12519         * Invoke remote method to get package information and install
12520         * location values. Override install location based on default
12521         * policy if needed and then create install arguments based
12522         * on the install location.
12523         */
12524        public void handleStartCopy() throws RemoteException {
12525            int ret = PackageManager.INSTALL_SUCCEEDED;
12526
12527            // If we're already staged, we've firmly committed to an install location
12528            if (origin.staged) {
12529                if (origin.file != null) {
12530                    installFlags |= PackageManager.INSTALL_INTERNAL;
12531                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12532                } else if (origin.cid != null) {
12533                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12534                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12535                } else {
12536                    throw new IllegalStateException("Invalid stage location");
12537                }
12538            }
12539
12540            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12541            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12542            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12543            PackageInfoLite pkgLite = null;
12544
12545            if (onInt && onSd) {
12546                // Check if both bits are set.
12547                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12548                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12549            } else if (onSd && ephemeral) {
12550                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12551                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12552            } else {
12553                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12554                        packageAbiOverride);
12555
12556                if (DEBUG_EPHEMERAL && ephemeral) {
12557                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12558                }
12559
12560                /*
12561                 * If we have too little free space, try to free cache
12562                 * before giving up.
12563                 */
12564                if (!origin.staged && pkgLite.recommendedInstallLocation
12565                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12566                    // TODO: focus freeing disk space on the target device
12567                    final StorageManager storage = StorageManager.from(mContext);
12568                    final long lowThreshold = storage.getStorageLowBytes(
12569                            Environment.getDataDirectory());
12570
12571                    final long sizeBytes = mContainerService.calculateInstalledSize(
12572                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12573
12574                    try {
12575                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12576                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12577                                installFlags, packageAbiOverride);
12578                    } catch (InstallerException e) {
12579                        Slog.w(TAG, "Failed to free cache", e);
12580                    }
12581
12582                    /*
12583                     * The cache free must have deleted the file we
12584                     * downloaded to install.
12585                     *
12586                     * TODO: fix the "freeCache" call to not delete
12587                     *       the file we care about.
12588                     */
12589                    if (pkgLite.recommendedInstallLocation
12590                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12591                        pkgLite.recommendedInstallLocation
12592                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12593                    }
12594                }
12595            }
12596
12597            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12598                int loc = pkgLite.recommendedInstallLocation;
12599                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12600                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12601                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12602                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12603                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12604                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12605                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12606                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12607                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12608                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12609                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12610                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12611                } else {
12612                    // Override with defaults if needed.
12613                    loc = installLocationPolicy(pkgLite);
12614                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12615                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12616                    } else if (!onSd && !onInt) {
12617                        // Override install location with flags
12618                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12619                            // Set the flag to install on external media.
12620                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12621                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12622                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12623                            if (DEBUG_EPHEMERAL) {
12624                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12625                            }
12626                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12627                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12628                                    |PackageManager.INSTALL_INTERNAL);
12629                        } else {
12630                            // Make sure the flag for installing on external
12631                            // media is unset
12632                            installFlags |= PackageManager.INSTALL_INTERNAL;
12633                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12634                        }
12635                    }
12636                }
12637            }
12638
12639            final InstallArgs args = createInstallArgs(this);
12640            mArgs = args;
12641
12642            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12643                // TODO: http://b/22976637
12644                // Apps installed for "all" users use the device owner to verify the app
12645                UserHandle verifierUser = getUser();
12646                if (verifierUser == UserHandle.ALL) {
12647                    verifierUser = UserHandle.SYSTEM;
12648                }
12649
12650                /*
12651                 * Determine if we have any installed package verifiers. If we
12652                 * do, then we'll defer to them to verify the packages.
12653                 */
12654                final int requiredUid = mRequiredVerifierPackage == null ? -1
12655                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12656                                verifierUser.getIdentifier());
12657                if (!origin.existing && requiredUid != -1
12658                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12659                    final Intent verification = new Intent(
12660                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12661                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12662                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12663                            PACKAGE_MIME_TYPE);
12664                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12665
12666                    // Query all live verifiers based on current user state
12667                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12668                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12669
12670                    if (DEBUG_VERIFY) {
12671                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12672                                + verification.toString() + " with " + pkgLite.verifiers.length
12673                                + " optional verifiers");
12674                    }
12675
12676                    final int verificationId = mPendingVerificationToken++;
12677
12678                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12679
12680                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12681                            installerPackageName);
12682
12683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12684                            installFlags);
12685
12686                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12687                            pkgLite.packageName);
12688
12689                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12690                            pkgLite.versionCode);
12691
12692                    if (verificationInfo != null) {
12693                        if (verificationInfo.originatingUri != null) {
12694                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12695                                    verificationInfo.originatingUri);
12696                        }
12697                        if (verificationInfo.referrer != null) {
12698                            verification.putExtra(Intent.EXTRA_REFERRER,
12699                                    verificationInfo.referrer);
12700                        }
12701                        if (verificationInfo.originatingUid >= 0) {
12702                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12703                                    verificationInfo.originatingUid);
12704                        }
12705                        if (verificationInfo.installerUid >= 0) {
12706                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12707                                    verificationInfo.installerUid);
12708                        }
12709                    }
12710
12711                    final PackageVerificationState verificationState = new PackageVerificationState(
12712                            requiredUid, args);
12713
12714                    mPendingVerification.append(verificationId, verificationState);
12715
12716                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12717                            receivers, verificationState);
12718
12719                    /*
12720                     * If any sufficient verifiers were listed in the package
12721                     * manifest, attempt to ask them.
12722                     */
12723                    if (sufficientVerifiers != null) {
12724                        final int N = sufficientVerifiers.size();
12725                        if (N == 0) {
12726                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12727                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12728                        } else {
12729                            for (int i = 0; i < N; i++) {
12730                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12731
12732                                final Intent sufficientIntent = new Intent(verification);
12733                                sufficientIntent.setComponent(verifierComponent);
12734                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12735                            }
12736                        }
12737                    }
12738
12739                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12740                            mRequiredVerifierPackage, receivers);
12741                    if (ret == PackageManager.INSTALL_SUCCEEDED
12742                            && mRequiredVerifierPackage != null) {
12743                        Trace.asyncTraceBegin(
12744                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12745                        /*
12746                         * Send the intent to the required verification agent,
12747                         * but only start the verification timeout after the
12748                         * target BroadcastReceivers have run.
12749                         */
12750                        verification.setComponent(requiredVerifierComponent);
12751                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12752                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12753                                new BroadcastReceiver() {
12754                                    @Override
12755                                    public void onReceive(Context context, Intent intent) {
12756                                        final Message msg = mHandler
12757                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12758                                        msg.arg1 = verificationId;
12759                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12760                                    }
12761                                }, null, 0, null, null);
12762
12763                        /*
12764                         * We don't want the copy to proceed until verification
12765                         * succeeds, so null out this field.
12766                         */
12767                        mArgs = null;
12768                    }
12769                } else {
12770                    /*
12771                     * No package verification is enabled, so immediately start
12772                     * the remote call to initiate copy using temporary file.
12773                     */
12774                    ret = args.copyApk(mContainerService, true);
12775                }
12776            }
12777
12778            mRet = ret;
12779        }
12780
12781        @Override
12782        void handleReturnCode() {
12783            // If mArgs is null, then MCS couldn't be reached. When it
12784            // reconnects, it will try again to install. At that point, this
12785            // will succeed.
12786            if (mArgs != null) {
12787                processPendingInstall(mArgs, mRet);
12788            }
12789        }
12790
12791        @Override
12792        void handleServiceError() {
12793            mArgs = createInstallArgs(this);
12794            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12795        }
12796
12797        public boolean isForwardLocked() {
12798            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12799        }
12800    }
12801
12802    /**
12803     * Used during creation of InstallArgs
12804     *
12805     * @param installFlags package installation flags
12806     * @return true if should be installed on external storage
12807     */
12808    private static boolean installOnExternalAsec(int installFlags) {
12809        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12810            return false;
12811        }
12812        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12813            return true;
12814        }
12815        return false;
12816    }
12817
12818    /**
12819     * Used during creation of InstallArgs
12820     *
12821     * @param installFlags package installation flags
12822     * @return true if should be installed as forward locked
12823     */
12824    private static boolean installForwardLocked(int installFlags) {
12825        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12826    }
12827
12828    private InstallArgs createInstallArgs(InstallParams params) {
12829        if (params.move != null) {
12830            return new MoveInstallArgs(params);
12831        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12832            return new AsecInstallArgs(params);
12833        } else {
12834            return new FileInstallArgs(params);
12835        }
12836    }
12837
12838    /**
12839     * Create args that describe an existing installed package. Typically used
12840     * when cleaning up old installs, or used as a move source.
12841     */
12842    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12843            String resourcePath, String[] instructionSets) {
12844        final boolean isInAsec;
12845        if (installOnExternalAsec(installFlags)) {
12846            /* Apps on SD card are always in ASEC containers. */
12847            isInAsec = true;
12848        } else if (installForwardLocked(installFlags)
12849                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12850            /*
12851             * Forward-locked apps are only in ASEC containers if they're the
12852             * new style
12853             */
12854            isInAsec = true;
12855        } else {
12856            isInAsec = false;
12857        }
12858
12859        if (isInAsec) {
12860            return new AsecInstallArgs(codePath, instructionSets,
12861                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12862        } else {
12863            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12864        }
12865    }
12866
12867    static abstract class InstallArgs {
12868        /** @see InstallParams#origin */
12869        final OriginInfo origin;
12870        /** @see InstallParams#move */
12871        final MoveInfo move;
12872
12873        final IPackageInstallObserver2 observer;
12874        // Always refers to PackageManager flags only
12875        final int installFlags;
12876        final String installerPackageName;
12877        final String volumeUuid;
12878        final UserHandle user;
12879        final String abiOverride;
12880        final String[] installGrantPermissions;
12881        /** If non-null, drop an async trace when the install completes */
12882        final String traceMethod;
12883        final int traceCookie;
12884        final Certificate[][] certificates;
12885
12886        // The list of instruction sets supported by this app. This is currently
12887        // only used during the rmdex() phase to clean up resources. We can get rid of this
12888        // if we move dex files under the common app path.
12889        /* nullable */ String[] instructionSets;
12890
12891        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12892                int installFlags, String installerPackageName, String volumeUuid,
12893                UserHandle user, String[] instructionSets,
12894                String abiOverride, String[] installGrantPermissions,
12895                String traceMethod, int traceCookie, Certificate[][] certificates) {
12896            this.origin = origin;
12897            this.move = move;
12898            this.installFlags = installFlags;
12899            this.observer = observer;
12900            this.installerPackageName = installerPackageName;
12901            this.volumeUuid = volumeUuid;
12902            this.user = user;
12903            this.instructionSets = instructionSets;
12904            this.abiOverride = abiOverride;
12905            this.installGrantPermissions = installGrantPermissions;
12906            this.traceMethod = traceMethod;
12907            this.traceCookie = traceCookie;
12908            this.certificates = certificates;
12909        }
12910
12911        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12912        abstract int doPreInstall(int status);
12913
12914        /**
12915         * Rename package into final resting place. All paths on the given
12916         * scanned package should be updated to reflect the rename.
12917         */
12918        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12919        abstract int doPostInstall(int status, int uid);
12920
12921        /** @see PackageSettingBase#codePathString */
12922        abstract String getCodePath();
12923        /** @see PackageSettingBase#resourcePathString */
12924        abstract String getResourcePath();
12925
12926        // Need installer lock especially for dex file removal.
12927        abstract void cleanUpResourcesLI();
12928        abstract boolean doPostDeleteLI(boolean delete);
12929
12930        /**
12931         * Called before the source arguments are copied. This is used mostly
12932         * for MoveParams when it needs to read the source file to put it in the
12933         * destination.
12934         */
12935        int doPreCopy() {
12936            return PackageManager.INSTALL_SUCCEEDED;
12937        }
12938
12939        /**
12940         * Called after the source arguments are copied. This is used mostly for
12941         * MoveParams when it needs to read the source file to put it in the
12942         * destination.
12943         */
12944        int doPostCopy(int uid) {
12945            return PackageManager.INSTALL_SUCCEEDED;
12946        }
12947
12948        protected boolean isFwdLocked() {
12949            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12950        }
12951
12952        protected boolean isExternalAsec() {
12953            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12954        }
12955
12956        protected boolean isEphemeral() {
12957            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12958        }
12959
12960        UserHandle getUser() {
12961            return user;
12962        }
12963    }
12964
12965    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12966        if (!allCodePaths.isEmpty()) {
12967            if (instructionSets == null) {
12968                throw new IllegalStateException("instructionSet == null");
12969            }
12970            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12971            for (String codePath : allCodePaths) {
12972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12973                    try {
12974                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12975                    } catch (InstallerException ignored) {
12976                    }
12977                }
12978            }
12979        }
12980    }
12981
12982    /**
12983     * Logic to handle installation of non-ASEC applications, including copying
12984     * and renaming logic.
12985     */
12986    class FileInstallArgs extends InstallArgs {
12987        private File codeFile;
12988        private File resourceFile;
12989
12990        // Example topology:
12991        // /data/app/com.example/base.apk
12992        // /data/app/com.example/split_foo.apk
12993        // /data/app/com.example/lib/arm/libfoo.so
12994        // /data/app/com.example/lib/arm64/libfoo.so
12995        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12996
12997        /** New install */
12998        FileInstallArgs(InstallParams params) {
12999            super(params.origin, params.move, params.observer, params.installFlags,
13000                    params.installerPackageName, params.volumeUuid,
13001                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13002                    params.grantedRuntimePermissions,
13003                    params.traceMethod, params.traceCookie, params.certificates);
13004            if (isFwdLocked()) {
13005                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13006            }
13007        }
13008
13009        /** Existing install */
13010        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13011            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13012                    null, null, null, 0, null /*certificates*/);
13013            this.codeFile = (codePath != null) ? new File(codePath) : null;
13014            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13015        }
13016
13017        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13018            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13019            try {
13020                return doCopyApk(imcs, temp);
13021            } finally {
13022                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13023            }
13024        }
13025
13026        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13027            if (origin.staged) {
13028                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13029                codeFile = origin.file;
13030                resourceFile = origin.file;
13031                return PackageManager.INSTALL_SUCCEEDED;
13032            }
13033
13034            try {
13035                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13036                final File tempDir =
13037                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13038                codeFile = tempDir;
13039                resourceFile = tempDir;
13040            } catch (IOException e) {
13041                Slog.w(TAG, "Failed to create copy file: " + e);
13042                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13043            }
13044
13045            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13046                @Override
13047                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13048                    if (!FileUtils.isValidExtFilename(name)) {
13049                        throw new IllegalArgumentException("Invalid filename: " + name);
13050                    }
13051                    try {
13052                        final File file = new File(codeFile, name);
13053                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13054                                O_RDWR | O_CREAT, 0644);
13055                        Os.chmod(file.getAbsolutePath(), 0644);
13056                        return new ParcelFileDescriptor(fd);
13057                    } catch (ErrnoException e) {
13058                        throw new RemoteException("Failed to open: " + e.getMessage());
13059                    }
13060                }
13061            };
13062
13063            int ret = PackageManager.INSTALL_SUCCEEDED;
13064            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13065            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13066                Slog.e(TAG, "Failed to copy package");
13067                return ret;
13068            }
13069
13070            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13071            NativeLibraryHelper.Handle handle = null;
13072            try {
13073                handle = NativeLibraryHelper.Handle.create(codeFile);
13074                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13075                        abiOverride);
13076            } catch (IOException e) {
13077                Slog.e(TAG, "Copying native libraries failed", e);
13078                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13079            } finally {
13080                IoUtils.closeQuietly(handle);
13081            }
13082
13083            return ret;
13084        }
13085
13086        int doPreInstall(int status) {
13087            if (status != PackageManager.INSTALL_SUCCEEDED) {
13088                cleanUp();
13089            }
13090            return status;
13091        }
13092
13093        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13094            if (status != PackageManager.INSTALL_SUCCEEDED) {
13095                cleanUp();
13096                return false;
13097            }
13098
13099            final File targetDir = codeFile.getParentFile();
13100            final File beforeCodeFile = codeFile;
13101            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13102
13103            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13104            try {
13105                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13106            } catch (ErrnoException e) {
13107                Slog.w(TAG, "Failed to rename", e);
13108                return false;
13109            }
13110
13111            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13112                Slog.w(TAG, "Failed to restorecon");
13113                return false;
13114            }
13115
13116            // Reflect the rename internally
13117            codeFile = afterCodeFile;
13118            resourceFile = afterCodeFile;
13119
13120            // Reflect the rename in scanned details
13121            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13122            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13123                    afterCodeFile, pkg.baseCodePath));
13124            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13125                    afterCodeFile, pkg.splitCodePaths));
13126
13127            // Reflect the rename in app info
13128            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13129            pkg.setApplicationInfoCodePath(pkg.codePath);
13130            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13131            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13132            pkg.setApplicationInfoResourcePath(pkg.codePath);
13133            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13134            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13135
13136            return true;
13137        }
13138
13139        int doPostInstall(int status, int uid) {
13140            if (status != PackageManager.INSTALL_SUCCEEDED) {
13141                cleanUp();
13142            }
13143            return status;
13144        }
13145
13146        @Override
13147        String getCodePath() {
13148            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13149        }
13150
13151        @Override
13152        String getResourcePath() {
13153            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13154        }
13155
13156        private boolean cleanUp() {
13157            if (codeFile == null || !codeFile.exists()) {
13158                return false;
13159            }
13160
13161            removeCodePathLI(codeFile);
13162
13163            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13164                resourceFile.delete();
13165            }
13166
13167            return true;
13168        }
13169
13170        void cleanUpResourcesLI() {
13171            // Try enumerating all code paths before deleting
13172            List<String> allCodePaths = Collections.EMPTY_LIST;
13173            if (codeFile != null && codeFile.exists()) {
13174                try {
13175                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13176                    allCodePaths = pkg.getAllCodePaths();
13177                } catch (PackageParserException e) {
13178                    // Ignored; we tried our best
13179                }
13180            }
13181
13182            cleanUp();
13183            removeDexFiles(allCodePaths, instructionSets);
13184        }
13185
13186        boolean doPostDeleteLI(boolean delete) {
13187            // XXX err, shouldn't we respect the delete flag?
13188            cleanUpResourcesLI();
13189            return true;
13190        }
13191    }
13192
13193    private boolean isAsecExternal(String cid) {
13194        final String asecPath = PackageHelper.getSdFilesystem(cid);
13195        return !asecPath.startsWith(mAsecInternalPath);
13196    }
13197
13198    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13199            PackageManagerException {
13200        if (copyRet < 0) {
13201            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13202                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13203                throw new PackageManagerException(copyRet, message);
13204            }
13205        }
13206    }
13207
13208    /**
13209     * Extract the MountService "container ID" from the full code path of an
13210     * .apk.
13211     */
13212    static String cidFromCodePath(String fullCodePath) {
13213        int eidx = fullCodePath.lastIndexOf("/");
13214        String subStr1 = fullCodePath.substring(0, eidx);
13215        int sidx = subStr1.lastIndexOf("/");
13216        return subStr1.substring(sidx+1, eidx);
13217    }
13218
13219    /**
13220     * Logic to handle installation of ASEC applications, including copying and
13221     * renaming logic.
13222     */
13223    class AsecInstallArgs extends InstallArgs {
13224        static final String RES_FILE_NAME = "pkg.apk";
13225        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13226
13227        String cid;
13228        String packagePath;
13229        String resourcePath;
13230
13231        /** New install */
13232        AsecInstallArgs(InstallParams params) {
13233            super(params.origin, params.move, params.observer, params.installFlags,
13234                    params.installerPackageName, params.volumeUuid,
13235                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13236                    params.grantedRuntimePermissions,
13237                    params.traceMethod, params.traceCookie, params.certificates);
13238        }
13239
13240        /** Existing install */
13241        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13242                        boolean isExternal, boolean isForwardLocked) {
13243            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13244              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13245                    instructionSets, null, null, null, 0, null /*certificates*/);
13246            // Hackily pretend we're still looking at a full code path
13247            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13248                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13249            }
13250
13251            // Extract cid from fullCodePath
13252            int eidx = fullCodePath.lastIndexOf("/");
13253            String subStr1 = fullCodePath.substring(0, eidx);
13254            int sidx = subStr1.lastIndexOf("/");
13255            cid = subStr1.substring(sidx+1, eidx);
13256            setMountPath(subStr1);
13257        }
13258
13259        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13260            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13261              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13262                    instructionSets, null, null, null, 0, null /*certificates*/);
13263            this.cid = cid;
13264            setMountPath(PackageHelper.getSdDir(cid));
13265        }
13266
13267        void createCopyFile() {
13268            cid = mInstallerService.allocateExternalStageCidLegacy();
13269        }
13270
13271        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13272            if (origin.staged && origin.cid != null) {
13273                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13274                cid = origin.cid;
13275                setMountPath(PackageHelper.getSdDir(cid));
13276                return PackageManager.INSTALL_SUCCEEDED;
13277            }
13278
13279            if (temp) {
13280                createCopyFile();
13281            } else {
13282                /*
13283                 * Pre-emptively destroy the container since it's destroyed if
13284                 * copying fails due to it existing anyway.
13285                 */
13286                PackageHelper.destroySdDir(cid);
13287            }
13288
13289            final String newMountPath = imcs.copyPackageToContainer(
13290                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13291                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13292
13293            if (newMountPath != null) {
13294                setMountPath(newMountPath);
13295                return PackageManager.INSTALL_SUCCEEDED;
13296            } else {
13297                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13298            }
13299        }
13300
13301        @Override
13302        String getCodePath() {
13303            return packagePath;
13304        }
13305
13306        @Override
13307        String getResourcePath() {
13308            return resourcePath;
13309        }
13310
13311        int doPreInstall(int status) {
13312            if (status != PackageManager.INSTALL_SUCCEEDED) {
13313                // Destroy container
13314                PackageHelper.destroySdDir(cid);
13315            } else {
13316                boolean mounted = PackageHelper.isContainerMounted(cid);
13317                if (!mounted) {
13318                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13319                            Process.SYSTEM_UID);
13320                    if (newMountPath != null) {
13321                        setMountPath(newMountPath);
13322                    } else {
13323                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13324                    }
13325                }
13326            }
13327            return status;
13328        }
13329
13330        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13331            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13332            String newMountPath = null;
13333            if (PackageHelper.isContainerMounted(cid)) {
13334                // Unmount the container
13335                if (!PackageHelper.unMountSdDir(cid)) {
13336                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13337                    return false;
13338                }
13339            }
13340            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13341                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13342                        " which might be stale. Will try to clean up.");
13343                // Clean up the stale container and proceed to recreate.
13344                if (!PackageHelper.destroySdDir(newCacheId)) {
13345                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13346                    return false;
13347                }
13348                // Successfully cleaned up stale container. Try to rename again.
13349                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13350                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13351                            + " inspite of cleaning it up.");
13352                    return false;
13353                }
13354            }
13355            if (!PackageHelper.isContainerMounted(newCacheId)) {
13356                Slog.w(TAG, "Mounting container " + newCacheId);
13357                newMountPath = PackageHelper.mountSdDir(newCacheId,
13358                        getEncryptKey(), Process.SYSTEM_UID);
13359            } else {
13360                newMountPath = PackageHelper.getSdDir(newCacheId);
13361            }
13362            if (newMountPath == null) {
13363                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13364                return false;
13365            }
13366            Log.i(TAG, "Succesfully renamed " + cid +
13367                    " to " + newCacheId +
13368                    " at new path: " + newMountPath);
13369            cid = newCacheId;
13370
13371            final File beforeCodeFile = new File(packagePath);
13372            setMountPath(newMountPath);
13373            final File afterCodeFile = new File(packagePath);
13374
13375            // Reflect the rename in scanned details
13376            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13377            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13378                    afterCodeFile, pkg.baseCodePath));
13379            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13380                    afterCodeFile, pkg.splitCodePaths));
13381
13382            // Reflect the rename in app info
13383            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13384            pkg.setApplicationInfoCodePath(pkg.codePath);
13385            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13386            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13387            pkg.setApplicationInfoResourcePath(pkg.codePath);
13388            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13389            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13390
13391            return true;
13392        }
13393
13394        private void setMountPath(String mountPath) {
13395            final File mountFile = new File(mountPath);
13396
13397            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13398            if (monolithicFile.exists()) {
13399                packagePath = monolithicFile.getAbsolutePath();
13400                if (isFwdLocked()) {
13401                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13402                } else {
13403                    resourcePath = packagePath;
13404                }
13405            } else {
13406                packagePath = mountFile.getAbsolutePath();
13407                resourcePath = packagePath;
13408            }
13409        }
13410
13411        int doPostInstall(int status, int uid) {
13412            if (status != PackageManager.INSTALL_SUCCEEDED) {
13413                cleanUp();
13414            } else {
13415                final int groupOwner;
13416                final String protectedFile;
13417                if (isFwdLocked()) {
13418                    groupOwner = UserHandle.getSharedAppGid(uid);
13419                    protectedFile = RES_FILE_NAME;
13420                } else {
13421                    groupOwner = -1;
13422                    protectedFile = null;
13423                }
13424
13425                if (uid < Process.FIRST_APPLICATION_UID
13426                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13427                    Slog.e(TAG, "Failed to finalize " + cid);
13428                    PackageHelper.destroySdDir(cid);
13429                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13430                }
13431
13432                boolean mounted = PackageHelper.isContainerMounted(cid);
13433                if (!mounted) {
13434                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13435                }
13436            }
13437            return status;
13438        }
13439
13440        private void cleanUp() {
13441            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13442
13443            // Destroy secure container
13444            PackageHelper.destroySdDir(cid);
13445        }
13446
13447        private List<String> getAllCodePaths() {
13448            final File codeFile = new File(getCodePath());
13449            if (codeFile != null && codeFile.exists()) {
13450                try {
13451                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13452                    return pkg.getAllCodePaths();
13453                } catch (PackageParserException e) {
13454                    // Ignored; we tried our best
13455                }
13456            }
13457            return Collections.EMPTY_LIST;
13458        }
13459
13460        void cleanUpResourcesLI() {
13461            // Enumerate all code paths before deleting
13462            cleanUpResourcesLI(getAllCodePaths());
13463        }
13464
13465        private void cleanUpResourcesLI(List<String> allCodePaths) {
13466            cleanUp();
13467            removeDexFiles(allCodePaths, instructionSets);
13468        }
13469
13470        String getPackageName() {
13471            return getAsecPackageName(cid);
13472        }
13473
13474        boolean doPostDeleteLI(boolean delete) {
13475            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13476            final List<String> allCodePaths = getAllCodePaths();
13477            boolean mounted = PackageHelper.isContainerMounted(cid);
13478            if (mounted) {
13479                // Unmount first
13480                if (PackageHelper.unMountSdDir(cid)) {
13481                    mounted = false;
13482                }
13483            }
13484            if (!mounted && delete) {
13485                cleanUpResourcesLI(allCodePaths);
13486            }
13487            return !mounted;
13488        }
13489
13490        @Override
13491        int doPreCopy() {
13492            if (isFwdLocked()) {
13493                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13494                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13495                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13496                }
13497            }
13498
13499            return PackageManager.INSTALL_SUCCEEDED;
13500        }
13501
13502        @Override
13503        int doPostCopy(int uid) {
13504            if (isFwdLocked()) {
13505                if (uid < Process.FIRST_APPLICATION_UID
13506                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13507                                RES_FILE_NAME)) {
13508                    Slog.e(TAG, "Failed to finalize " + cid);
13509                    PackageHelper.destroySdDir(cid);
13510                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13511                }
13512            }
13513
13514            return PackageManager.INSTALL_SUCCEEDED;
13515        }
13516    }
13517
13518    /**
13519     * Logic to handle movement of existing installed applications.
13520     */
13521    class MoveInstallArgs extends InstallArgs {
13522        private File codeFile;
13523        private File resourceFile;
13524
13525        /** New install */
13526        MoveInstallArgs(InstallParams params) {
13527            super(params.origin, params.move, params.observer, params.installFlags,
13528                    params.installerPackageName, params.volumeUuid,
13529                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13530                    params.grantedRuntimePermissions,
13531                    params.traceMethod, params.traceCookie, params.certificates);
13532        }
13533
13534        int copyApk(IMediaContainerService imcs, boolean temp) {
13535            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13536                    + move.fromUuid + " to " + move.toUuid);
13537            synchronized (mInstaller) {
13538                try {
13539                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13540                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13541                } catch (InstallerException e) {
13542                    Slog.w(TAG, "Failed to move app", e);
13543                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13544                }
13545            }
13546
13547            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13548            resourceFile = codeFile;
13549            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13550
13551            return PackageManager.INSTALL_SUCCEEDED;
13552        }
13553
13554        int doPreInstall(int status) {
13555            if (status != PackageManager.INSTALL_SUCCEEDED) {
13556                cleanUp(move.toUuid);
13557            }
13558            return status;
13559        }
13560
13561        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13562            if (status != PackageManager.INSTALL_SUCCEEDED) {
13563                cleanUp(move.toUuid);
13564                return false;
13565            }
13566
13567            // Reflect the move in app info
13568            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13569            pkg.setApplicationInfoCodePath(pkg.codePath);
13570            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13571            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13572            pkg.setApplicationInfoResourcePath(pkg.codePath);
13573            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13574            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13575
13576            return true;
13577        }
13578
13579        int doPostInstall(int status, int uid) {
13580            if (status == PackageManager.INSTALL_SUCCEEDED) {
13581                cleanUp(move.fromUuid);
13582            } else {
13583                cleanUp(move.toUuid);
13584            }
13585            return status;
13586        }
13587
13588        @Override
13589        String getCodePath() {
13590            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13591        }
13592
13593        @Override
13594        String getResourcePath() {
13595            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13596        }
13597
13598        private boolean cleanUp(String volumeUuid) {
13599            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13600                    move.dataAppName);
13601            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13602            final int[] userIds = sUserManager.getUserIds();
13603            synchronized (mInstallLock) {
13604                // Clean up both app data and code
13605                // All package moves are frozen until finished
13606                for (int userId : userIds) {
13607                    try {
13608                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13609                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13610                    } catch (InstallerException e) {
13611                        Slog.w(TAG, String.valueOf(e));
13612                    }
13613                }
13614                removeCodePathLI(codeFile);
13615            }
13616            return true;
13617        }
13618
13619        void cleanUpResourcesLI() {
13620            throw new UnsupportedOperationException();
13621        }
13622
13623        boolean doPostDeleteLI(boolean delete) {
13624            throw new UnsupportedOperationException();
13625        }
13626    }
13627
13628    static String getAsecPackageName(String packageCid) {
13629        int idx = packageCid.lastIndexOf("-");
13630        if (idx == -1) {
13631            return packageCid;
13632        }
13633        return packageCid.substring(0, idx);
13634    }
13635
13636    // Utility method used to create code paths based on package name and available index.
13637    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13638        String idxStr = "";
13639        int idx = 1;
13640        // Fall back to default value of idx=1 if prefix is not
13641        // part of oldCodePath
13642        if (oldCodePath != null) {
13643            String subStr = oldCodePath;
13644            // Drop the suffix right away
13645            if (suffix != null && subStr.endsWith(suffix)) {
13646                subStr = subStr.substring(0, subStr.length() - suffix.length());
13647            }
13648            // If oldCodePath already contains prefix find out the
13649            // ending index to either increment or decrement.
13650            int sidx = subStr.lastIndexOf(prefix);
13651            if (sidx != -1) {
13652                subStr = subStr.substring(sidx + prefix.length());
13653                if (subStr != null) {
13654                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13655                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13656                    }
13657                    try {
13658                        idx = Integer.parseInt(subStr);
13659                        if (idx <= 1) {
13660                            idx++;
13661                        } else {
13662                            idx--;
13663                        }
13664                    } catch(NumberFormatException e) {
13665                    }
13666                }
13667            }
13668        }
13669        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13670        return prefix + idxStr;
13671    }
13672
13673    private File getNextCodePath(File targetDir, String packageName) {
13674        int suffix = 1;
13675        File result;
13676        do {
13677            result = new File(targetDir, packageName + "-" + suffix);
13678            suffix++;
13679        } while (result.exists());
13680        return result;
13681    }
13682
13683    // Utility method that returns the relative package path with respect
13684    // to the installation directory. Like say for /data/data/com.test-1.apk
13685    // string com.test-1 is returned.
13686    static String deriveCodePathName(String codePath) {
13687        if (codePath == null) {
13688            return null;
13689        }
13690        final File codeFile = new File(codePath);
13691        final String name = codeFile.getName();
13692        if (codeFile.isDirectory()) {
13693            return name;
13694        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13695            final int lastDot = name.lastIndexOf('.');
13696            return name.substring(0, lastDot);
13697        } else {
13698            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13699            return null;
13700        }
13701    }
13702
13703    static class PackageInstalledInfo {
13704        String name;
13705        int uid;
13706        // The set of users that originally had this package installed.
13707        int[] origUsers;
13708        // The set of users that now have this package installed.
13709        int[] newUsers;
13710        PackageParser.Package pkg;
13711        int returnCode;
13712        String returnMsg;
13713        PackageRemovedInfo removedInfo;
13714        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13715
13716        public void setError(int code, String msg) {
13717            setReturnCode(code);
13718            setReturnMessage(msg);
13719            Slog.w(TAG, msg);
13720        }
13721
13722        public void setError(String msg, PackageParserException e) {
13723            setReturnCode(e.error);
13724            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13725            Slog.w(TAG, msg, e);
13726        }
13727
13728        public void setError(String msg, PackageManagerException e) {
13729            returnCode = e.error;
13730            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13731            Slog.w(TAG, msg, e);
13732        }
13733
13734        public void setReturnCode(int returnCode) {
13735            this.returnCode = returnCode;
13736            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13737            for (int i = 0; i < childCount; i++) {
13738                addedChildPackages.valueAt(i).returnCode = returnCode;
13739            }
13740        }
13741
13742        private void setReturnMessage(String returnMsg) {
13743            this.returnMsg = returnMsg;
13744            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13745            for (int i = 0; i < childCount; i++) {
13746                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13747            }
13748        }
13749
13750        // In some error cases we want to convey more info back to the observer
13751        String origPackage;
13752        String origPermission;
13753    }
13754
13755    /*
13756     * Install a non-existing package.
13757     */
13758    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13759            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13760            PackageInstalledInfo res) {
13761        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13762
13763        // Remember this for later, in case we need to rollback this install
13764        String pkgName = pkg.packageName;
13765
13766        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13767
13768        synchronized(mPackages) {
13769            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13770                // A package with the same name is already installed, though
13771                // it has been renamed to an older name.  The package we
13772                // are trying to install should be installed as an update to
13773                // the existing one, but that has not been requested, so bail.
13774                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13775                        + " without first uninstalling package running as "
13776                        + mSettings.mRenamedPackages.get(pkgName));
13777                return;
13778            }
13779            if (mPackages.containsKey(pkgName)) {
13780                // Don't allow installation over an existing package with the same name.
13781                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13782                        + " without first uninstalling.");
13783                return;
13784            }
13785        }
13786
13787        try {
13788            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13789                    System.currentTimeMillis(), user);
13790
13791            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13792
13793            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13794                prepareAppDataAfterInstallLIF(newPackage);
13795
13796            } else {
13797                // Remove package from internal structures, but keep around any
13798                // data that might have already existed
13799                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13800                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13801            }
13802        } catch (PackageManagerException e) {
13803            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13804        }
13805
13806        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13807    }
13808
13809    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13810        // Can't rotate keys during boot or if sharedUser.
13811        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13812                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13813            return false;
13814        }
13815        // app is using upgradeKeySets; make sure all are valid
13816        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13817        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13818        for (int i = 0; i < upgradeKeySets.length; i++) {
13819            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13820                Slog.wtf(TAG, "Package "
13821                         + (oldPs.name != null ? oldPs.name : "<null>")
13822                         + " contains upgrade-key-set reference to unknown key-set: "
13823                         + upgradeKeySets[i]
13824                         + " reverting to signatures check.");
13825                return false;
13826            }
13827        }
13828        return true;
13829    }
13830
13831    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13832        // Upgrade keysets are being used.  Determine if new package has a superset of the
13833        // required keys.
13834        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13835        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13836        for (int i = 0; i < upgradeKeySets.length; i++) {
13837            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13838            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13839                return true;
13840            }
13841        }
13842        return false;
13843    }
13844
13845    private static void updateDigest(MessageDigest digest, File file) throws IOException {
13846        try (DigestInputStream digestStream =
13847                new DigestInputStream(new FileInputStream(file), digest)) {
13848            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
13849        }
13850    }
13851
13852    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13853            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13854        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13855
13856        final PackageParser.Package oldPackage;
13857        final String pkgName = pkg.packageName;
13858        final int[] allUsers;
13859        final int[] installedUsers;
13860
13861        synchronized(mPackages) {
13862            oldPackage = mPackages.get(pkgName);
13863            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13864
13865            // don't allow upgrade to target a release SDK from a pre-release SDK
13866            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13867                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13868            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13869                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13870            if (oldTargetsPreRelease
13871                    && !newTargetsPreRelease
13872                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13873                Slog.w(TAG, "Can't install package targeting released sdk");
13874                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13875                return;
13876            }
13877
13878            // don't allow an upgrade from full to ephemeral
13879            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13880            if (isEphemeral && !oldIsEphemeral) {
13881                // can't downgrade from full to ephemeral
13882                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13883                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13884                return;
13885            }
13886
13887            // verify signatures are valid
13888            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13889            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13890                if (!checkUpgradeKeySetLP(ps, pkg)) {
13891                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13892                            "New package not signed by keys specified by upgrade-keysets: "
13893                                    + pkgName);
13894                    return;
13895                }
13896            } else {
13897                // default to original signature matching
13898                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13899                        != PackageManager.SIGNATURE_MATCH) {
13900                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13901                            "New package has a different signature: " + pkgName);
13902                    return;
13903                }
13904            }
13905
13906            // don't allow a system upgrade unless the upgrade hash matches
13907            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
13908                byte[] digestBytes = null;
13909                try {
13910                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
13911                    updateDigest(digest, new File(pkg.baseCodePath));
13912                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
13913                        for (String path : pkg.splitCodePaths) {
13914                            updateDigest(digest, new File(path));
13915                        }
13916                    }
13917                    digestBytes = digest.digest();
13918                } catch (NoSuchAlgorithmException | IOException e) {
13919                    res.setError(INSTALL_FAILED_INVALID_APK,
13920                            "Could not compute hash: " + pkgName);
13921                    return;
13922                }
13923                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
13924                    res.setError(INSTALL_FAILED_INVALID_APK,
13925                            "New package fails restrict-update check: " + pkgName);
13926                    return;
13927                }
13928                // retain upgrade restriction
13929                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
13930            }
13931
13932            // Check for shared user id changes
13933            String invalidPackageName =
13934                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13935            if (invalidPackageName != null) {
13936                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13937                        "Package " + invalidPackageName + " tried to change user "
13938                                + oldPackage.mSharedUserId);
13939                return;
13940            }
13941
13942            // In case of rollback, remember per-user/profile install state
13943            allUsers = sUserManager.getUserIds();
13944            installedUsers = ps.queryInstalledUsers(allUsers, true);
13945        }
13946
13947        // Update what is removed
13948        res.removedInfo = new PackageRemovedInfo();
13949        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13950        res.removedInfo.removedPackage = oldPackage.packageName;
13951        res.removedInfo.isUpdate = true;
13952        res.removedInfo.origUsers = installedUsers;
13953        final int childCount = (oldPackage.childPackages != null)
13954                ? oldPackage.childPackages.size() : 0;
13955        for (int i = 0; i < childCount; i++) {
13956            boolean childPackageUpdated = false;
13957            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13958            if (res.addedChildPackages != null) {
13959                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13960                if (childRes != null) {
13961                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13962                    childRes.removedInfo.removedPackage = childPkg.packageName;
13963                    childRes.removedInfo.isUpdate = true;
13964                    childPackageUpdated = true;
13965                }
13966            }
13967            if (!childPackageUpdated) {
13968                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13969                childRemovedRes.removedPackage = childPkg.packageName;
13970                childRemovedRes.isUpdate = false;
13971                childRemovedRes.dataRemoved = true;
13972                synchronized (mPackages) {
13973                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13974                    if (childPs != null) {
13975                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13976                    }
13977                }
13978                if (res.removedInfo.removedChildPackages == null) {
13979                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13980                }
13981                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13982            }
13983        }
13984
13985        boolean sysPkg = (isSystemApp(oldPackage));
13986        if (sysPkg) {
13987            // Set the system/privileged flags as needed
13988            final boolean privileged =
13989                    (oldPackage.applicationInfo.privateFlags
13990                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13991            final int systemPolicyFlags = policyFlags
13992                    | PackageParser.PARSE_IS_SYSTEM
13993                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
13994
13995            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
13996                    user, allUsers, installerPackageName, res);
13997        } else {
13998            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
13999                    user, allUsers, installerPackageName, res);
14000        }
14001    }
14002
14003    public List<String> getPreviousCodePaths(String packageName) {
14004        final PackageSetting ps = mSettings.mPackages.get(packageName);
14005        final List<String> result = new ArrayList<String>();
14006        if (ps != null && ps.oldCodePaths != null) {
14007            result.addAll(ps.oldCodePaths);
14008        }
14009        return result;
14010    }
14011
14012    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14013            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14014            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14015        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14016                + deletedPackage);
14017
14018        String pkgName = deletedPackage.packageName;
14019        boolean deletedPkg = true;
14020        boolean addedPkg = false;
14021        boolean updatedSettings = false;
14022        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14023        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14024                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14025
14026        final long origUpdateTime = (pkg.mExtras != null)
14027                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14028
14029        // First delete the existing package while retaining the data directory
14030        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14031                res.removedInfo, true, pkg)) {
14032            // If the existing package wasn't successfully deleted
14033            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14034            deletedPkg = false;
14035        } else {
14036            // Successfully deleted the old package; proceed with replace.
14037
14038            // If deleted package lived in a container, give users a chance to
14039            // relinquish resources before killing.
14040            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14041                if (DEBUG_INSTALL) {
14042                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14043                }
14044                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14045                final ArrayList<String> pkgList = new ArrayList<String>(1);
14046                pkgList.add(deletedPackage.applicationInfo.packageName);
14047                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14048            }
14049
14050            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14051                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14052            clearAppProfilesLIF(pkg);
14053
14054            try {
14055                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14056                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14057                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14058
14059                // Update the in-memory copy of the previous code paths.
14060                PackageSetting ps = mSettings.mPackages.get(pkgName);
14061                if (!killApp) {
14062                    if (ps.oldCodePaths == null) {
14063                        ps.oldCodePaths = new ArraySet<>();
14064                    }
14065                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14066                    if (deletedPackage.splitCodePaths != null) {
14067                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14068                    }
14069                } else {
14070                    ps.oldCodePaths = null;
14071                }
14072                if (ps.childPackageNames != null) {
14073                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14074                        final String childPkgName = ps.childPackageNames.get(i);
14075                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14076                        childPs.oldCodePaths = ps.oldCodePaths;
14077                    }
14078                }
14079                prepareAppDataAfterInstallLIF(newPackage);
14080                addedPkg = true;
14081            } catch (PackageManagerException e) {
14082                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14083            }
14084        }
14085
14086        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14087            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14088
14089            // Revert all internal state mutations and added folders for the failed install
14090            if (addedPkg) {
14091                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14092                        res.removedInfo, true, null);
14093            }
14094
14095            // Restore the old package
14096            if (deletedPkg) {
14097                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14098                File restoreFile = new File(deletedPackage.codePath);
14099                // Parse old package
14100                boolean oldExternal = isExternal(deletedPackage);
14101                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14102                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14103                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14104                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14105                try {
14106                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14107                            null);
14108                } catch (PackageManagerException e) {
14109                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14110                            + e.getMessage());
14111                    return;
14112                }
14113
14114                synchronized (mPackages) {
14115                    // Ensure the installer package name up to date
14116                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14117
14118                    // Update permissions for restored package
14119                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14120
14121                    mSettings.writeLPr();
14122                }
14123
14124                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14125            }
14126        } else {
14127            synchronized (mPackages) {
14128                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14129                if (ps != null) {
14130                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14131                    if (res.removedInfo.removedChildPackages != null) {
14132                        final int childCount = res.removedInfo.removedChildPackages.size();
14133                        // Iterate in reverse as we may modify the collection
14134                        for (int i = childCount - 1; i >= 0; i--) {
14135                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14136                            if (res.addedChildPackages.containsKey(childPackageName)) {
14137                                res.removedInfo.removedChildPackages.removeAt(i);
14138                            } else {
14139                                PackageRemovedInfo childInfo = res.removedInfo
14140                                        .removedChildPackages.valueAt(i);
14141                                childInfo.removedForAllUsers = mPackages.get(
14142                                        childInfo.removedPackage) == null;
14143                            }
14144                        }
14145                    }
14146                }
14147            }
14148        }
14149    }
14150
14151    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14152            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14153            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14154        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14155                + ", old=" + deletedPackage);
14156
14157        final boolean disabledSystem;
14158
14159        // Remove existing system package
14160        removePackageLI(deletedPackage, true);
14161
14162        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14163        if (!disabledSystem) {
14164            // We didn't need to disable the .apk as a current system package,
14165            // which means we are replacing another update that is already
14166            // installed.  We need to make sure to delete the older one's .apk.
14167            res.removedInfo.args = createInstallArgsForExisting(0,
14168                    deletedPackage.applicationInfo.getCodePath(),
14169                    deletedPackage.applicationInfo.getResourcePath(),
14170                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14171        } else {
14172            res.removedInfo.args = null;
14173        }
14174
14175        // Successfully disabled the old package. Now proceed with re-installation
14176        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14177                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14178        clearAppProfilesLIF(pkg);
14179
14180        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14181        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14182                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14183
14184        PackageParser.Package newPackage = null;
14185        try {
14186            // Add the package to the internal data structures
14187            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14188
14189            // Set the update and install times
14190            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14191            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14192                    System.currentTimeMillis());
14193
14194            // Update the package dynamic state if succeeded
14195            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14196                // Now that the install succeeded make sure we remove data
14197                // directories for any child package the update removed.
14198                final int deletedChildCount = (deletedPackage.childPackages != null)
14199                        ? deletedPackage.childPackages.size() : 0;
14200                final int newChildCount = (newPackage.childPackages != null)
14201                        ? newPackage.childPackages.size() : 0;
14202                for (int i = 0; i < deletedChildCount; i++) {
14203                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14204                    boolean childPackageDeleted = true;
14205                    for (int j = 0; j < newChildCount; j++) {
14206                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14207                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14208                            childPackageDeleted = false;
14209                            break;
14210                        }
14211                    }
14212                    if (childPackageDeleted) {
14213                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14214                                deletedChildPkg.packageName);
14215                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14216                            PackageRemovedInfo removedChildRes = res.removedInfo
14217                                    .removedChildPackages.get(deletedChildPkg.packageName);
14218                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14219                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14220                        }
14221                    }
14222                }
14223
14224                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14225                prepareAppDataAfterInstallLIF(newPackage);
14226            }
14227        } catch (PackageManagerException e) {
14228            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14229            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14230        }
14231
14232        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14233            // Re installation failed. Restore old information
14234            // Remove new pkg information
14235            if (newPackage != null) {
14236                removeInstalledPackageLI(newPackage, true);
14237            }
14238            // Add back the old system package
14239            try {
14240                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14241            } catch (PackageManagerException e) {
14242                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14243            }
14244
14245            synchronized (mPackages) {
14246                if (disabledSystem) {
14247                    enableSystemPackageLPw(deletedPackage);
14248                }
14249
14250                // Ensure the installer package name up to date
14251                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14252
14253                // Update permissions for restored package
14254                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14255
14256                mSettings.writeLPr();
14257            }
14258
14259            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14260                    + " after failed upgrade");
14261        }
14262    }
14263
14264    /**
14265     * Checks whether the parent or any of the child packages have a change shared
14266     * user. For a package to be a valid update the shred users of the parent and
14267     * the children should match. We may later support changing child shared users.
14268     * @param oldPkg The updated package.
14269     * @param newPkg The update package.
14270     * @return The shared user that change between the versions.
14271     */
14272    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14273            PackageParser.Package newPkg) {
14274        // Check parent shared user
14275        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14276            return newPkg.packageName;
14277        }
14278        // Check child shared users
14279        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14280        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14281        for (int i = 0; i < newChildCount; i++) {
14282            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14283            // If this child was present, did it have the same shared user?
14284            for (int j = 0; j < oldChildCount; j++) {
14285                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14286                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14287                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14288                    return newChildPkg.packageName;
14289                }
14290            }
14291        }
14292        return null;
14293    }
14294
14295    private void removeNativeBinariesLI(PackageSetting ps) {
14296        // Remove the lib path for the parent package
14297        if (ps != null) {
14298            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14299            // Remove the lib path for the child packages
14300            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14301            for (int i = 0; i < childCount; i++) {
14302                PackageSetting childPs = null;
14303                synchronized (mPackages) {
14304                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14305                }
14306                if (childPs != null) {
14307                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14308                            .legacyNativeLibraryPathString);
14309                }
14310            }
14311        }
14312    }
14313
14314    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14315        // Enable the parent package
14316        mSettings.enableSystemPackageLPw(pkg.packageName);
14317        // Enable the child packages
14318        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14319        for (int i = 0; i < childCount; i++) {
14320            PackageParser.Package childPkg = pkg.childPackages.get(i);
14321            mSettings.enableSystemPackageLPw(childPkg.packageName);
14322        }
14323    }
14324
14325    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14326            PackageParser.Package newPkg) {
14327        // Disable the parent package (parent always replaced)
14328        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14329        // Disable the child packages
14330        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14331        for (int i = 0; i < childCount; i++) {
14332            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14333            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14334            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14335        }
14336        return disabled;
14337    }
14338
14339    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14340            String installerPackageName) {
14341        // Enable the parent package
14342        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14343        // Enable the child packages
14344        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14345        for (int i = 0; i < childCount; i++) {
14346            PackageParser.Package childPkg = pkg.childPackages.get(i);
14347            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14348        }
14349    }
14350
14351    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14352        // Collect all used permissions in the UID
14353        ArraySet<String> usedPermissions = new ArraySet<>();
14354        final int packageCount = su.packages.size();
14355        for (int i = 0; i < packageCount; i++) {
14356            PackageSetting ps = su.packages.valueAt(i);
14357            if (ps.pkg == null) {
14358                continue;
14359            }
14360            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14361            for (int j = 0; j < requestedPermCount; j++) {
14362                String permission = ps.pkg.requestedPermissions.get(j);
14363                BasePermission bp = mSettings.mPermissions.get(permission);
14364                if (bp != null) {
14365                    usedPermissions.add(permission);
14366                }
14367            }
14368        }
14369
14370        PermissionsState permissionsState = su.getPermissionsState();
14371        // Prune install permissions
14372        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14373        final int installPermCount = installPermStates.size();
14374        for (int i = installPermCount - 1; i >= 0;  i--) {
14375            PermissionState permissionState = installPermStates.get(i);
14376            if (!usedPermissions.contains(permissionState.getName())) {
14377                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14378                if (bp != null) {
14379                    permissionsState.revokeInstallPermission(bp);
14380                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14381                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14382                }
14383            }
14384        }
14385
14386        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14387
14388        // Prune runtime permissions
14389        for (int userId : allUserIds) {
14390            List<PermissionState> runtimePermStates = permissionsState
14391                    .getRuntimePermissionStates(userId);
14392            final int runtimePermCount = runtimePermStates.size();
14393            for (int i = runtimePermCount - 1; i >= 0; i--) {
14394                PermissionState permissionState = runtimePermStates.get(i);
14395                if (!usedPermissions.contains(permissionState.getName())) {
14396                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14397                    if (bp != null) {
14398                        permissionsState.revokeRuntimePermission(bp, userId);
14399                        permissionsState.updatePermissionFlags(bp, userId,
14400                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14401                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14402                                runtimePermissionChangedUserIds, userId);
14403                    }
14404                }
14405            }
14406        }
14407
14408        return runtimePermissionChangedUserIds;
14409    }
14410
14411    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14412            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14413        // Update the parent package setting
14414        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14415                res, user);
14416        // Update the child packages setting
14417        final int childCount = (newPackage.childPackages != null)
14418                ? newPackage.childPackages.size() : 0;
14419        for (int i = 0; i < childCount; i++) {
14420            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14421            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14422            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14423                    childRes.origUsers, childRes, user);
14424        }
14425    }
14426
14427    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14428            String installerPackageName, int[] allUsers, int[] installedForUsers,
14429            PackageInstalledInfo res, UserHandle user) {
14430        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14431
14432        String pkgName = newPackage.packageName;
14433        synchronized (mPackages) {
14434            //write settings. the installStatus will be incomplete at this stage.
14435            //note that the new package setting would have already been
14436            //added to mPackages. It hasn't been persisted yet.
14437            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14438            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14439            mSettings.writeLPr();
14440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14441        }
14442
14443        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14444        synchronized (mPackages) {
14445            updatePermissionsLPw(newPackage.packageName, newPackage,
14446                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14447                            ? UPDATE_PERMISSIONS_ALL : 0));
14448            // For system-bundled packages, we assume that installing an upgraded version
14449            // of the package implies that the user actually wants to run that new code,
14450            // so we enable the package.
14451            PackageSetting ps = mSettings.mPackages.get(pkgName);
14452            final int userId = user.getIdentifier();
14453            if (ps != null) {
14454                if (isSystemApp(newPackage)) {
14455                    if (DEBUG_INSTALL) {
14456                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14457                    }
14458                    // Enable system package for requested users
14459                    if (res.origUsers != null) {
14460                        for (int origUserId : res.origUsers) {
14461                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14462                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14463                                        origUserId, installerPackageName);
14464                            }
14465                        }
14466                    }
14467                    // Also convey the prior install/uninstall state
14468                    if (allUsers != null && installedForUsers != null) {
14469                        for (int currentUserId : allUsers) {
14470                            final boolean installed = ArrayUtils.contains(
14471                                    installedForUsers, currentUserId);
14472                            if (DEBUG_INSTALL) {
14473                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14474                            }
14475                            ps.setInstalled(installed, currentUserId);
14476                        }
14477                        // these install state changes will be persisted in the
14478                        // upcoming call to mSettings.writeLPr().
14479                    }
14480                }
14481                // It's implied that when a user requests installation, they want the app to be
14482                // installed and enabled.
14483                if (userId != UserHandle.USER_ALL) {
14484                    ps.setInstalled(true, userId);
14485                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14486                }
14487            }
14488            res.name = pkgName;
14489            res.uid = newPackage.applicationInfo.uid;
14490            res.pkg = newPackage;
14491            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14492            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14493            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14494            //to update install status
14495            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14496            mSettings.writeLPr();
14497            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14498        }
14499
14500        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14501    }
14502
14503    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14504        try {
14505            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14506            installPackageLI(args, res);
14507        } finally {
14508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14509        }
14510    }
14511
14512    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14513        final int installFlags = args.installFlags;
14514        final String installerPackageName = args.installerPackageName;
14515        final String volumeUuid = args.volumeUuid;
14516        final File tmpPackageFile = new File(args.getCodePath());
14517        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14518        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14519                || (args.volumeUuid != null));
14520        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14521        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14522        boolean replace = false;
14523        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14524        if (args.move != null) {
14525            // moving a complete application; perform an initial scan on the new install location
14526            scanFlags |= SCAN_INITIAL;
14527        }
14528        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14529            scanFlags |= SCAN_DONT_KILL_APP;
14530        }
14531
14532        // Result object to be returned
14533        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14534
14535        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14536
14537        // Sanity check
14538        if (ephemeral && (forwardLocked || onExternal)) {
14539            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14540                    + " external=" + onExternal);
14541            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14542            return;
14543        }
14544
14545        // Retrieve PackageSettings and parse package
14546        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14547                | PackageParser.PARSE_ENFORCE_CODE
14548                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14549                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14550                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14551                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14552        PackageParser pp = new PackageParser();
14553        pp.setSeparateProcesses(mSeparateProcesses);
14554        pp.setDisplayMetrics(mMetrics);
14555
14556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14557        final PackageParser.Package pkg;
14558        try {
14559            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14560        } catch (PackageParserException e) {
14561            res.setError("Failed parse during installPackageLI", e);
14562            return;
14563        } finally {
14564            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14565        }
14566
14567        // If we are installing a clustered package add results for the children
14568        if (pkg.childPackages != null) {
14569            synchronized (mPackages) {
14570                final int childCount = pkg.childPackages.size();
14571                for (int i = 0; i < childCount; i++) {
14572                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14573                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14574                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14575                    childRes.pkg = childPkg;
14576                    childRes.name = childPkg.packageName;
14577                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14578                    if (childPs != null) {
14579                        childRes.origUsers = childPs.queryInstalledUsers(
14580                                sUserManager.getUserIds(), true);
14581                    }
14582                    if ((mPackages.containsKey(childPkg.packageName))) {
14583                        childRes.removedInfo = new PackageRemovedInfo();
14584                        childRes.removedInfo.removedPackage = childPkg.packageName;
14585                    }
14586                    if (res.addedChildPackages == null) {
14587                        res.addedChildPackages = new ArrayMap<>();
14588                    }
14589                    res.addedChildPackages.put(childPkg.packageName, childRes);
14590                }
14591            }
14592        }
14593
14594        // If package doesn't declare API override, mark that we have an install
14595        // time CPU ABI override.
14596        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14597            pkg.cpuAbiOverride = args.abiOverride;
14598        }
14599
14600        String pkgName = res.name = pkg.packageName;
14601        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14602            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14603                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14604                return;
14605            }
14606        }
14607
14608        try {
14609            // either use what we've been given or parse directly from the APK
14610            if (args.certificates != null) {
14611                try {
14612                    PackageParser.populateCertificates(pkg, args.certificates);
14613                } catch (PackageParserException e) {
14614                    // there was something wrong with the certificates we were given;
14615                    // try to pull them from the APK
14616                    PackageParser.collectCertificates(pkg, parseFlags);
14617                }
14618            } else {
14619                PackageParser.collectCertificates(pkg, parseFlags);
14620            }
14621        } catch (PackageParserException e) {
14622            res.setError("Failed collect during installPackageLI", e);
14623            return;
14624        }
14625
14626        // Get rid of all references to package scan path via parser.
14627        pp = null;
14628        String oldCodePath = null;
14629        boolean systemApp = false;
14630        synchronized (mPackages) {
14631            // Check if installing already existing package
14632            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14633                String oldName = mSettings.mRenamedPackages.get(pkgName);
14634                if (pkg.mOriginalPackages != null
14635                        && pkg.mOriginalPackages.contains(oldName)
14636                        && mPackages.containsKey(oldName)) {
14637                    // This package is derived from an original package,
14638                    // and this device has been updating from that original
14639                    // name.  We must continue using the original name, so
14640                    // rename the new package here.
14641                    pkg.setPackageName(oldName);
14642                    pkgName = pkg.packageName;
14643                    replace = true;
14644                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14645                            + oldName + " pkgName=" + pkgName);
14646                } else if (mPackages.containsKey(pkgName)) {
14647                    // This package, under its official name, already exists
14648                    // on the device; we should replace it.
14649                    replace = true;
14650                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14651                }
14652
14653                // Child packages are installed through the parent package
14654                if (pkg.parentPackage != null) {
14655                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14656                            "Package " + pkg.packageName + " is child of package "
14657                                    + pkg.parentPackage.parentPackage + ". Child packages "
14658                                    + "can be updated only through the parent package.");
14659                    return;
14660                }
14661
14662                if (replace) {
14663                    // Prevent apps opting out from runtime permissions
14664                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14665                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14666                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14667                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14668                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14669                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14670                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14671                                        + " doesn't support runtime permissions but the old"
14672                                        + " target SDK " + oldTargetSdk + " does.");
14673                        return;
14674                    }
14675
14676                    // Prevent installing of child packages
14677                    if (oldPackage.parentPackage != null) {
14678                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14679                                "Package " + pkg.packageName + " is child of package "
14680                                        + oldPackage.parentPackage + ". Child packages "
14681                                        + "can be updated only through the parent package.");
14682                        return;
14683                    }
14684                }
14685            }
14686
14687            PackageSetting ps = mSettings.mPackages.get(pkgName);
14688            if (ps != null) {
14689                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14690
14691                // Quick sanity check that we're signed correctly if updating;
14692                // we'll check this again later when scanning, but we want to
14693                // bail early here before tripping over redefined permissions.
14694                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14695                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14696                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14697                                + pkg.packageName + " upgrade keys do not match the "
14698                                + "previously installed version");
14699                        return;
14700                    }
14701                } else {
14702                    try {
14703                        verifySignaturesLP(ps, pkg);
14704                    } catch (PackageManagerException e) {
14705                        res.setError(e.error, e.getMessage());
14706                        return;
14707                    }
14708                }
14709
14710                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14711                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14712                    systemApp = (ps.pkg.applicationInfo.flags &
14713                            ApplicationInfo.FLAG_SYSTEM) != 0;
14714                }
14715                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14716            }
14717
14718            // Check whether the newly-scanned package wants to define an already-defined perm
14719            int N = pkg.permissions.size();
14720            for (int i = N-1; i >= 0; i--) {
14721                PackageParser.Permission perm = pkg.permissions.get(i);
14722                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14723                if (bp != null) {
14724                    // If the defining package is signed with our cert, it's okay.  This
14725                    // also includes the "updating the same package" case, of course.
14726                    // "updating same package" could also involve key-rotation.
14727                    final boolean sigsOk;
14728                    if (bp.sourcePackage.equals(pkg.packageName)
14729                            && (bp.packageSetting instanceof PackageSetting)
14730                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14731                                    scanFlags))) {
14732                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14733                    } else {
14734                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14735                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14736                    }
14737                    if (!sigsOk) {
14738                        // If the owning package is the system itself, we log but allow
14739                        // install to proceed; we fail the install on all other permission
14740                        // redefinitions.
14741                        if (!bp.sourcePackage.equals("android")) {
14742                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14743                                    + pkg.packageName + " attempting to redeclare permission "
14744                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14745                            res.origPermission = perm.info.name;
14746                            res.origPackage = bp.sourcePackage;
14747                            return;
14748                        } else {
14749                            Slog.w(TAG, "Package " + pkg.packageName
14750                                    + " attempting to redeclare system permission "
14751                                    + perm.info.name + "; ignoring new declaration");
14752                            pkg.permissions.remove(i);
14753                        }
14754                    }
14755                }
14756            }
14757        }
14758
14759        if (systemApp) {
14760            if (onExternal) {
14761                // Abort update; system app can't be replaced with app on sdcard
14762                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14763                        "Cannot install updates to system apps on sdcard");
14764                return;
14765            } else if (ephemeral) {
14766                // Abort update; system app can't be replaced with an ephemeral app
14767                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14768                        "Cannot update a system app with an ephemeral app");
14769                return;
14770            }
14771        }
14772
14773        if (args.move != null) {
14774            // We did an in-place move, so dex is ready to roll
14775            scanFlags |= SCAN_NO_DEX;
14776            scanFlags |= SCAN_MOVE;
14777
14778            synchronized (mPackages) {
14779                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14780                if (ps == null) {
14781                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14782                            "Missing settings for moved package " + pkgName);
14783                }
14784
14785                // We moved the entire application as-is, so bring over the
14786                // previously derived ABI information.
14787                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14788                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14789            }
14790
14791        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14792            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14793            scanFlags |= SCAN_NO_DEX;
14794
14795            try {
14796                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14797                    args.abiOverride : pkg.cpuAbiOverride);
14798                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14799                        true /* extract libs */);
14800            } catch (PackageManagerException pme) {
14801                Slog.e(TAG, "Error deriving application ABI", pme);
14802                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14803                return;
14804            }
14805
14806            // Shared libraries for the package need to be updated.
14807            synchronized (mPackages) {
14808                try {
14809                    updateSharedLibrariesLPw(pkg, null);
14810                } catch (PackageManagerException e) {
14811                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14812                }
14813            }
14814            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14815            // Do not run PackageDexOptimizer through the local performDexOpt
14816            // method because `pkg` is not in `mPackages` yet.
14817            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14818                    null /* instructionSets */, false /* checkProfiles */,
14819                    getCompilerFilterForReason(REASON_INSTALL));
14820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14821            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14822                String msg = "Extracting package failed for " + pkgName;
14823                res.setError(INSTALL_FAILED_DEXOPT, msg);
14824                return;
14825            }
14826
14827            // Notify BackgroundDexOptService that the package has been changed.
14828            // If this is an update of a package which used to fail to compile,
14829            // BDOS will remove it from its blacklist.
14830            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14831        }
14832
14833        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14834            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14835            return;
14836        }
14837
14838        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14839
14840        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14841                "installPackageLI")) {
14842            if (replace) {
14843                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14844                        installerPackageName, res);
14845            } else {
14846                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14847                        args.user, installerPackageName, volumeUuid, res);
14848            }
14849        }
14850        synchronized (mPackages) {
14851            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14852            if (ps != null) {
14853                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14854            }
14855
14856            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14857            for (int i = 0; i < childCount; i++) {
14858                PackageParser.Package childPkg = pkg.childPackages.get(i);
14859                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14860                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14861                if (childPs != null) {
14862                    childRes.newUsers = childPs.queryInstalledUsers(
14863                            sUserManager.getUserIds(), true);
14864                }
14865            }
14866        }
14867    }
14868
14869    private void startIntentFilterVerifications(int userId, boolean replacing,
14870            PackageParser.Package pkg) {
14871        if (mIntentFilterVerifierComponent == null) {
14872            Slog.w(TAG, "No IntentFilter verification will not be done as "
14873                    + "there is no IntentFilterVerifier available!");
14874            return;
14875        }
14876
14877        final int verifierUid = getPackageUid(
14878                mIntentFilterVerifierComponent.getPackageName(),
14879                MATCH_DEBUG_TRIAGED_MISSING,
14880                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14881
14882        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14883        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14884        mHandler.sendMessage(msg);
14885
14886        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14887        for (int i = 0; i < childCount; i++) {
14888            PackageParser.Package childPkg = pkg.childPackages.get(i);
14889            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14890            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14891            mHandler.sendMessage(msg);
14892        }
14893    }
14894
14895    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14896            PackageParser.Package pkg) {
14897        int size = pkg.activities.size();
14898        if (size == 0) {
14899            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14900                    "No activity, so no need to verify any IntentFilter!");
14901            return;
14902        }
14903
14904        final boolean hasDomainURLs = hasDomainURLs(pkg);
14905        if (!hasDomainURLs) {
14906            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14907                    "No domain URLs, so no need to verify any IntentFilter!");
14908            return;
14909        }
14910
14911        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14912                + " if any IntentFilter from the " + size
14913                + " Activities needs verification ...");
14914
14915        int count = 0;
14916        final String packageName = pkg.packageName;
14917
14918        synchronized (mPackages) {
14919            // If this is a new install and we see that we've already run verification for this
14920            // package, we have nothing to do: it means the state was restored from backup.
14921            if (!replacing) {
14922                IntentFilterVerificationInfo ivi =
14923                        mSettings.getIntentFilterVerificationLPr(packageName);
14924                if (ivi != null) {
14925                    if (DEBUG_DOMAIN_VERIFICATION) {
14926                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14927                                + ivi.getStatusString());
14928                    }
14929                    return;
14930                }
14931            }
14932
14933            // If any filters need to be verified, then all need to be.
14934            boolean needToVerify = false;
14935            for (PackageParser.Activity a : pkg.activities) {
14936                for (ActivityIntentInfo filter : a.intents) {
14937                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14938                        if (DEBUG_DOMAIN_VERIFICATION) {
14939                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14940                        }
14941                        needToVerify = true;
14942                        break;
14943                    }
14944                }
14945            }
14946
14947            if (needToVerify) {
14948                final int verificationId = mIntentFilterVerificationToken++;
14949                for (PackageParser.Activity a : pkg.activities) {
14950                    for (ActivityIntentInfo filter : a.intents) {
14951                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14952                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14953                                    "Verification needed for IntentFilter:" + filter.toString());
14954                            mIntentFilterVerifier.addOneIntentFilterVerification(
14955                                    verifierUid, userId, verificationId, filter, packageName);
14956                            count++;
14957                        }
14958                    }
14959                }
14960            }
14961        }
14962
14963        if (count > 0) {
14964            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14965                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14966                    +  " for userId:" + userId);
14967            mIntentFilterVerifier.startVerifications(userId);
14968        } else {
14969            if (DEBUG_DOMAIN_VERIFICATION) {
14970                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14971            }
14972        }
14973    }
14974
14975    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14976        final ComponentName cn  = filter.activity.getComponentName();
14977        final String packageName = cn.getPackageName();
14978
14979        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14980                packageName);
14981        if (ivi == null) {
14982            return true;
14983        }
14984        int status = ivi.getStatus();
14985        switch (status) {
14986            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14987            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14988                return true;
14989
14990            default:
14991                // Nothing to do
14992                return false;
14993        }
14994    }
14995
14996    private static boolean isMultiArch(ApplicationInfo info) {
14997        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14998    }
14999
15000    private static boolean isExternal(PackageParser.Package pkg) {
15001        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15002    }
15003
15004    private static boolean isExternal(PackageSetting ps) {
15005        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15006    }
15007
15008    private static boolean isEphemeral(PackageParser.Package pkg) {
15009        return pkg.applicationInfo.isEphemeralApp();
15010    }
15011
15012    private static boolean isEphemeral(PackageSetting ps) {
15013        return ps.pkg != null && isEphemeral(ps.pkg);
15014    }
15015
15016    private static boolean isSystemApp(PackageParser.Package pkg) {
15017        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15018    }
15019
15020    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15021        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15022    }
15023
15024    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15025        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15026    }
15027
15028    private static boolean isSystemApp(PackageSetting ps) {
15029        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15030    }
15031
15032    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15033        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15034    }
15035
15036    private int packageFlagsToInstallFlags(PackageSetting ps) {
15037        int installFlags = 0;
15038        if (isEphemeral(ps)) {
15039            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15040        }
15041        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15042            // This existing package was an external ASEC install when we have
15043            // the external flag without a UUID
15044            installFlags |= PackageManager.INSTALL_EXTERNAL;
15045        }
15046        if (ps.isForwardLocked()) {
15047            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15048        }
15049        return installFlags;
15050    }
15051
15052    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15053        if (isExternal(pkg)) {
15054            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15055                return StorageManager.UUID_PRIMARY_PHYSICAL;
15056            } else {
15057                return pkg.volumeUuid;
15058            }
15059        } else {
15060            return StorageManager.UUID_PRIVATE_INTERNAL;
15061        }
15062    }
15063
15064    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15065        if (isExternal(pkg)) {
15066            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15067                return mSettings.getExternalVersion();
15068            } else {
15069                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15070            }
15071        } else {
15072            return mSettings.getInternalVersion();
15073        }
15074    }
15075
15076    private void deleteTempPackageFiles() {
15077        final FilenameFilter filter = new FilenameFilter() {
15078            public boolean accept(File dir, String name) {
15079                return name.startsWith("vmdl") && name.endsWith(".tmp");
15080            }
15081        };
15082        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15083            file.delete();
15084        }
15085    }
15086
15087    @Override
15088    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15089            int flags) {
15090        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15091                flags);
15092    }
15093
15094    @Override
15095    public void deletePackage(final String packageName,
15096            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15097        mContext.enforceCallingOrSelfPermission(
15098                android.Manifest.permission.DELETE_PACKAGES, null);
15099        Preconditions.checkNotNull(packageName);
15100        Preconditions.checkNotNull(observer);
15101        final int uid = Binder.getCallingUid();
15102        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15103        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15104        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15105            mContext.enforceCallingOrSelfPermission(
15106                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15107                    "deletePackage for user " + userId);
15108        }
15109
15110        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15111            try {
15112                observer.onPackageDeleted(packageName,
15113                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15114            } catch (RemoteException re) {
15115            }
15116            return;
15117        }
15118
15119        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15120            try {
15121                observer.onPackageDeleted(packageName,
15122                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15123            } catch (RemoteException re) {
15124            }
15125            return;
15126        }
15127
15128        if (DEBUG_REMOVE) {
15129            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15130                    + " deleteAllUsers: " + deleteAllUsers );
15131        }
15132        // Queue up an async operation since the package deletion may take a little while.
15133        mHandler.post(new Runnable() {
15134            public void run() {
15135                mHandler.removeCallbacks(this);
15136                int returnCode;
15137                if (!deleteAllUsers) {
15138                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15139                } else {
15140                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15141                    // If nobody is blocking uninstall, proceed with delete for all users
15142                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15143                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15144                    } else {
15145                        // Otherwise uninstall individually for users with blockUninstalls=false
15146                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15147                        for (int userId : users) {
15148                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15149                                returnCode = deletePackageX(packageName, userId, userFlags);
15150                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15151                                    Slog.w(TAG, "Package delete failed for user " + userId
15152                                            + ", returnCode " + returnCode);
15153                                }
15154                            }
15155                        }
15156                        // The app has only been marked uninstalled for certain users.
15157                        // We still need to report that delete was blocked
15158                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15159                    }
15160                }
15161                try {
15162                    observer.onPackageDeleted(packageName, returnCode, null);
15163                } catch (RemoteException e) {
15164                    Log.i(TAG, "Observer no longer exists.");
15165                } //end catch
15166            } //end run
15167        });
15168    }
15169
15170    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15171        int[] result = EMPTY_INT_ARRAY;
15172        for (int userId : userIds) {
15173            if (getBlockUninstallForUser(packageName, userId)) {
15174                result = ArrayUtils.appendInt(result, userId);
15175            }
15176        }
15177        return result;
15178    }
15179
15180    @Override
15181    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15182        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15183    }
15184
15185    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15186        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15187                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15188        try {
15189            if (dpm != null) {
15190                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15191                        /* callingUserOnly =*/ false);
15192                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15193                        : deviceOwnerComponentName.getPackageName();
15194                // Does the package contains the device owner?
15195                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15196                // this check is probably not needed, since DO should be registered as a device
15197                // admin on some user too. (Original bug for this: b/17657954)
15198                if (packageName.equals(deviceOwnerPackageName)) {
15199                    return true;
15200                }
15201                // Does it contain a device admin for any user?
15202                int[] users;
15203                if (userId == UserHandle.USER_ALL) {
15204                    users = sUserManager.getUserIds();
15205                } else {
15206                    users = new int[]{userId};
15207                }
15208                for (int i = 0; i < users.length; ++i) {
15209                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15210                        return true;
15211                    }
15212                }
15213            }
15214        } catch (RemoteException e) {
15215        }
15216        return false;
15217    }
15218
15219    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15220        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15221    }
15222
15223    /**
15224     *  This method is an internal method that could be get invoked either
15225     *  to delete an installed package or to clean up a failed installation.
15226     *  After deleting an installed package, a broadcast is sent to notify any
15227     *  listeners that the package has been removed. For cleaning up a failed
15228     *  installation, the broadcast is not necessary since the package's
15229     *  installation wouldn't have sent the initial broadcast either
15230     *  The key steps in deleting a package are
15231     *  deleting the package information in internal structures like mPackages,
15232     *  deleting the packages base directories through installd
15233     *  updating mSettings to reflect current status
15234     *  persisting settings for later use
15235     *  sending a broadcast if necessary
15236     */
15237    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15238        final PackageRemovedInfo info = new PackageRemovedInfo();
15239        final boolean res;
15240
15241        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15242                ? UserHandle.ALL : new UserHandle(userId);
15243
15244        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15245            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15246            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15247        }
15248
15249        PackageSetting uninstalledPs = null;
15250
15251        // for the uninstall-updates case and restricted profiles, remember the per-
15252        // user handle installed state
15253        int[] allUsers;
15254        synchronized (mPackages) {
15255            uninstalledPs = mSettings.mPackages.get(packageName);
15256            if (uninstalledPs == null) {
15257                Slog.w(TAG, "Not removing non-existent package " + packageName);
15258                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15259            }
15260            allUsers = sUserManager.getUserIds();
15261            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15262        }
15263
15264        synchronized (mInstallLock) {
15265            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15266            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15267                    "deletePackageX")) {
15268                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15269                        deleteFlags | REMOVE_CHATTY, info, true, null);
15270            }
15271            synchronized (mPackages) {
15272                if (res) {
15273                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15274                }
15275            }
15276        }
15277
15278        if (res) {
15279            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15280            info.sendPackageRemovedBroadcasts(killApp);
15281            info.sendSystemPackageUpdatedBroadcasts();
15282            info.sendSystemPackageAppearedBroadcasts();
15283        }
15284        // Force a gc here.
15285        Runtime.getRuntime().gc();
15286        // Delete the resources here after sending the broadcast to let
15287        // other processes clean up before deleting resources.
15288        if (info.args != null) {
15289            synchronized (mInstallLock) {
15290                info.args.doPostDeleteLI(true);
15291            }
15292        }
15293
15294        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15295    }
15296
15297    class PackageRemovedInfo {
15298        String removedPackage;
15299        int uid = -1;
15300        int removedAppId = -1;
15301        int[] origUsers;
15302        int[] removedUsers = null;
15303        boolean isRemovedPackageSystemUpdate = false;
15304        boolean isUpdate;
15305        boolean dataRemoved;
15306        boolean removedForAllUsers;
15307        // Clean up resources deleted packages.
15308        InstallArgs args = null;
15309        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15310        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15311
15312        void sendPackageRemovedBroadcasts(boolean killApp) {
15313            sendPackageRemovedBroadcastInternal(killApp);
15314            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15315            for (int i = 0; i < childCount; i++) {
15316                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15317                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15318            }
15319        }
15320
15321        void sendSystemPackageUpdatedBroadcasts() {
15322            if (isRemovedPackageSystemUpdate) {
15323                sendSystemPackageUpdatedBroadcastsInternal();
15324                final int childCount = (removedChildPackages != null)
15325                        ? removedChildPackages.size() : 0;
15326                for (int i = 0; i < childCount; i++) {
15327                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15328                    if (childInfo.isRemovedPackageSystemUpdate) {
15329                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15330                    }
15331                }
15332            }
15333        }
15334
15335        void sendSystemPackageAppearedBroadcasts() {
15336            final int packageCount = (appearedChildPackages != null)
15337                    ? appearedChildPackages.size() : 0;
15338            for (int i = 0; i < packageCount; i++) {
15339                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15340                for (int userId : installedInfo.newUsers) {
15341                    sendPackageAddedForUser(installedInfo.name, true,
15342                            UserHandle.getAppId(installedInfo.uid), userId);
15343                }
15344            }
15345        }
15346
15347        private void sendSystemPackageUpdatedBroadcastsInternal() {
15348            Bundle extras = new Bundle(2);
15349            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15350            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15351            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15352                    extras, 0, null, null, null);
15353            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15354                    extras, 0, null, null, null);
15355            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15356                    null, 0, removedPackage, null, null);
15357        }
15358
15359        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15360            Bundle extras = new Bundle(2);
15361            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15362            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15363            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15364            if (isUpdate || isRemovedPackageSystemUpdate) {
15365                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15366            }
15367            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15368            if (removedPackage != null) {
15369                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15370                        extras, 0, null, null, removedUsers);
15371                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15372                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15373                            removedPackage, extras, 0, null, null, removedUsers);
15374                }
15375            }
15376            if (removedAppId >= 0) {
15377                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15378                        removedUsers);
15379            }
15380        }
15381    }
15382
15383    /*
15384     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15385     * flag is not set, the data directory is removed as well.
15386     * make sure this flag is set for partially installed apps. If not its meaningless to
15387     * delete a partially installed application.
15388     */
15389    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15390            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15391        String packageName = ps.name;
15392        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15393        // Retrieve object to delete permissions for shared user later on
15394        final PackageParser.Package deletedPkg;
15395        final PackageSetting deletedPs;
15396        // reader
15397        synchronized (mPackages) {
15398            deletedPkg = mPackages.get(packageName);
15399            deletedPs = mSettings.mPackages.get(packageName);
15400            if (outInfo != null) {
15401                outInfo.removedPackage = packageName;
15402                outInfo.removedUsers = deletedPs != null
15403                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15404                        : null;
15405            }
15406        }
15407
15408        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15409
15410        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15411            destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL,
15412                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15413            destroyAppProfilesLIF(deletedPkg);
15414            if (outInfo != null) {
15415                outInfo.dataRemoved = true;
15416            }
15417            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15418        }
15419
15420        // writer
15421        synchronized (mPackages) {
15422            if (deletedPs != null) {
15423                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15424                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15425                    clearDefaultBrowserIfNeeded(packageName);
15426                    if (outInfo != null) {
15427                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15428                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15429                    }
15430                    updatePermissionsLPw(deletedPs.name, null, 0);
15431                    if (deletedPs.sharedUser != null) {
15432                        // Remove permissions associated with package. Since runtime
15433                        // permissions are per user we have to kill the removed package
15434                        // or packages running under the shared user of the removed
15435                        // package if revoking the permissions requested only by the removed
15436                        // package is successful and this causes a change in gids.
15437                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15438                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15439                                    userId);
15440                            if (userIdToKill == UserHandle.USER_ALL
15441                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15442                                // If gids changed for this user, kill all affected packages.
15443                                mHandler.post(new Runnable() {
15444                                    @Override
15445                                    public void run() {
15446                                        // This has to happen with no lock held.
15447                                        killApplication(deletedPs.name, deletedPs.appId,
15448                                                KILL_APP_REASON_GIDS_CHANGED);
15449                                    }
15450                                });
15451                                break;
15452                            }
15453                        }
15454                    }
15455                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15456                }
15457                // make sure to preserve per-user disabled state if this removal was just
15458                // a downgrade of a system app to the factory package
15459                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15460                    if (DEBUG_REMOVE) {
15461                        Slog.d(TAG, "Propagating install state across downgrade");
15462                    }
15463                    for (int userId : allUserHandles) {
15464                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15465                        if (DEBUG_REMOVE) {
15466                            Slog.d(TAG, "    user " + userId + " => " + installed);
15467                        }
15468                        ps.setInstalled(installed, userId);
15469                    }
15470                }
15471            }
15472            // can downgrade to reader
15473            if (writeSettings) {
15474                // Save settings now
15475                mSettings.writeLPr();
15476            }
15477        }
15478        if (outInfo != null) {
15479            // A user ID was deleted here. Go through all users and remove it
15480            // from KeyStore.
15481            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15482        }
15483    }
15484
15485    static boolean locationIsPrivileged(File path) {
15486        try {
15487            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15488                    .getCanonicalPath();
15489            return path.getCanonicalPath().startsWith(privilegedAppDir);
15490        } catch (IOException e) {
15491            Slog.e(TAG, "Unable to access code path " + path);
15492        }
15493        return false;
15494    }
15495
15496    /*
15497     * Tries to delete system package.
15498     */
15499    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15500            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15501            boolean writeSettings) {
15502        if (deletedPs.parentPackageName != null) {
15503            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15504            return false;
15505        }
15506
15507        final boolean applyUserRestrictions
15508                = (allUserHandles != null) && (outInfo.origUsers != null);
15509        final PackageSetting disabledPs;
15510        // Confirm if the system package has been updated
15511        // An updated system app can be deleted. This will also have to restore
15512        // the system pkg from system partition
15513        // reader
15514        synchronized (mPackages) {
15515            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15516        }
15517
15518        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15519                + " disabledPs=" + disabledPs);
15520
15521        if (disabledPs == null) {
15522            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15523            return false;
15524        } else if (DEBUG_REMOVE) {
15525            Slog.d(TAG, "Deleting system pkg from data partition");
15526        }
15527
15528        if (DEBUG_REMOVE) {
15529            if (applyUserRestrictions) {
15530                Slog.d(TAG, "Remembering install states:");
15531                for (int userId : allUserHandles) {
15532                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15533                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15534                }
15535            }
15536        }
15537
15538        // Delete the updated package
15539        outInfo.isRemovedPackageSystemUpdate = true;
15540        if (outInfo.removedChildPackages != null) {
15541            final int childCount = (deletedPs.childPackageNames != null)
15542                    ? deletedPs.childPackageNames.size() : 0;
15543            for (int i = 0; i < childCount; i++) {
15544                String childPackageName = deletedPs.childPackageNames.get(i);
15545                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15546                        .contains(childPackageName)) {
15547                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15548                            childPackageName);
15549                    if (childInfo != null) {
15550                        childInfo.isRemovedPackageSystemUpdate = true;
15551                    }
15552                }
15553            }
15554        }
15555
15556        if (disabledPs.versionCode < deletedPs.versionCode) {
15557            // Delete data for downgrades
15558            flags &= ~PackageManager.DELETE_KEEP_DATA;
15559        } else {
15560            // Preserve data by setting flag
15561            flags |= PackageManager.DELETE_KEEP_DATA;
15562        }
15563
15564        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15565                outInfo, writeSettings, disabledPs.pkg);
15566        if (!ret) {
15567            return false;
15568        }
15569
15570        // writer
15571        synchronized (mPackages) {
15572            // Reinstate the old system package
15573            enableSystemPackageLPw(disabledPs.pkg);
15574            // Remove any native libraries from the upgraded package.
15575            removeNativeBinariesLI(deletedPs);
15576        }
15577
15578        // Install the system package
15579        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15580        int parseFlags = mDefParseFlags
15581                | PackageParser.PARSE_MUST_BE_APK
15582                | PackageParser.PARSE_IS_SYSTEM
15583                | PackageParser.PARSE_IS_SYSTEM_DIR;
15584        if (locationIsPrivileged(disabledPs.codePath)) {
15585            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15586        }
15587
15588        final PackageParser.Package newPkg;
15589        try {
15590            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15591        } catch (PackageManagerException e) {
15592            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15593                    + e.getMessage());
15594            return false;
15595        }
15596
15597        prepareAppDataAfterInstallLIF(newPkg);
15598
15599        // writer
15600        synchronized (mPackages) {
15601            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15602
15603            // Propagate the permissions state as we do not want to drop on the floor
15604            // runtime permissions. The update permissions method below will take
15605            // care of removing obsolete permissions and grant install permissions.
15606            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15607            updatePermissionsLPw(newPkg.packageName, newPkg,
15608                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15609
15610            if (applyUserRestrictions) {
15611                if (DEBUG_REMOVE) {
15612                    Slog.d(TAG, "Propagating install state across reinstall");
15613                }
15614                for (int userId : allUserHandles) {
15615                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15616                    if (DEBUG_REMOVE) {
15617                        Slog.d(TAG, "    user " + userId + " => " + installed);
15618                    }
15619                    ps.setInstalled(installed, userId);
15620
15621                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15622                }
15623                // Regardless of writeSettings we need to ensure that this restriction
15624                // state propagation is persisted
15625                mSettings.writeAllUsersPackageRestrictionsLPr();
15626            }
15627            // can downgrade to reader here
15628            if (writeSettings) {
15629                mSettings.writeLPr();
15630            }
15631        }
15632        return true;
15633    }
15634
15635    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15636            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15637            PackageRemovedInfo outInfo, boolean writeSettings,
15638            PackageParser.Package replacingPackage) {
15639        synchronized (mPackages) {
15640            if (outInfo != null) {
15641                outInfo.uid = ps.appId;
15642            }
15643
15644            if (outInfo != null && outInfo.removedChildPackages != null) {
15645                final int childCount = (ps.childPackageNames != null)
15646                        ? ps.childPackageNames.size() : 0;
15647                for (int i = 0; i < childCount; i++) {
15648                    String childPackageName = ps.childPackageNames.get(i);
15649                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15650                    if (childPs == null) {
15651                        return false;
15652                    }
15653                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15654                            childPackageName);
15655                    if (childInfo != null) {
15656                        childInfo.uid = childPs.appId;
15657                    }
15658                }
15659            }
15660        }
15661
15662        // Delete package data from internal structures and also remove data if flag is set
15663        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15664
15665        // Delete the child packages data
15666        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15667        for (int i = 0; i < childCount; i++) {
15668            PackageSetting childPs;
15669            synchronized (mPackages) {
15670                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15671            }
15672            if (childPs != null) {
15673                PackageRemovedInfo childOutInfo = (outInfo != null
15674                        && outInfo.removedChildPackages != null)
15675                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15676                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15677                        && (replacingPackage != null
15678                        && !replacingPackage.hasChildPackage(childPs.name))
15679                        ? flags & ~DELETE_KEEP_DATA : flags;
15680                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15681                        deleteFlags, writeSettings);
15682            }
15683        }
15684
15685        // Delete application code and resources only for parent packages
15686        if (ps.parentPackageName == null) {
15687            if (deleteCodeAndResources && (outInfo != null)) {
15688                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15689                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15690                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15691            }
15692        }
15693
15694        return true;
15695    }
15696
15697    @Override
15698    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15699            int userId) {
15700        mContext.enforceCallingOrSelfPermission(
15701                android.Manifest.permission.DELETE_PACKAGES, null);
15702        synchronized (mPackages) {
15703            PackageSetting ps = mSettings.mPackages.get(packageName);
15704            if (ps == null) {
15705                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15706                return false;
15707            }
15708            if (!ps.getInstalled(userId)) {
15709                // Can't block uninstall for an app that is not installed or enabled.
15710                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15711                return false;
15712            }
15713            ps.setBlockUninstall(blockUninstall, userId);
15714            mSettings.writePackageRestrictionsLPr(userId);
15715        }
15716        return true;
15717    }
15718
15719    @Override
15720    public boolean getBlockUninstallForUser(String packageName, int userId) {
15721        synchronized (mPackages) {
15722            PackageSetting ps = mSettings.mPackages.get(packageName);
15723            if (ps == null) {
15724                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15725                return false;
15726            }
15727            return ps.getBlockUninstall(userId);
15728        }
15729    }
15730
15731    @Override
15732    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15733        int callingUid = Binder.getCallingUid();
15734        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15735            throw new SecurityException(
15736                    "setRequiredForSystemUser can only be run by the system or root");
15737        }
15738        synchronized (mPackages) {
15739            PackageSetting ps = mSettings.mPackages.get(packageName);
15740            if (ps == null) {
15741                Log.w(TAG, "Package doesn't exist: " + packageName);
15742                return false;
15743            }
15744            if (systemUserApp) {
15745                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15746            } else {
15747                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15748            }
15749            mSettings.writeLPr();
15750        }
15751        return true;
15752    }
15753
15754    /*
15755     * This method handles package deletion in general
15756     */
15757    private boolean deletePackageLIF(String packageName, UserHandle user,
15758            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15759            PackageRemovedInfo outInfo, boolean writeSettings,
15760            PackageParser.Package replacingPackage) {
15761        if (packageName == null) {
15762            Slog.w(TAG, "Attempt to delete null packageName.");
15763            return false;
15764        }
15765
15766        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15767
15768        PackageSetting ps;
15769
15770        synchronized (mPackages) {
15771            ps = mSettings.mPackages.get(packageName);
15772            if (ps == null) {
15773                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15774                return false;
15775            }
15776
15777            if (ps.parentPackageName != null && (!isSystemApp(ps)
15778                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15779                if (DEBUG_REMOVE) {
15780                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15781                            + ((user == null) ? UserHandle.USER_ALL : user));
15782                }
15783                final int removedUserId = (user != null) ? user.getIdentifier()
15784                        : UserHandle.USER_ALL;
15785                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15786                    return false;
15787                }
15788                markPackageUninstalledForUserLPw(ps, user);
15789                scheduleWritePackageRestrictionsLocked(user);
15790                return true;
15791            }
15792        }
15793
15794        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15795                && user.getIdentifier() != UserHandle.USER_ALL)) {
15796            // The caller is asking that the package only be deleted for a single
15797            // user.  To do this, we just mark its uninstalled state and delete
15798            // its data. If this is a system app, we only allow this to happen if
15799            // they have set the special DELETE_SYSTEM_APP which requests different
15800            // semantics than normal for uninstalling system apps.
15801            markPackageUninstalledForUserLPw(ps, user);
15802
15803            if (!isSystemApp(ps)) {
15804                // Do not uninstall the APK if an app should be cached
15805                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15806                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15807                    // Other user still have this package installed, so all
15808                    // we need to do is clear this user's data and save that
15809                    // it is uninstalled.
15810                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15811                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15812                        return false;
15813                    }
15814                    scheduleWritePackageRestrictionsLocked(user);
15815                    return true;
15816                } else {
15817                    // We need to set it back to 'installed' so the uninstall
15818                    // broadcasts will be sent correctly.
15819                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15820                    ps.setInstalled(true, user.getIdentifier());
15821                }
15822            } else {
15823                // This is a system app, so we assume that the
15824                // other users still have this package installed, so all
15825                // we need to do is clear this user's data and save that
15826                // it is uninstalled.
15827                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15828                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15829                    return false;
15830                }
15831                scheduleWritePackageRestrictionsLocked(user);
15832                return true;
15833            }
15834        }
15835
15836        // If we are deleting a composite package for all users, keep track
15837        // of result for each child.
15838        if (ps.childPackageNames != null && outInfo != null) {
15839            synchronized (mPackages) {
15840                final int childCount = ps.childPackageNames.size();
15841                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15842                for (int i = 0; i < childCount; i++) {
15843                    String childPackageName = ps.childPackageNames.get(i);
15844                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15845                    childInfo.removedPackage = childPackageName;
15846                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15847                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15848                    if (childPs != null) {
15849                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15850                    }
15851                }
15852            }
15853        }
15854
15855        boolean ret = false;
15856        if (isSystemApp(ps)) {
15857            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15858            // When an updated system application is deleted we delete the existing resources
15859            // as well and fall back to existing code in system partition
15860            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15861        } else {
15862            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15863            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15864                    outInfo, writeSettings, replacingPackage);
15865        }
15866
15867        // Take a note whether we deleted the package for all users
15868        if (outInfo != null) {
15869            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15870            if (outInfo.removedChildPackages != null) {
15871                synchronized (mPackages) {
15872                    final int childCount = outInfo.removedChildPackages.size();
15873                    for (int i = 0; i < childCount; i++) {
15874                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15875                        if (childInfo != null) {
15876                            childInfo.removedForAllUsers = mPackages.get(
15877                                    childInfo.removedPackage) == null;
15878                        }
15879                    }
15880                }
15881            }
15882            // If we uninstalled an update to a system app there may be some
15883            // child packages that appeared as they are declared in the system
15884            // app but were not declared in the update.
15885            if (isSystemApp(ps)) {
15886                synchronized (mPackages) {
15887                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15888                    final int childCount = (updatedPs.childPackageNames != null)
15889                            ? updatedPs.childPackageNames.size() : 0;
15890                    for (int i = 0; i < childCount; i++) {
15891                        String childPackageName = updatedPs.childPackageNames.get(i);
15892                        if (outInfo.removedChildPackages == null
15893                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15894                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15895                            if (childPs == null) {
15896                                continue;
15897                            }
15898                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15899                            installRes.name = childPackageName;
15900                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15901                            installRes.pkg = mPackages.get(childPackageName);
15902                            installRes.uid = childPs.pkg.applicationInfo.uid;
15903                            if (outInfo.appearedChildPackages == null) {
15904                                outInfo.appearedChildPackages = new ArrayMap<>();
15905                            }
15906                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15907                        }
15908                    }
15909                }
15910            }
15911        }
15912
15913        return ret;
15914    }
15915
15916    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15917        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15918                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15919        for (int nextUserId : userIds) {
15920            if (DEBUG_REMOVE) {
15921                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15922            }
15923            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15924                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15925                    false /*hidden*/, false /*suspended*/, null, null, null,
15926                    false /*blockUninstall*/,
15927                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15928        }
15929    }
15930
15931    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15932            PackageRemovedInfo outInfo) {
15933        final PackageParser.Package pkg;
15934        synchronized (mPackages) {
15935            pkg = mPackages.get(ps.name);
15936        }
15937
15938        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15939                : new int[] {userId};
15940        for (int nextUserId : userIds) {
15941            if (DEBUG_REMOVE) {
15942                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15943                        + nextUserId);
15944            }
15945
15946            destroyAppDataLIF(pkg, userId,
15947                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15948            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15949            schedulePackageCleaning(ps.name, nextUserId, false);
15950            synchronized (mPackages) {
15951                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15952                    scheduleWritePackageRestrictionsLocked(nextUserId);
15953                }
15954                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15955            }
15956        }
15957
15958        if (outInfo != null) {
15959            outInfo.removedPackage = ps.name;
15960            outInfo.removedAppId = ps.appId;
15961            outInfo.removedUsers = userIds;
15962        }
15963
15964        return true;
15965    }
15966
15967    private final class ClearStorageConnection implements ServiceConnection {
15968        IMediaContainerService mContainerService;
15969
15970        @Override
15971        public void onServiceConnected(ComponentName name, IBinder service) {
15972            synchronized (this) {
15973                mContainerService = IMediaContainerService.Stub.asInterface(service);
15974                notifyAll();
15975            }
15976        }
15977
15978        @Override
15979        public void onServiceDisconnected(ComponentName name) {
15980        }
15981    }
15982
15983    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15984        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
15985
15986        final boolean mounted;
15987        if (Environment.isExternalStorageEmulated()) {
15988            mounted = true;
15989        } else {
15990            final String status = Environment.getExternalStorageState();
15991
15992            mounted = status.equals(Environment.MEDIA_MOUNTED)
15993                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15994        }
15995
15996        if (!mounted) {
15997            return;
15998        }
15999
16000        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16001        int[] users;
16002        if (userId == UserHandle.USER_ALL) {
16003            users = sUserManager.getUserIds();
16004        } else {
16005            users = new int[] { userId };
16006        }
16007        final ClearStorageConnection conn = new ClearStorageConnection();
16008        if (mContext.bindServiceAsUser(
16009                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16010            try {
16011                for (int curUser : users) {
16012                    long timeout = SystemClock.uptimeMillis() + 5000;
16013                    synchronized (conn) {
16014                        long now = SystemClock.uptimeMillis();
16015                        while (conn.mContainerService == null && now < timeout) {
16016                            try {
16017                                conn.wait(timeout - now);
16018                            } catch (InterruptedException e) {
16019                            }
16020                        }
16021                    }
16022                    if (conn.mContainerService == null) {
16023                        return;
16024                    }
16025
16026                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16027                    clearDirectory(conn.mContainerService,
16028                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16029                    if (allData) {
16030                        clearDirectory(conn.mContainerService,
16031                                userEnv.buildExternalStorageAppDataDirs(packageName));
16032                        clearDirectory(conn.mContainerService,
16033                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16034                    }
16035                }
16036            } finally {
16037                mContext.unbindService(conn);
16038            }
16039        }
16040    }
16041
16042    @Override
16043    public void clearApplicationProfileData(String packageName) {
16044        enforceSystemOrRoot("Only the system can clear all profile data");
16045
16046        final PackageParser.Package pkg;
16047        synchronized (mPackages) {
16048            pkg = mPackages.get(packageName);
16049        }
16050
16051        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16052            synchronized (mInstallLock) {
16053                clearAppProfilesLIF(pkg);
16054            }
16055        }
16056    }
16057
16058    @Override
16059    public void clearApplicationUserData(final String packageName,
16060            final IPackageDataObserver observer, final int userId) {
16061        mContext.enforceCallingOrSelfPermission(
16062                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16063
16064        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16065                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16066
16067        final DevicePolicyManagerInternal dpmi = LocalServices
16068                .getService(DevicePolicyManagerInternal.class);
16069        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16070            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16071        }
16072        // Queue up an async operation since the package deletion may take a little while.
16073        mHandler.post(new Runnable() {
16074            public void run() {
16075                mHandler.removeCallbacks(this);
16076                final boolean succeeded;
16077                try (PackageFreezer freezer = freezePackage(packageName,
16078                        "clearApplicationUserData")) {
16079                    synchronized (mInstallLock) {
16080                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16081                    }
16082                    clearExternalStorageDataSync(packageName, userId, true);
16083                }
16084                if (succeeded) {
16085                    // invoke DeviceStorageMonitor's update method to clear any notifications
16086                    DeviceStorageMonitorInternal dsm = LocalServices
16087                            .getService(DeviceStorageMonitorInternal.class);
16088                    if (dsm != null) {
16089                        dsm.checkMemory();
16090                    }
16091                }
16092                if(observer != null) {
16093                    try {
16094                        observer.onRemoveCompleted(packageName, succeeded);
16095                    } catch (RemoteException e) {
16096                        Log.i(TAG, "Observer no longer exists.");
16097                    }
16098                } //end if observer
16099            } //end run
16100        });
16101    }
16102
16103    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16104        if (packageName == null) {
16105            Slog.w(TAG, "Attempt to delete null packageName.");
16106            return false;
16107        }
16108
16109        // Try finding details about the requested package
16110        PackageParser.Package pkg;
16111        synchronized (mPackages) {
16112            pkg = mPackages.get(packageName);
16113            if (pkg == null) {
16114                final PackageSetting ps = mSettings.mPackages.get(packageName);
16115                if (ps != null) {
16116                    pkg = ps.pkg;
16117                }
16118            }
16119
16120            if (pkg == null) {
16121                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16122                return false;
16123            }
16124
16125            PackageSetting ps = (PackageSetting) pkg.mExtras;
16126            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16127        }
16128
16129        clearAppDataLIF(pkg, userId,
16130                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16131
16132        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16133        removeKeystoreDataIfNeeded(userId, appId);
16134
16135        final UserManager um = mContext.getSystemService(UserManager.class);
16136        final int flags;
16137        if (um.isUserUnlockingOrUnlocked(userId)) {
16138            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16139        } else if (um.isUserRunning(userId)) {
16140            flags = StorageManager.FLAG_STORAGE_DE;
16141        } else {
16142            flags = 0;
16143        }
16144        prepareAppDataContentsLIF(pkg, userId, flags);
16145
16146        return true;
16147    }
16148
16149    /**
16150     * Reverts user permission state changes (permissions and flags) in
16151     * all packages for a given user.
16152     *
16153     * @param userId The device user for which to do a reset.
16154     */
16155    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16156        final int packageCount = mPackages.size();
16157        for (int i = 0; i < packageCount; i++) {
16158            PackageParser.Package pkg = mPackages.valueAt(i);
16159            PackageSetting ps = (PackageSetting) pkg.mExtras;
16160            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16161        }
16162    }
16163
16164    private void resetNetworkPolicies(int userId) {
16165        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16166    }
16167
16168    /**
16169     * Reverts user permission state changes (permissions and flags).
16170     *
16171     * @param ps The package for which to reset.
16172     * @param userId The device user for which to do a reset.
16173     */
16174    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16175            final PackageSetting ps, final int userId) {
16176        if (ps.pkg == null) {
16177            return;
16178        }
16179
16180        // These are flags that can change base on user actions.
16181        final int userSettableMask = FLAG_PERMISSION_USER_SET
16182                | FLAG_PERMISSION_USER_FIXED
16183                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16184                | FLAG_PERMISSION_REVIEW_REQUIRED;
16185
16186        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16187                | FLAG_PERMISSION_POLICY_FIXED;
16188
16189        boolean writeInstallPermissions = false;
16190        boolean writeRuntimePermissions = false;
16191
16192        final int permissionCount = ps.pkg.requestedPermissions.size();
16193        for (int i = 0; i < permissionCount; i++) {
16194            String permission = ps.pkg.requestedPermissions.get(i);
16195
16196            BasePermission bp = mSettings.mPermissions.get(permission);
16197            if (bp == null) {
16198                continue;
16199            }
16200
16201            // If shared user we just reset the state to which only this app contributed.
16202            if (ps.sharedUser != null) {
16203                boolean used = false;
16204                final int packageCount = ps.sharedUser.packages.size();
16205                for (int j = 0; j < packageCount; j++) {
16206                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16207                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16208                            && pkg.pkg.requestedPermissions.contains(permission)) {
16209                        used = true;
16210                        break;
16211                    }
16212                }
16213                if (used) {
16214                    continue;
16215                }
16216            }
16217
16218            PermissionsState permissionsState = ps.getPermissionsState();
16219
16220            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16221
16222            // Always clear the user settable flags.
16223            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16224                    bp.name) != null;
16225            // If permission review is enabled and this is a legacy app, mark the
16226            // permission as requiring a review as this is the initial state.
16227            int flags = 0;
16228            if (Build.PERMISSIONS_REVIEW_REQUIRED
16229                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16230                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16231            }
16232            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16233                if (hasInstallState) {
16234                    writeInstallPermissions = true;
16235                } else {
16236                    writeRuntimePermissions = true;
16237                }
16238            }
16239
16240            // Below is only runtime permission handling.
16241            if (!bp.isRuntime()) {
16242                continue;
16243            }
16244
16245            // Never clobber system or policy.
16246            if ((oldFlags & policyOrSystemFlags) != 0) {
16247                continue;
16248            }
16249
16250            // If this permission was granted by default, make sure it is.
16251            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16252                if (permissionsState.grantRuntimePermission(bp, userId)
16253                        != PERMISSION_OPERATION_FAILURE) {
16254                    writeRuntimePermissions = true;
16255                }
16256            // If permission review is enabled the permissions for a legacy apps
16257            // are represented as constantly granted runtime ones, so don't revoke.
16258            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16259                // Otherwise, reset the permission.
16260                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16261                switch (revokeResult) {
16262                    case PERMISSION_OPERATION_SUCCESS:
16263                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16264                        writeRuntimePermissions = true;
16265                        final int appId = ps.appId;
16266                        mHandler.post(new Runnable() {
16267                            @Override
16268                            public void run() {
16269                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16270                            }
16271                        });
16272                    } break;
16273                }
16274            }
16275        }
16276
16277        // Synchronously write as we are taking permissions away.
16278        if (writeRuntimePermissions) {
16279            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16280        }
16281
16282        // Synchronously write as we are taking permissions away.
16283        if (writeInstallPermissions) {
16284            mSettings.writeLPr();
16285        }
16286    }
16287
16288    /**
16289     * Remove entries from the keystore daemon. Will only remove it if the
16290     * {@code appId} is valid.
16291     */
16292    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16293        if (appId < 0) {
16294            return;
16295        }
16296
16297        final KeyStore keyStore = KeyStore.getInstance();
16298        if (keyStore != null) {
16299            if (userId == UserHandle.USER_ALL) {
16300                for (final int individual : sUserManager.getUserIds()) {
16301                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16302                }
16303            } else {
16304                keyStore.clearUid(UserHandle.getUid(userId, appId));
16305            }
16306        } else {
16307            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16308        }
16309    }
16310
16311    @Override
16312    public void deleteApplicationCacheFiles(final String packageName,
16313            final IPackageDataObserver observer) {
16314        final int userId = UserHandle.getCallingUserId();
16315        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16316    }
16317
16318    @Override
16319    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16320            final IPackageDataObserver observer) {
16321        mContext.enforceCallingOrSelfPermission(
16322                android.Manifest.permission.DELETE_CACHE_FILES, null);
16323        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16324                /* requireFullPermission= */ true, /* checkShell= */ false,
16325                "delete application cache files");
16326
16327        final PackageParser.Package pkg;
16328        synchronized (mPackages) {
16329            pkg = mPackages.get(packageName);
16330        }
16331
16332        // Queue up an async operation since the package deletion may take a little while.
16333        mHandler.post(new Runnable() {
16334            public void run() {
16335                synchronized (mInstallLock) {
16336                    final int flags = StorageManager.FLAG_STORAGE_DE
16337                            | StorageManager.FLAG_STORAGE_CE;
16338                    // We're only clearing cache files, so we don't care if the
16339                    // app is unfrozen and still able to run
16340                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16341                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16342                }
16343                clearExternalStorageDataSync(packageName, userId, false);
16344                if (observer != null) {
16345                    try {
16346                        observer.onRemoveCompleted(packageName, true);
16347                    } catch (RemoteException e) {
16348                        Log.i(TAG, "Observer no longer exists.");
16349                    }
16350                }
16351            }
16352        });
16353    }
16354
16355    @Override
16356    public void getPackageSizeInfo(final String packageName, int userHandle,
16357            final IPackageStatsObserver observer) {
16358        mContext.enforceCallingOrSelfPermission(
16359                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16360        if (packageName == null) {
16361            throw new IllegalArgumentException("Attempt to get size of null packageName");
16362        }
16363
16364        PackageStats stats = new PackageStats(packageName, userHandle);
16365
16366        /*
16367         * Queue up an async operation since the package measurement may take a
16368         * little while.
16369         */
16370        Message msg = mHandler.obtainMessage(INIT_COPY);
16371        msg.obj = new MeasureParams(stats, observer);
16372        mHandler.sendMessage(msg);
16373    }
16374
16375    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16376        final PackageSetting ps;
16377        synchronized (mPackages) {
16378            ps = mSettings.mPackages.get(packageName);
16379            if (ps == null) {
16380                Slog.w(TAG, "Failed to find settings for " + packageName);
16381                return false;
16382            }
16383        }
16384        try {
16385            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16386                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16387                    ps.getCeDataInode(userId), ps.codePathString, stats);
16388        } catch (InstallerException e) {
16389            Slog.w(TAG, String.valueOf(e));
16390            return false;
16391        }
16392
16393        // For now, ignore code size of packages on system partition
16394        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16395            stats.codeSize = 0;
16396        }
16397
16398        return true;
16399    }
16400
16401    private int getUidTargetSdkVersionLockedLPr(int uid) {
16402        Object obj = mSettings.getUserIdLPr(uid);
16403        if (obj instanceof SharedUserSetting) {
16404            final SharedUserSetting sus = (SharedUserSetting) obj;
16405            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16406            final Iterator<PackageSetting> it = sus.packages.iterator();
16407            while (it.hasNext()) {
16408                final PackageSetting ps = it.next();
16409                if (ps.pkg != null) {
16410                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16411                    if (v < vers) vers = v;
16412                }
16413            }
16414            return vers;
16415        } else if (obj instanceof PackageSetting) {
16416            final PackageSetting ps = (PackageSetting) obj;
16417            if (ps.pkg != null) {
16418                return ps.pkg.applicationInfo.targetSdkVersion;
16419            }
16420        }
16421        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16422    }
16423
16424    @Override
16425    public void addPreferredActivity(IntentFilter filter, int match,
16426            ComponentName[] set, ComponentName activity, int userId) {
16427        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16428                "Adding preferred");
16429    }
16430
16431    private void addPreferredActivityInternal(IntentFilter filter, int match,
16432            ComponentName[] set, ComponentName activity, boolean always, int userId,
16433            String opname) {
16434        // writer
16435        int callingUid = Binder.getCallingUid();
16436        enforceCrossUserPermission(callingUid, userId,
16437                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16438        if (filter.countActions() == 0) {
16439            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16440            return;
16441        }
16442        synchronized (mPackages) {
16443            if (mContext.checkCallingOrSelfPermission(
16444                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16445                    != PackageManager.PERMISSION_GRANTED) {
16446                if (getUidTargetSdkVersionLockedLPr(callingUid)
16447                        < Build.VERSION_CODES.FROYO) {
16448                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16449                            + callingUid);
16450                    return;
16451                }
16452                mContext.enforceCallingOrSelfPermission(
16453                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16454            }
16455
16456            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16457            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16458                    + userId + ":");
16459            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16460            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16461            scheduleWritePackageRestrictionsLocked(userId);
16462        }
16463    }
16464
16465    @Override
16466    public void replacePreferredActivity(IntentFilter filter, int match,
16467            ComponentName[] set, ComponentName activity, int userId) {
16468        if (filter.countActions() != 1) {
16469            throw new IllegalArgumentException(
16470                    "replacePreferredActivity expects filter to have only 1 action.");
16471        }
16472        if (filter.countDataAuthorities() != 0
16473                || filter.countDataPaths() != 0
16474                || filter.countDataSchemes() > 1
16475                || filter.countDataTypes() != 0) {
16476            throw new IllegalArgumentException(
16477                    "replacePreferredActivity expects filter to have no data authorities, " +
16478                    "paths, or types; and at most one scheme.");
16479        }
16480
16481        final int callingUid = Binder.getCallingUid();
16482        enforceCrossUserPermission(callingUid, userId,
16483                true /* requireFullPermission */, false /* checkShell */,
16484                "replace preferred activity");
16485        synchronized (mPackages) {
16486            if (mContext.checkCallingOrSelfPermission(
16487                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16488                    != PackageManager.PERMISSION_GRANTED) {
16489                if (getUidTargetSdkVersionLockedLPr(callingUid)
16490                        < Build.VERSION_CODES.FROYO) {
16491                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16492                            + Binder.getCallingUid());
16493                    return;
16494                }
16495                mContext.enforceCallingOrSelfPermission(
16496                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16497            }
16498
16499            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16500            if (pir != null) {
16501                // Get all of the existing entries that exactly match this filter.
16502                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16503                if (existing != null && existing.size() == 1) {
16504                    PreferredActivity cur = existing.get(0);
16505                    if (DEBUG_PREFERRED) {
16506                        Slog.i(TAG, "Checking replace of preferred:");
16507                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16508                        if (!cur.mPref.mAlways) {
16509                            Slog.i(TAG, "  -- CUR; not mAlways!");
16510                        } else {
16511                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16512                            Slog.i(TAG, "  -- CUR: mSet="
16513                                    + Arrays.toString(cur.mPref.mSetComponents));
16514                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16515                            Slog.i(TAG, "  -- NEW: mMatch="
16516                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16517                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16518                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16519                        }
16520                    }
16521                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16522                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16523                            && cur.mPref.sameSet(set)) {
16524                        // Setting the preferred activity to what it happens to be already
16525                        if (DEBUG_PREFERRED) {
16526                            Slog.i(TAG, "Replacing with same preferred activity "
16527                                    + cur.mPref.mShortComponent + " for user "
16528                                    + userId + ":");
16529                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16530                        }
16531                        return;
16532                    }
16533                }
16534
16535                if (existing != null) {
16536                    if (DEBUG_PREFERRED) {
16537                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16538                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16539                    }
16540                    for (int i = 0; i < existing.size(); i++) {
16541                        PreferredActivity pa = existing.get(i);
16542                        if (DEBUG_PREFERRED) {
16543                            Slog.i(TAG, "Removing existing preferred activity "
16544                                    + pa.mPref.mComponent + ":");
16545                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16546                        }
16547                        pir.removeFilter(pa);
16548                    }
16549                }
16550            }
16551            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16552                    "Replacing preferred");
16553        }
16554    }
16555
16556    @Override
16557    public void clearPackagePreferredActivities(String packageName) {
16558        final int uid = Binder.getCallingUid();
16559        // writer
16560        synchronized (mPackages) {
16561            PackageParser.Package pkg = mPackages.get(packageName);
16562            if (pkg == null || pkg.applicationInfo.uid != uid) {
16563                if (mContext.checkCallingOrSelfPermission(
16564                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16565                        != PackageManager.PERMISSION_GRANTED) {
16566                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16567                            < Build.VERSION_CODES.FROYO) {
16568                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16569                                + Binder.getCallingUid());
16570                        return;
16571                    }
16572                    mContext.enforceCallingOrSelfPermission(
16573                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16574                }
16575            }
16576
16577            int user = UserHandle.getCallingUserId();
16578            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16579                scheduleWritePackageRestrictionsLocked(user);
16580            }
16581        }
16582    }
16583
16584    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16585    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16586        ArrayList<PreferredActivity> removed = null;
16587        boolean changed = false;
16588        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16589            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16590            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16591            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16592                continue;
16593            }
16594            Iterator<PreferredActivity> it = pir.filterIterator();
16595            while (it.hasNext()) {
16596                PreferredActivity pa = it.next();
16597                // Mark entry for removal only if it matches the package name
16598                // and the entry is of type "always".
16599                if (packageName == null ||
16600                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16601                                && pa.mPref.mAlways)) {
16602                    if (removed == null) {
16603                        removed = new ArrayList<PreferredActivity>();
16604                    }
16605                    removed.add(pa);
16606                }
16607            }
16608            if (removed != null) {
16609                for (int j=0; j<removed.size(); j++) {
16610                    PreferredActivity pa = removed.get(j);
16611                    pir.removeFilter(pa);
16612                }
16613                changed = true;
16614            }
16615        }
16616        return changed;
16617    }
16618
16619    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16620    private void clearIntentFilterVerificationsLPw(int userId) {
16621        final int packageCount = mPackages.size();
16622        for (int i = 0; i < packageCount; i++) {
16623            PackageParser.Package pkg = mPackages.valueAt(i);
16624            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16625        }
16626    }
16627
16628    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16629    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16630        if (userId == UserHandle.USER_ALL) {
16631            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16632                    sUserManager.getUserIds())) {
16633                for (int oneUserId : sUserManager.getUserIds()) {
16634                    scheduleWritePackageRestrictionsLocked(oneUserId);
16635                }
16636            }
16637        } else {
16638            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16639                scheduleWritePackageRestrictionsLocked(userId);
16640            }
16641        }
16642    }
16643
16644    void clearDefaultBrowserIfNeeded(String packageName) {
16645        for (int oneUserId : sUserManager.getUserIds()) {
16646            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16647            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16648            if (packageName.equals(defaultBrowserPackageName)) {
16649                setDefaultBrowserPackageName(null, oneUserId);
16650            }
16651        }
16652    }
16653
16654    @Override
16655    public void resetApplicationPreferences(int userId) {
16656        mContext.enforceCallingOrSelfPermission(
16657                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16658        final long identity = Binder.clearCallingIdentity();
16659        // writer
16660        try {
16661            synchronized (mPackages) {
16662                clearPackagePreferredActivitiesLPw(null, userId);
16663                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16664                // TODO: We have to reset the default SMS and Phone. This requires
16665                // significant refactoring to keep all default apps in the package
16666                // manager (cleaner but more work) or have the services provide
16667                // callbacks to the package manager to request a default app reset.
16668                applyFactoryDefaultBrowserLPw(userId);
16669                clearIntentFilterVerificationsLPw(userId);
16670                primeDomainVerificationsLPw(userId);
16671                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16672                scheduleWritePackageRestrictionsLocked(userId);
16673            }
16674            resetNetworkPolicies(userId);
16675        } finally {
16676            Binder.restoreCallingIdentity(identity);
16677        }
16678    }
16679
16680    @Override
16681    public int getPreferredActivities(List<IntentFilter> outFilters,
16682            List<ComponentName> outActivities, String packageName) {
16683
16684        int num = 0;
16685        final int userId = UserHandle.getCallingUserId();
16686        // reader
16687        synchronized (mPackages) {
16688            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16689            if (pir != null) {
16690                final Iterator<PreferredActivity> it = pir.filterIterator();
16691                while (it.hasNext()) {
16692                    final PreferredActivity pa = it.next();
16693                    if (packageName == null
16694                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16695                                    && pa.mPref.mAlways)) {
16696                        if (outFilters != null) {
16697                            outFilters.add(new IntentFilter(pa));
16698                        }
16699                        if (outActivities != null) {
16700                            outActivities.add(pa.mPref.mComponent);
16701                        }
16702                    }
16703                }
16704            }
16705        }
16706
16707        return num;
16708    }
16709
16710    @Override
16711    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16712            int userId) {
16713        int callingUid = Binder.getCallingUid();
16714        if (callingUid != Process.SYSTEM_UID) {
16715            throw new SecurityException(
16716                    "addPersistentPreferredActivity can only be run by the system");
16717        }
16718        if (filter.countActions() == 0) {
16719            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16720            return;
16721        }
16722        synchronized (mPackages) {
16723            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16724                    ":");
16725            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16726            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16727                    new PersistentPreferredActivity(filter, activity));
16728            scheduleWritePackageRestrictionsLocked(userId);
16729        }
16730    }
16731
16732    @Override
16733    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16734        int callingUid = Binder.getCallingUid();
16735        if (callingUid != Process.SYSTEM_UID) {
16736            throw new SecurityException(
16737                    "clearPackagePersistentPreferredActivities can only be run by the system");
16738        }
16739        ArrayList<PersistentPreferredActivity> removed = null;
16740        boolean changed = false;
16741        synchronized (mPackages) {
16742            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16743                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16744                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16745                        .valueAt(i);
16746                if (userId != thisUserId) {
16747                    continue;
16748                }
16749                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16750                while (it.hasNext()) {
16751                    PersistentPreferredActivity ppa = it.next();
16752                    // Mark entry for removal only if it matches the package name.
16753                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16754                        if (removed == null) {
16755                            removed = new ArrayList<PersistentPreferredActivity>();
16756                        }
16757                        removed.add(ppa);
16758                    }
16759                }
16760                if (removed != null) {
16761                    for (int j=0; j<removed.size(); j++) {
16762                        PersistentPreferredActivity ppa = removed.get(j);
16763                        ppir.removeFilter(ppa);
16764                    }
16765                    changed = true;
16766                }
16767            }
16768
16769            if (changed) {
16770                scheduleWritePackageRestrictionsLocked(userId);
16771            }
16772        }
16773    }
16774
16775    /**
16776     * Common machinery for picking apart a restored XML blob and passing
16777     * it to a caller-supplied functor to be applied to the running system.
16778     */
16779    private void restoreFromXml(XmlPullParser parser, int userId,
16780            String expectedStartTag, BlobXmlRestorer functor)
16781            throws IOException, XmlPullParserException {
16782        int type;
16783        while ((type = parser.next()) != XmlPullParser.START_TAG
16784                && type != XmlPullParser.END_DOCUMENT) {
16785        }
16786        if (type != XmlPullParser.START_TAG) {
16787            // oops didn't find a start tag?!
16788            if (DEBUG_BACKUP) {
16789                Slog.e(TAG, "Didn't find start tag during restore");
16790            }
16791            return;
16792        }
16793Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16794        // this is supposed to be TAG_PREFERRED_BACKUP
16795        if (!expectedStartTag.equals(parser.getName())) {
16796            if (DEBUG_BACKUP) {
16797                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16798            }
16799            return;
16800        }
16801
16802        // skip interfering stuff, then we're aligned with the backing implementation
16803        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16804Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16805        functor.apply(parser, userId);
16806    }
16807
16808    private interface BlobXmlRestorer {
16809        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16810    }
16811
16812    /**
16813     * Non-Binder method, support for the backup/restore mechanism: write the
16814     * full set of preferred activities in its canonical XML format.  Returns the
16815     * XML output as a byte array, or null if there is none.
16816     */
16817    @Override
16818    public byte[] getPreferredActivityBackup(int userId) {
16819        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16820            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16821        }
16822
16823        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16824        try {
16825            final XmlSerializer serializer = new FastXmlSerializer();
16826            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16827            serializer.startDocument(null, true);
16828            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16829
16830            synchronized (mPackages) {
16831                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16832            }
16833
16834            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16835            serializer.endDocument();
16836            serializer.flush();
16837        } catch (Exception e) {
16838            if (DEBUG_BACKUP) {
16839                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16840            }
16841            return null;
16842        }
16843
16844        return dataStream.toByteArray();
16845    }
16846
16847    @Override
16848    public void restorePreferredActivities(byte[] backup, int userId) {
16849        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16850            throw new SecurityException("Only the system may call restorePreferredActivities()");
16851        }
16852
16853        try {
16854            final XmlPullParser parser = Xml.newPullParser();
16855            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16856            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16857                    new BlobXmlRestorer() {
16858                        @Override
16859                        public void apply(XmlPullParser parser, int userId)
16860                                throws XmlPullParserException, IOException {
16861                            synchronized (mPackages) {
16862                                mSettings.readPreferredActivitiesLPw(parser, userId);
16863                            }
16864                        }
16865                    } );
16866        } catch (Exception e) {
16867            if (DEBUG_BACKUP) {
16868                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16869            }
16870        }
16871    }
16872
16873    /**
16874     * Non-Binder method, support for the backup/restore mechanism: write the
16875     * default browser (etc) settings in its canonical XML format.  Returns the default
16876     * browser XML representation as a byte array, or null if there is none.
16877     */
16878    @Override
16879    public byte[] getDefaultAppsBackup(int userId) {
16880        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16881            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16882        }
16883
16884        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16885        try {
16886            final XmlSerializer serializer = new FastXmlSerializer();
16887            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16888            serializer.startDocument(null, true);
16889            serializer.startTag(null, TAG_DEFAULT_APPS);
16890
16891            synchronized (mPackages) {
16892                mSettings.writeDefaultAppsLPr(serializer, userId);
16893            }
16894
16895            serializer.endTag(null, TAG_DEFAULT_APPS);
16896            serializer.endDocument();
16897            serializer.flush();
16898        } catch (Exception e) {
16899            if (DEBUG_BACKUP) {
16900                Slog.e(TAG, "Unable to write default apps for backup", e);
16901            }
16902            return null;
16903        }
16904
16905        return dataStream.toByteArray();
16906    }
16907
16908    @Override
16909    public void restoreDefaultApps(byte[] backup, int userId) {
16910        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16911            throw new SecurityException("Only the system may call restoreDefaultApps()");
16912        }
16913
16914        try {
16915            final XmlPullParser parser = Xml.newPullParser();
16916            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16917            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16918                    new BlobXmlRestorer() {
16919                        @Override
16920                        public void apply(XmlPullParser parser, int userId)
16921                                throws XmlPullParserException, IOException {
16922                            synchronized (mPackages) {
16923                                mSettings.readDefaultAppsLPw(parser, userId);
16924                            }
16925                        }
16926                    } );
16927        } catch (Exception e) {
16928            if (DEBUG_BACKUP) {
16929                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16930            }
16931        }
16932    }
16933
16934    @Override
16935    public byte[] getIntentFilterVerificationBackup(int userId) {
16936        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16937            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16938        }
16939
16940        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16941        try {
16942            final XmlSerializer serializer = new FastXmlSerializer();
16943            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16944            serializer.startDocument(null, true);
16945            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16946
16947            synchronized (mPackages) {
16948                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16949            }
16950
16951            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16952            serializer.endDocument();
16953            serializer.flush();
16954        } catch (Exception e) {
16955            if (DEBUG_BACKUP) {
16956                Slog.e(TAG, "Unable to write default apps for backup", e);
16957            }
16958            return null;
16959        }
16960
16961        return dataStream.toByteArray();
16962    }
16963
16964    @Override
16965    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16966        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16967            throw new SecurityException("Only the system may call restorePreferredActivities()");
16968        }
16969
16970        try {
16971            final XmlPullParser parser = Xml.newPullParser();
16972            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16973            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16974                    new BlobXmlRestorer() {
16975                        @Override
16976                        public void apply(XmlPullParser parser, int userId)
16977                                throws XmlPullParserException, IOException {
16978                            synchronized (mPackages) {
16979                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16980                                mSettings.writeLPr();
16981                            }
16982                        }
16983                    } );
16984        } catch (Exception e) {
16985            if (DEBUG_BACKUP) {
16986                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16987            }
16988        }
16989    }
16990
16991    @Override
16992    public byte[] getPermissionGrantBackup(int userId) {
16993        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16994            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16995        }
16996
16997        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16998        try {
16999            final XmlSerializer serializer = new FastXmlSerializer();
17000            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17001            serializer.startDocument(null, true);
17002            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17003
17004            synchronized (mPackages) {
17005                serializeRuntimePermissionGrantsLPr(serializer, userId);
17006            }
17007
17008            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17009            serializer.endDocument();
17010            serializer.flush();
17011        } catch (Exception e) {
17012            if (DEBUG_BACKUP) {
17013                Slog.e(TAG, "Unable to write default apps for backup", e);
17014            }
17015            return null;
17016        }
17017
17018        return dataStream.toByteArray();
17019    }
17020
17021    @Override
17022    public void restorePermissionGrants(byte[] backup, int userId) {
17023        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17024            throw new SecurityException("Only the system may call restorePermissionGrants()");
17025        }
17026
17027        try {
17028            final XmlPullParser parser = Xml.newPullParser();
17029            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17030            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17031                    new BlobXmlRestorer() {
17032                        @Override
17033                        public void apply(XmlPullParser parser, int userId)
17034                                throws XmlPullParserException, IOException {
17035                            synchronized (mPackages) {
17036                                processRestoredPermissionGrantsLPr(parser, userId);
17037                            }
17038                        }
17039                    } );
17040        } catch (Exception e) {
17041            if (DEBUG_BACKUP) {
17042                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17043            }
17044        }
17045    }
17046
17047    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17048            throws IOException {
17049        serializer.startTag(null, TAG_ALL_GRANTS);
17050
17051        final int N = mSettings.mPackages.size();
17052        for (int i = 0; i < N; i++) {
17053            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17054            boolean pkgGrantsKnown = false;
17055
17056            PermissionsState packagePerms = ps.getPermissionsState();
17057
17058            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17059                final int grantFlags = state.getFlags();
17060                // only look at grants that are not system/policy fixed
17061                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17062                    final boolean isGranted = state.isGranted();
17063                    // And only back up the user-twiddled state bits
17064                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17065                        final String packageName = mSettings.mPackages.keyAt(i);
17066                        if (!pkgGrantsKnown) {
17067                            serializer.startTag(null, TAG_GRANT);
17068                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17069                            pkgGrantsKnown = true;
17070                        }
17071
17072                        final boolean userSet =
17073                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17074                        final boolean userFixed =
17075                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17076                        final boolean revoke =
17077                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17078
17079                        serializer.startTag(null, TAG_PERMISSION);
17080                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17081                        if (isGranted) {
17082                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17083                        }
17084                        if (userSet) {
17085                            serializer.attribute(null, ATTR_USER_SET, "true");
17086                        }
17087                        if (userFixed) {
17088                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17089                        }
17090                        if (revoke) {
17091                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17092                        }
17093                        serializer.endTag(null, TAG_PERMISSION);
17094                    }
17095                }
17096            }
17097
17098            if (pkgGrantsKnown) {
17099                serializer.endTag(null, TAG_GRANT);
17100            }
17101        }
17102
17103        serializer.endTag(null, TAG_ALL_GRANTS);
17104    }
17105
17106    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17107            throws XmlPullParserException, IOException {
17108        String pkgName = null;
17109        int outerDepth = parser.getDepth();
17110        int type;
17111        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17112                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17113            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17114                continue;
17115            }
17116
17117            final String tagName = parser.getName();
17118            if (tagName.equals(TAG_GRANT)) {
17119                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17120                if (DEBUG_BACKUP) {
17121                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17122                }
17123            } else if (tagName.equals(TAG_PERMISSION)) {
17124
17125                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17126                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17127
17128                int newFlagSet = 0;
17129                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17130                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17131                }
17132                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17133                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17134                }
17135                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17136                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17137                }
17138                if (DEBUG_BACKUP) {
17139                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17140                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17141                }
17142                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17143                if (ps != null) {
17144                    // Already installed so we apply the grant immediately
17145                    if (DEBUG_BACKUP) {
17146                        Slog.v(TAG, "        + already installed; applying");
17147                    }
17148                    PermissionsState perms = ps.getPermissionsState();
17149                    BasePermission bp = mSettings.mPermissions.get(permName);
17150                    if (bp != null) {
17151                        if (isGranted) {
17152                            perms.grantRuntimePermission(bp, userId);
17153                        }
17154                        if (newFlagSet != 0) {
17155                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17156                        }
17157                    }
17158                } else {
17159                    // Need to wait for post-restore install to apply the grant
17160                    if (DEBUG_BACKUP) {
17161                        Slog.v(TAG, "        - not yet installed; saving for later");
17162                    }
17163                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17164                            isGranted, newFlagSet, userId);
17165                }
17166            } else {
17167                PackageManagerService.reportSettingsProblem(Log.WARN,
17168                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17169                XmlUtils.skipCurrentTag(parser);
17170            }
17171        }
17172
17173        scheduleWriteSettingsLocked();
17174        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17175    }
17176
17177    @Override
17178    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17179            int sourceUserId, int targetUserId, int flags) {
17180        mContext.enforceCallingOrSelfPermission(
17181                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17182        int callingUid = Binder.getCallingUid();
17183        enforceOwnerRights(ownerPackage, callingUid);
17184        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17185        if (intentFilter.countActions() == 0) {
17186            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17187            return;
17188        }
17189        synchronized (mPackages) {
17190            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17191                    ownerPackage, targetUserId, flags);
17192            CrossProfileIntentResolver resolver =
17193                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17194            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17195            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17196            if (existing != null) {
17197                int size = existing.size();
17198                for (int i = 0; i < size; i++) {
17199                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17200                        return;
17201                    }
17202                }
17203            }
17204            resolver.addFilter(newFilter);
17205            scheduleWritePackageRestrictionsLocked(sourceUserId);
17206        }
17207    }
17208
17209    @Override
17210    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17211        mContext.enforceCallingOrSelfPermission(
17212                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17213        int callingUid = Binder.getCallingUid();
17214        enforceOwnerRights(ownerPackage, callingUid);
17215        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17216        synchronized (mPackages) {
17217            CrossProfileIntentResolver resolver =
17218                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17219            ArraySet<CrossProfileIntentFilter> set =
17220                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17221            for (CrossProfileIntentFilter filter : set) {
17222                if (filter.getOwnerPackage().equals(ownerPackage)) {
17223                    resolver.removeFilter(filter);
17224                }
17225            }
17226            scheduleWritePackageRestrictionsLocked(sourceUserId);
17227        }
17228    }
17229
17230    // Enforcing that callingUid is owning pkg on userId
17231    private void enforceOwnerRights(String pkg, int callingUid) {
17232        // The system owns everything.
17233        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17234            return;
17235        }
17236        int callingUserId = UserHandle.getUserId(callingUid);
17237        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17238        if (pi == null) {
17239            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17240                    + callingUserId);
17241        }
17242        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17243            throw new SecurityException("Calling uid " + callingUid
17244                    + " does not own package " + pkg);
17245        }
17246    }
17247
17248    @Override
17249    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17250        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17251    }
17252
17253    private Intent getHomeIntent() {
17254        Intent intent = new Intent(Intent.ACTION_MAIN);
17255        intent.addCategory(Intent.CATEGORY_HOME);
17256        return intent;
17257    }
17258
17259    private IntentFilter getHomeFilter() {
17260        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17261        filter.addCategory(Intent.CATEGORY_HOME);
17262        filter.addCategory(Intent.CATEGORY_DEFAULT);
17263        return filter;
17264    }
17265
17266    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17267            int userId) {
17268        Intent intent  = getHomeIntent();
17269        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17270                PackageManager.GET_META_DATA, userId);
17271        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17272                true, false, false, userId);
17273
17274        allHomeCandidates.clear();
17275        if (list != null) {
17276            for (ResolveInfo ri : list) {
17277                allHomeCandidates.add(ri);
17278            }
17279        }
17280        return (preferred == null || preferred.activityInfo == null)
17281                ? null
17282                : new ComponentName(preferred.activityInfo.packageName,
17283                        preferred.activityInfo.name);
17284    }
17285
17286    @Override
17287    public void setHomeActivity(ComponentName comp, int userId) {
17288        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17289        getHomeActivitiesAsUser(homeActivities, userId);
17290
17291        boolean found = false;
17292
17293        final int size = homeActivities.size();
17294        final ComponentName[] set = new ComponentName[size];
17295        for (int i = 0; i < size; i++) {
17296            final ResolveInfo candidate = homeActivities.get(i);
17297            final ActivityInfo info = candidate.activityInfo;
17298            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17299            set[i] = activityName;
17300            if (!found && activityName.equals(comp)) {
17301                found = true;
17302            }
17303        }
17304        if (!found) {
17305            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17306                    + userId);
17307        }
17308        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17309                set, comp, userId);
17310    }
17311
17312    private @Nullable String getSetupWizardPackageName() {
17313        final Intent intent = new Intent(Intent.ACTION_MAIN);
17314        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17315
17316        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17317                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17318                        | MATCH_DISABLED_COMPONENTS,
17319                UserHandle.myUserId());
17320        if (matches.size() == 1) {
17321            return matches.get(0).getComponentInfo().packageName;
17322        } else {
17323            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17324                    + ": matches=" + matches);
17325            return null;
17326        }
17327    }
17328
17329    @Override
17330    public void setApplicationEnabledSetting(String appPackageName,
17331            int newState, int flags, int userId, String callingPackage) {
17332        if (!sUserManager.exists(userId)) return;
17333        if (callingPackage == null) {
17334            callingPackage = Integer.toString(Binder.getCallingUid());
17335        }
17336        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17337    }
17338
17339    @Override
17340    public void setComponentEnabledSetting(ComponentName componentName,
17341            int newState, int flags, int userId) {
17342        if (!sUserManager.exists(userId)) return;
17343        setEnabledSetting(componentName.getPackageName(),
17344                componentName.getClassName(), newState, flags, userId, null);
17345    }
17346
17347    private void setEnabledSetting(final String packageName, String className, int newState,
17348            final int flags, int userId, String callingPackage) {
17349        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17350              || newState == COMPONENT_ENABLED_STATE_ENABLED
17351              || newState == COMPONENT_ENABLED_STATE_DISABLED
17352              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17353              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17354            throw new IllegalArgumentException("Invalid new component state: "
17355                    + newState);
17356        }
17357        PackageSetting pkgSetting;
17358        final int uid = Binder.getCallingUid();
17359        final int permission;
17360        if (uid == Process.SYSTEM_UID) {
17361            permission = PackageManager.PERMISSION_GRANTED;
17362        } else {
17363            permission = mContext.checkCallingOrSelfPermission(
17364                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17365        }
17366        enforceCrossUserPermission(uid, userId,
17367                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17368        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17369        boolean sendNow = false;
17370        boolean isApp = (className == null);
17371        String componentName = isApp ? packageName : className;
17372        int packageUid = -1;
17373        ArrayList<String> components;
17374
17375        // writer
17376        synchronized (mPackages) {
17377            pkgSetting = mSettings.mPackages.get(packageName);
17378            if (pkgSetting == null) {
17379                if (className == null) {
17380                    throw new IllegalArgumentException("Unknown package: " + packageName);
17381                }
17382                throw new IllegalArgumentException(
17383                        "Unknown component: " + packageName + "/" + className);
17384            }
17385            // Allow root and verify that userId is not being specified by a different user
17386            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17387                throw new SecurityException(
17388                        "Permission Denial: attempt to change component state from pid="
17389                        + Binder.getCallingPid()
17390                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17391            }
17392            if (className == null) {
17393                // We're dealing with an application/package level state change
17394                if (pkgSetting.getEnabled(userId) == newState) {
17395                    // Nothing to do
17396                    return;
17397                }
17398                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17399                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17400                    // Don't care about who enables an app.
17401                    callingPackage = null;
17402                }
17403                pkgSetting.setEnabled(newState, userId, callingPackage);
17404                // pkgSetting.pkg.mSetEnabled = newState;
17405            } else {
17406                // We're dealing with a component level state change
17407                // First, verify that this is a valid class name.
17408                PackageParser.Package pkg = pkgSetting.pkg;
17409                if (pkg == null || !pkg.hasComponentClassName(className)) {
17410                    if (pkg != null &&
17411                            pkg.applicationInfo.targetSdkVersion >=
17412                                    Build.VERSION_CODES.JELLY_BEAN) {
17413                        throw new IllegalArgumentException("Component class " + className
17414                                + " does not exist in " + packageName);
17415                    } else {
17416                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17417                                + className + " does not exist in " + packageName);
17418                    }
17419                }
17420                switch (newState) {
17421                case COMPONENT_ENABLED_STATE_ENABLED:
17422                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17423                        return;
17424                    }
17425                    break;
17426                case COMPONENT_ENABLED_STATE_DISABLED:
17427                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17428                        return;
17429                    }
17430                    break;
17431                case COMPONENT_ENABLED_STATE_DEFAULT:
17432                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17433                        return;
17434                    }
17435                    break;
17436                default:
17437                    Slog.e(TAG, "Invalid new component state: " + newState);
17438                    return;
17439                }
17440            }
17441            scheduleWritePackageRestrictionsLocked(userId);
17442            components = mPendingBroadcasts.get(userId, packageName);
17443            final boolean newPackage = components == null;
17444            if (newPackage) {
17445                components = new ArrayList<String>();
17446            }
17447            if (!components.contains(componentName)) {
17448                components.add(componentName);
17449            }
17450            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17451                sendNow = true;
17452                // Purge entry from pending broadcast list if another one exists already
17453                // since we are sending one right away.
17454                mPendingBroadcasts.remove(userId, packageName);
17455            } else {
17456                if (newPackage) {
17457                    mPendingBroadcasts.put(userId, packageName, components);
17458                }
17459                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17460                    // Schedule a message
17461                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17462                }
17463            }
17464        }
17465
17466        long callingId = Binder.clearCallingIdentity();
17467        try {
17468            if (sendNow) {
17469                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17470                sendPackageChangedBroadcast(packageName,
17471                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17472            }
17473        } finally {
17474            Binder.restoreCallingIdentity(callingId);
17475        }
17476    }
17477
17478    @Override
17479    public void flushPackageRestrictionsAsUser(int userId) {
17480        if (!sUserManager.exists(userId)) {
17481            return;
17482        }
17483        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17484                false /* checkShell */, "flushPackageRestrictions");
17485        synchronized (mPackages) {
17486            mSettings.writePackageRestrictionsLPr(userId);
17487            mDirtyUsers.remove(userId);
17488            if (mDirtyUsers.isEmpty()) {
17489                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17490            }
17491        }
17492    }
17493
17494    private void sendPackageChangedBroadcast(String packageName,
17495            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17496        if (DEBUG_INSTALL)
17497            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17498                    + componentNames);
17499        Bundle extras = new Bundle(4);
17500        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17501        String nameList[] = new String[componentNames.size()];
17502        componentNames.toArray(nameList);
17503        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17504        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17505        extras.putInt(Intent.EXTRA_UID, packageUid);
17506        // If this is not reporting a change of the overall package, then only send it
17507        // to registered receivers.  We don't want to launch a swath of apps for every
17508        // little component state change.
17509        final int flags = !componentNames.contains(packageName)
17510                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17511        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17512                new int[] {UserHandle.getUserId(packageUid)});
17513    }
17514
17515    @Override
17516    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17517        if (!sUserManager.exists(userId)) return;
17518        final int uid = Binder.getCallingUid();
17519        final int permission = mContext.checkCallingOrSelfPermission(
17520                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17521        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17522        enforceCrossUserPermission(uid, userId,
17523                true /* requireFullPermission */, true /* checkShell */, "stop package");
17524        // writer
17525        synchronized (mPackages) {
17526            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17527                    allowedByPermission, uid, userId)) {
17528                scheduleWritePackageRestrictionsLocked(userId);
17529            }
17530        }
17531    }
17532
17533    @Override
17534    public String getInstallerPackageName(String packageName) {
17535        // reader
17536        synchronized (mPackages) {
17537            return mSettings.getInstallerPackageNameLPr(packageName);
17538        }
17539    }
17540
17541    public boolean isOrphaned(String packageName) {
17542        // reader
17543        synchronized (mPackages) {
17544            return mSettings.isOrphaned(packageName);
17545        }
17546    }
17547
17548    @Override
17549    public int getApplicationEnabledSetting(String packageName, int userId) {
17550        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17551        int uid = Binder.getCallingUid();
17552        enforceCrossUserPermission(uid, userId,
17553                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17554        // reader
17555        synchronized (mPackages) {
17556            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17557        }
17558    }
17559
17560    @Override
17561    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17562        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17563        int uid = Binder.getCallingUid();
17564        enforceCrossUserPermission(uid, userId,
17565                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17566        // reader
17567        synchronized (mPackages) {
17568            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17569        }
17570    }
17571
17572    @Override
17573    public void enterSafeMode() {
17574        enforceSystemOrRoot("Only the system can request entering safe mode");
17575
17576        if (!mSystemReady) {
17577            mSafeMode = true;
17578        }
17579    }
17580
17581    @Override
17582    public void systemReady() {
17583        mSystemReady = true;
17584
17585        // Read the compatibilty setting when the system is ready.
17586        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17587                mContext.getContentResolver(),
17588                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17589        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17590        if (DEBUG_SETTINGS) {
17591            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17592        }
17593
17594        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17595
17596        synchronized (mPackages) {
17597            // Verify that all of the preferred activity components actually
17598            // exist.  It is possible for applications to be updated and at
17599            // that point remove a previously declared activity component that
17600            // had been set as a preferred activity.  We try to clean this up
17601            // the next time we encounter that preferred activity, but it is
17602            // possible for the user flow to never be able to return to that
17603            // situation so here we do a sanity check to make sure we haven't
17604            // left any junk around.
17605            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17606            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17607                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17608                removed.clear();
17609                for (PreferredActivity pa : pir.filterSet()) {
17610                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17611                        removed.add(pa);
17612                    }
17613                }
17614                if (removed.size() > 0) {
17615                    for (int r=0; r<removed.size(); r++) {
17616                        PreferredActivity pa = removed.get(r);
17617                        Slog.w(TAG, "Removing dangling preferred activity: "
17618                                + pa.mPref.mComponent);
17619                        pir.removeFilter(pa);
17620                    }
17621                    mSettings.writePackageRestrictionsLPr(
17622                            mSettings.mPreferredActivities.keyAt(i));
17623                }
17624            }
17625
17626            for (int userId : UserManagerService.getInstance().getUserIds()) {
17627                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17628                    grantPermissionsUserIds = ArrayUtils.appendInt(
17629                            grantPermissionsUserIds, userId);
17630                }
17631            }
17632        }
17633        sUserManager.systemReady();
17634
17635        // If we upgraded grant all default permissions before kicking off.
17636        for (int userId : grantPermissionsUserIds) {
17637            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17638        }
17639
17640        // Kick off any messages waiting for system ready
17641        if (mPostSystemReadyMessages != null) {
17642            for (Message msg : mPostSystemReadyMessages) {
17643                msg.sendToTarget();
17644            }
17645            mPostSystemReadyMessages = null;
17646        }
17647
17648        // Watch for external volumes that come and go over time
17649        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17650        storage.registerListener(mStorageListener);
17651
17652        mInstallerService.systemReady();
17653        mPackageDexOptimizer.systemReady();
17654
17655        MountServiceInternal mountServiceInternal = LocalServices.getService(
17656                MountServiceInternal.class);
17657        mountServiceInternal.addExternalStoragePolicy(
17658                new MountServiceInternal.ExternalStorageMountPolicy() {
17659            @Override
17660            public int getMountMode(int uid, String packageName) {
17661                if (Process.isIsolated(uid)) {
17662                    return Zygote.MOUNT_EXTERNAL_NONE;
17663                }
17664                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17665                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17666                }
17667                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17668                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17669                }
17670                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17671                    return Zygote.MOUNT_EXTERNAL_READ;
17672                }
17673                return Zygote.MOUNT_EXTERNAL_WRITE;
17674            }
17675
17676            @Override
17677            public boolean hasExternalStorage(int uid, String packageName) {
17678                return true;
17679            }
17680        });
17681
17682        // Now that we're mostly running, clean up stale users and apps
17683        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17684        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17685    }
17686
17687    @Override
17688    public boolean isSafeMode() {
17689        return mSafeMode;
17690    }
17691
17692    @Override
17693    public boolean hasSystemUidErrors() {
17694        return mHasSystemUidErrors;
17695    }
17696
17697    static String arrayToString(int[] array) {
17698        StringBuffer buf = new StringBuffer(128);
17699        buf.append('[');
17700        if (array != null) {
17701            for (int i=0; i<array.length; i++) {
17702                if (i > 0) buf.append(", ");
17703                buf.append(array[i]);
17704            }
17705        }
17706        buf.append(']');
17707        return buf.toString();
17708    }
17709
17710    static class DumpState {
17711        public static final int DUMP_LIBS = 1 << 0;
17712        public static final int DUMP_FEATURES = 1 << 1;
17713        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17714        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17715        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17716        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17717        public static final int DUMP_PERMISSIONS = 1 << 6;
17718        public static final int DUMP_PACKAGES = 1 << 7;
17719        public static final int DUMP_SHARED_USERS = 1 << 8;
17720        public static final int DUMP_MESSAGES = 1 << 9;
17721        public static final int DUMP_PROVIDERS = 1 << 10;
17722        public static final int DUMP_VERIFIERS = 1 << 11;
17723        public static final int DUMP_PREFERRED = 1 << 12;
17724        public static final int DUMP_PREFERRED_XML = 1 << 13;
17725        public static final int DUMP_KEYSETS = 1 << 14;
17726        public static final int DUMP_VERSION = 1 << 15;
17727        public static final int DUMP_INSTALLS = 1 << 16;
17728        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17729        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17730        public static final int DUMP_FROZEN = 1 << 19;
17731
17732        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17733
17734        private int mTypes;
17735
17736        private int mOptions;
17737
17738        private boolean mTitlePrinted;
17739
17740        private SharedUserSetting mSharedUser;
17741
17742        public boolean isDumping(int type) {
17743            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17744                return true;
17745            }
17746
17747            return (mTypes & type) != 0;
17748        }
17749
17750        public void setDump(int type) {
17751            mTypes |= type;
17752        }
17753
17754        public boolean isOptionEnabled(int option) {
17755            return (mOptions & option) != 0;
17756        }
17757
17758        public void setOptionEnabled(int option) {
17759            mOptions |= option;
17760        }
17761
17762        public boolean onTitlePrinted() {
17763            final boolean printed = mTitlePrinted;
17764            mTitlePrinted = true;
17765            return printed;
17766        }
17767
17768        public boolean getTitlePrinted() {
17769            return mTitlePrinted;
17770        }
17771
17772        public void setTitlePrinted(boolean enabled) {
17773            mTitlePrinted = enabled;
17774        }
17775
17776        public SharedUserSetting getSharedUser() {
17777            return mSharedUser;
17778        }
17779
17780        public void setSharedUser(SharedUserSetting user) {
17781            mSharedUser = user;
17782        }
17783    }
17784
17785    @Override
17786    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17787            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17788        (new PackageManagerShellCommand(this)).exec(
17789                this, in, out, err, args, resultReceiver);
17790    }
17791
17792    @Override
17793    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17794        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17795                != PackageManager.PERMISSION_GRANTED) {
17796            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17797                    + Binder.getCallingPid()
17798                    + ", uid=" + Binder.getCallingUid()
17799                    + " without permission "
17800                    + android.Manifest.permission.DUMP);
17801            return;
17802        }
17803
17804        DumpState dumpState = new DumpState();
17805        boolean fullPreferred = false;
17806        boolean checkin = false;
17807
17808        String packageName = null;
17809        ArraySet<String> permissionNames = null;
17810
17811        int opti = 0;
17812        while (opti < args.length) {
17813            String opt = args[opti];
17814            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17815                break;
17816            }
17817            opti++;
17818
17819            if ("-a".equals(opt)) {
17820                // Right now we only know how to print all.
17821            } else if ("-h".equals(opt)) {
17822                pw.println("Package manager dump options:");
17823                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17824                pw.println("    --checkin: dump for a checkin");
17825                pw.println("    -f: print details of intent filters");
17826                pw.println("    -h: print this help");
17827                pw.println("  cmd may be one of:");
17828                pw.println("    l[ibraries]: list known shared libraries");
17829                pw.println("    f[eatures]: list device features");
17830                pw.println("    k[eysets]: print known keysets");
17831                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17832                pw.println("    perm[issions]: dump permissions");
17833                pw.println("    permission [name ...]: dump declaration and use of given permission");
17834                pw.println("    pref[erred]: print preferred package settings");
17835                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17836                pw.println("    prov[iders]: dump content providers");
17837                pw.println("    p[ackages]: dump installed packages");
17838                pw.println("    s[hared-users]: dump shared user IDs");
17839                pw.println("    m[essages]: print collected runtime messages");
17840                pw.println("    v[erifiers]: print package verifier info");
17841                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17842                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17843                pw.println("    version: print database version info");
17844                pw.println("    write: write current settings now");
17845                pw.println("    installs: details about install sessions");
17846                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17847                pw.println("    <package.name>: info about given package");
17848                return;
17849            } else if ("--checkin".equals(opt)) {
17850                checkin = true;
17851            } else if ("-f".equals(opt)) {
17852                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17853            } else {
17854                pw.println("Unknown argument: " + opt + "; use -h for help");
17855            }
17856        }
17857
17858        // Is the caller requesting to dump a particular piece of data?
17859        if (opti < args.length) {
17860            String cmd = args[opti];
17861            opti++;
17862            // Is this a package name?
17863            if ("android".equals(cmd) || cmd.contains(".")) {
17864                packageName = cmd;
17865                // When dumping a single package, we always dump all of its
17866                // filter information since the amount of data will be reasonable.
17867                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17868            } else if ("check-permission".equals(cmd)) {
17869                if (opti >= args.length) {
17870                    pw.println("Error: check-permission missing permission argument");
17871                    return;
17872                }
17873                String perm = args[opti];
17874                opti++;
17875                if (opti >= args.length) {
17876                    pw.println("Error: check-permission missing package argument");
17877                    return;
17878                }
17879                String pkg = args[opti];
17880                opti++;
17881                int user = UserHandle.getUserId(Binder.getCallingUid());
17882                if (opti < args.length) {
17883                    try {
17884                        user = Integer.parseInt(args[opti]);
17885                    } catch (NumberFormatException e) {
17886                        pw.println("Error: check-permission user argument is not a number: "
17887                                + args[opti]);
17888                        return;
17889                    }
17890                }
17891                pw.println(checkPermission(perm, pkg, user));
17892                return;
17893            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17894                dumpState.setDump(DumpState.DUMP_LIBS);
17895            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17896                dumpState.setDump(DumpState.DUMP_FEATURES);
17897            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17898                if (opti >= args.length) {
17899                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17900                            | DumpState.DUMP_SERVICE_RESOLVERS
17901                            | DumpState.DUMP_RECEIVER_RESOLVERS
17902                            | DumpState.DUMP_CONTENT_RESOLVERS);
17903                } else {
17904                    while (opti < args.length) {
17905                        String name = args[opti];
17906                        if ("a".equals(name) || "activity".equals(name)) {
17907                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17908                        } else if ("s".equals(name) || "service".equals(name)) {
17909                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17910                        } else if ("r".equals(name) || "receiver".equals(name)) {
17911                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17912                        } else if ("c".equals(name) || "content".equals(name)) {
17913                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17914                        } else {
17915                            pw.println("Error: unknown resolver table type: " + name);
17916                            return;
17917                        }
17918                        opti++;
17919                    }
17920                }
17921            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17922                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17923            } else if ("permission".equals(cmd)) {
17924                if (opti >= args.length) {
17925                    pw.println("Error: permission requires permission name");
17926                    return;
17927                }
17928                permissionNames = new ArraySet<>();
17929                while (opti < args.length) {
17930                    permissionNames.add(args[opti]);
17931                    opti++;
17932                }
17933                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17934                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17935            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17936                dumpState.setDump(DumpState.DUMP_PREFERRED);
17937            } else if ("preferred-xml".equals(cmd)) {
17938                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17939                if (opti < args.length && "--full".equals(args[opti])) {
17940                    fullPreferred = true;
17941                    opti++;
17942                }
17943            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17944                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17945            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17946                dumpState.setDump(DumpState.DUMP_PACKAGES);
17947            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17948                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17949            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17950                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17951            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17952                dumpState.setDump(DumpState.DUMP_MESSAGES);
17953            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17954                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17955            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17956                    || "intent-filter-verifiers".equals(cmd)) {
17957                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17958            } else if ("version".equals(cmd)) {
17959                dumpState.setDump(DumpState.DUMP_VERSION);
17960            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17961                dumpState.setDump(DumpState.DUMP_KEYSETS);
17962            } else if ("installs".equals(cmd)) {
17963                dumpState.setDump(DumpState.DUMP_INSTALLS);
17964            } else if ("frozen".equals(cmd)) {
17965                dumpState.setDump(DumpState.DUMP_FROZEN);
17966            } else if ("write".equals(cmd)) {
17967                synchronized (mPackages) {
17968                    mSettings.writeLPr();
17969                    pw.println("Settings written.");
17970                    return;
17971                }
17972            }
17973        }
17974
17975        if (checkin) {
17976            pw.println("vers,1");
17977        }
17978
17979        // reader
17980        synchronized (mPackages) {
17981            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17982                if (!checkin) {
17983                    if (dumpState.onTitlePrinted())
17984                        pw.println();
17985                    pw.println("Database versions:");
17986                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17987                }
17988            }
17989
17990            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17991                if (!checkin) {
17992                    if (dumpState.onTitlePrinted())
17993                        pw.println();
17994                    pw.println("Verifiers:");
17995                    pw.print("  Required: ");
17996                    pw.print(mRequiredVerifierPackage);
17997                    pw.print(" (uid=");
17998                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17999                            UserHandle.USER_SYSTEM));
18000                    pw.println(")");
18001                } else if (mRequiredVerifierPackage != null) {
18002                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18003                    pw.print(",");
18004                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18005                            UserHandle.USER_SYSTEM));
18006                }
18007            }
18008
18009            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18010                    packageName == null) {
18011                if (mIntentFilterVerifierComponent != null) {
18012                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18013                    if (!checkin) {
18014                        if (dumpState.onTitlePrinted())
18015                            pw.println();
18016                        pw.println("Intent Filter Verifier:");
18017                        pw.print("  Using: ");
18018                        pw.print(verifierPackageName);
18019                        pw.print(" (uid=");
18020                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18021                                UserHandle.USER_SYSTEM));
18022                        pw.println(")");
18023                    } else if (verifierPackageName != null) {
18024                        pw.print("ifv,"); pw.print(verifierPackageName);
18025                        pw.print(",");
18026                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18027                                UserHandle.USER_SYSTEM));
18028                    }
18029                } else {
18030                    pw.println();
18031                    pw.println("No Intent Filter Verifier available!");
18032                }
18033            }
18034
18035            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18036                boolean printedHeader = false;
18037                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18038                while (it.hasNext()) {
18039                    String name = it.next();
18040                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18041                    if (!checkin) {
18042                        if (!printedHeader) {
18043                            if (dumpState.onTitlePrinted())
18044                                pw.println();
18045                            pw.println("Libraries:");
18046                            printedHeader = true;
18047                        }
18048                        pw.print("  ");
18049                    } else {
18050                        pw.print("lib,");
18051                    }
18052                    pw.print(name);
18053                    if (!checkin) {
18054                        pw.print(" -> ");
18055                    }
18056                    if (ent.path != null) {
18057                        if (!checkin) {
18058                            pw.print("(jar) ");
18059                            pw.print(ent.path);
18060                        } else {
18061                            pw.print(",jar,");
18062                            pw.print(ent.path);
18063                        }
18064                    } else {
18065                        if (!checkin) {
18066                            pw.print("(apk) ");
18067                            pw.print(ent.apk);
18068                        } else {
18069                            pw.print(",apk,");
18070                            pw.print(ent.apk);
18071                        }
18072                    }
18073                    pw.println();
18074                }
18075            }
18076
18077            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18078                if (dumpState.onTitlePrinted())
18079                    pw.println();
18080                if (!checkin) {
18081                    pw.println("Features:");
18082                }
18083
18084                for (FeatureInfo feat : mAvailableFeatures.values()) {
18085                    if (checkin) {
18086                        pw.print("feat,");
18087                        pw.print(feat.name);
18088                        pw.print(",");
18089                        pw.println(feat.version);
18090                    } else {
18091                        pw.print("  ");
18092                        pw.print(feat.name);
18093                        if (feat.version > 0) {
18094                            pw.print(" version=");
18095                            pw.print(feat.version);
18096                        }
18097                        pw.println();
18098                    }
18099                }
18100            }
18101
18102            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18103                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18104                        : "Activity Resolver Table:", "  ", packageName,
18105                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18106                    dumpState.setTitlePrinted(true);
18107                }
18108            }
18109            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18110                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18111                        : "Receiver Resolver Table:", "  ", packageName,
18112                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18113                    dumpState.setTitlePrinted(true);
18114                }
18115            }
18116            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18117                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18118                        : "Service Resolver Table:", "  ", packageName,
18119                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18120                    dumpState.setTitlePrinted(true);
18121                }
18122            }
18123            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18124                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18125                        : "Provider Resolver Table:", "  ", packageName,
18126                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18127                    dumpState.setTitlePrinted(true);
18128                }
18129            }
18130
18131            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18132                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18133                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18134                    int user = mSettings.mPreferredActivities.keyAt(i);
18135                    if (pir.dump(pw,
18136                            dumpState.getTitlePrinted()
18137                                ? "\nPreferred Activities User " + user + ":"
18138                                : "Preferred Activities User " + user + ":", "  ",
18139                            packageName, true, false)) {
18140                        dumpState.setTitlePrinted(true);
18141                    }
18142                }
18143            }
18144
18145            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18146                pw.flush();
18147                FileOutputStream fout = new FileOutputStream(fd);
18148                BufferedOutputStream str = new BufferedOutputStream(fout);
18149                XmlSerializer serializer = new FastXmlSerializer();
18150                try {
18151                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18152                    serializer.startDocument(null, true);
18153                    serializer.setFeature(
18154                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18155                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18156                    serializer.endDocument();
18157                    serializer.flush();
18158                } catch (IllegalArgumentException e) {
18159                    pw.println("Failed writing: " + e);
18160                } catch (IllegalStateException e) {
18161                    pw.println("Failed writing: " + e);
18162                } catch (IOException e) {
18163                    pw.println("Failed writing: " + e);
18164                }
18165            }
18166
18167            if (!checkin
18168                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18169                    && packageName == null) {
18170                pw.println();
18171                int count = mSettings.mPackages.size();
18172                if (count == 0) {
18173                    pw.println("No applications!");
18174                    pw.println();
18175                } else {
18176                    final String prefix = "  ";
18177                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18178                    if (allPackageSettings.size() == 0) {
18179                        pw.println("No domain preferred apps!");
18180                        pw.println();
18181                    } else {
18182                        pw.println("App verification status:");
18183                        pw.println();
18184                        count = 0;
18185                        for (PackageSetting ps : allPackageSettings) {
18186                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18187                            if (ivi == null || ivi.getPackageName() == null) continue;
18188                            pw.println(prefix + "Package: " + ivi.getPackageName());
18189                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18190                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18191                            pw.println();
18192                            count++;
18193                        }
18194                        if (count == 0) {
18195                            pw.println(prefix + "No app verification established.");
18196                            pw.println();
18197                        }
18198                        for (int userId : sUserManager.getUserIds()) {
18199                            pw.println("App linkages for user " + userId + ":");
18200                            pw.println();
18201                            count = 0;
18202                            for (PackageSetting ps : allPackageSettings) {
18203                                final long status = ps.getDomainVerificationStatusForUser(userId);
18204                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18205                                    continue;
18206                                }
18207                                pw.println(prefix + "Package: " + ps.name);
18208                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18209                                String statusStr = IntentFilterVerificationInfo.
18210                                        getStatusStringFromValue(status);
18211                                pw.println(prefix + "Status:  " + statusStr);
18212                                pw.println();
18213                                count++;
18214                            }
18215                            if (count == 0) {
18216                                pw.println(prefix + "No configured app linkages.");
18217                                pw.println();
18218                            }
18219                        }
18220                    }
18221                }
18222            }
18223
18224            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18225                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18226                if (packageName == null && permissionNames == null) {
18227                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18228                        if (iperm == 0) {
18229                            if (dumpState.onTitlePrinted())
18230                                pw.println();
18231                            pw.println("AppOp Permissions:");
18232                        }
18233                        pw.print("  AppOp Permission ");
18234                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18235                        pw.println(":");
18236                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18237                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18238                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18239                        }
18240                    }
18241                }
18242            }
18243
18244            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18245                boolean printedSomething = false;
18246                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18247                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18248                        continue;
18249                    }
18250                    if (!printedSomething) {
18251                        if (dumpState.onTitlePrinted())
18252                            pw.println();
18253                        pw.println("Registered ContentProviders:");
18254                        printedSomething = true;
18255                    }
18256                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18257                    pw.print("    "); pw.println(p.toString());
18258                }
18259                printedSomething = false;
18260                for (Map.Entry<String, PackageParser.Provider> entry :
18261                        mProvidersByAuthority.entrySet()) {
18262                    PackageParser.Provider p = entry.getValue();
18263                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18264                        continue;
18265                    }
18266                    if (!printedSomething) {
18267                        if (dumpState.onTitlePrinted())
18268                            pw.println();
18269                        pw.println("ContentProvider Authorities:");
18270                        printedSomething = true;
18271                    }
18272                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18273                    pw.print("    "); pw.println(p.toString());
18274                    if (p.info != null && p.info.applicationInfo != null) {
18275                        final String appInfo = p.info.applicationInfo.toString();
18276                        pw.print("      applicationInfo="); pw.println(appInfo);
18277                    }
18278                }
18279            }
18280
18281            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18282                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18283            }
18284
18285            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18286                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18287            }
18288
18289            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18290                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18291            }
18292
18293            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18294                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18295            }
18296
18297            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18298                // XXX should handle packageName != null by dumping only install data that
18299                // the given package is involved with.
18300                if (dumpState.onTitlePrinted()) pw.println();
18301                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18302            }
18303
18304            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18305                // XXX should handle packageName != null by dumping only install data that
18306                // the given package is involved with.
18307                if (dumpState.onTitlePrinted()) pw.println();
18308
18309                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18310                ipw.println();
18311                ipw.println("Frozen packages:");
18312                ipw.increaseIndent();
18313                if (mFrozenPackages.size() == 0) {
18314                    ipw.println("(none)");
18315                } else {
18316                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18317                        ipw.println(mFrozenPackages.valueAt(i));
18318                    }
18319                }
18320                ipw.decreaseIndent();
18321            }
18322
18323            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18324                if (dumpState.onTitlePrinted()) pw.println();
18325                mSettings.dumpReadMessagesLPr(pw, dumpState);
18326
18327                pw.println();
18328                pw.println("Package warning messages:");
18329                BufferedReader in = null;
18330                String line = null;
18331                try {
18332                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18333                    while ((line = in.readLine()) != null) {
18334                        if (line.contains("ignored: updated version")) continue;
18335                        pw.println(line);
18336                    }
18337                } catch (IOException ignored) {
18338                } finally {
18339                    IoUtils.closeQuietly(in);
18340                }
18341            }
18342
18343            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18344                BufferedReader in = null;
18345                String line = null;
18346                try {
18347                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18348                    while ((line = in.readLine()) != null) {
18349                        if (line.contains("ignored: updated version")) continue;
18350                        pw.print("msg,");
18351                        pw.println(line);
18352                    }
18353                } catch (IOException ignored) {
18354                } finally {
18355                    IoUtils.closeQuietly(in);
18356                }
18357            }
18358        }
18359    }
18360
18361    private String dumpDomainString(String packageName) {
18362        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18363                .getList();
18364        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18365
18366        ArraySet<String> result = new ArraySet<>();
18367        if (iviList.size() > 0) {
18368            for (IntentFilterVerificationInfo ivi : iviList) {
18369                for (String host : ivi.getDomains()) {
18370                    result.add(host);
18371                }
18372            }
18373        }
18374        if (filters != null && filters.size() > 0) {
18375            for (IntentFilter filter : filters) {
18376                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18377                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18378                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18379                    result.addAll(filter.getHostsList());
18380                }
18381            }
18382        }
18383
18384        StringBuilder sb = new StringBuilder(result.size() * 16);
18385        for (String domain : result) {
18386            if (sb.length() > 0) sb.append(" ");
18387            sb.append(domain);
18388        }
18389        return sb.toString();
18390    }
18391
18392    // ------- apps on sdcard specific code -------
18393    static final boolean DEBUG_SD_INSTALL = false;
18394
18395    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18396
18397    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18398
18399    private boolean mMediaMounted = false;
18400
18401    static String getEncryptKey() {
18402        try {
18403            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18404                    SD_ENCRYPTION_KEYSTORE_NAME);
18405            if (sdEncKey == null) {
18406                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18407                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18408                if (sdEncKey == null) {
18409                    Slog.e(TAG, "Failed to create encryption keys");
18410                    return null;
18411                }
18412            }
18413            return sdEncKey;
18414        } catch (NoSuchAlgorithmException nsae) {
18415            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18416            return null;
18417        } catch (IOException ioe) {
18418            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18419            return null;
18420        }
18421    }
18422
18423    /*
18424     * Update media status on PackageManager.
18425     */
18426    @Override
18427    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18428        int callingUid = Binder.getCallingUid();
18429        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18430            throw new SecurityException("Media status can only be updated by the system");
18431        }
18432        // reader; this apparently protects mMediaMounted, but should probably
18433        // be a different lock in that case.
18434        synchronized (mPackages) {
18435            Log.i(TAG, "Updating external media status from "
18436                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18437                    + (mediaStatus ? "mounted" : "unmounted"));
18438            if (DEBUG_SD_INSTALL)
18439                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18440                        + ", mMediaMounted=" + mMediaMounted);
18441            if (mediaStatus == mMediaMounted) {
18442                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18443                        : 0, -1);
18444                mHandler.sendMessage(msg);
18445                return;
18446            }
18447            mMediaMounted = mediaStatus;
18448        }
18449        // Queue up an async operation since the package installation may take a
18450        // little while.
18451        mHandler.post(new Runnable() {
18452            public void run() {
18453                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18454            }
18455        });
18456    }
18457
18458    /**
18459     * Called by MountService when the initial ASECs to scan are available.
18460     * Should block until all the ASEC containers are finished being scanned.
18461     */
18462    public void scanAvailableAsecs() {
18463        updateExternalMediaStatusInner(true, false, false);
18464    }
18465
18466    /*
18467     * Collect information of applications on external media, map them against
18468     * existing containers and update information based on current mount status.
18469     * Please note that we always have to report status if reportStatus has been
18470     * set to true especially when unloading packages.
18471     */
18472    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18473            boolean externalStorage) {
18474        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18475        int[] uidArr = EmptyArray.INT;
18476
18477        final String[] list = PackageHelper.getSecureContainerList();
18478        if (ArrayUtils.isEmpty(list)) {
18479            Log.i(TAG, "No secure containers found");
18480        } else {
18481            // Process list of secure containers and categorize them
18482            // as active or stale based on their package internal state.
18483
18484            // reader
18485            synchronized (mPackages) {
18486                for (String cid : list) {
18487                    // Leave stages untouched for now; installer service owns them
18488                    if (PackageInstallerService.isStageName(cid)) continue;
18489
18490                    if (DEBUG_SD_INSTALL)
18491                        Log.i(TAG, "Processing container " + cid);
18492                    String pkgName = getAsecPackageName(cid);
18493                    if (pkgName == null) {
18494                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18495                        continue;
18496                    }
18497                    if (DEBUG_SD_INSTALL)
18498                        Log.i(TAG, "Looking for pkg : " + pkgName);
18499
18500                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18501                    if (ps == null) {
18502                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18503                        continue;
18504                    }
18505
18506                    /*
18507                     * Skip packages that are not external if we're unmounting
18508                     * external storage.
18509                     */
18510                    if (externalStorage && !isMounted && !isExternal(ps)) {
18511                        continue;
18512                    }
18513
18514                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18515                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18516                    // The package status is changed only if the code path
18517                    // matches between settings and the container id.
18518                    if (ps.codePathString != null
18519                            && ps.codePathString.startsWith(args.getCodePath())) {
18520                        if (DEBUG_SD_INSTALL) {
18521                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18522                                    + " at code path: " + ps.codePathString);
18523                        }
18524
18525                        // We do have a valid package installed on sdcard
18526                        processCids.put(args, ps.codePathString);
18527                        final int uid = ps.appId;
18528                        if (uid != -1) {
18529                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18530                        }
18531                    } else {
18532                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18533                                + ps.codePathString);
18534                    }
18535                }
18536            }
18537
18538            Arrays.sort(uidArr);
18539        }
18540
18541        // Process packages with valid entries.
18542        if (isMounted) {
18543            if (DEBUG_SD_INSTALL)
18544                Log.i(TAG, "Loading packages");
18545            loadMediaPackages(processCids, uidArr, externalStorage);
18546            startCleaningPackages();
18547            mInstallerService.onSecureContainersAvailable();
18548        } else {
18549            if (DEBUG_SD_INSTALL)
18550                Log.i(TAG, "Unloading packages");
18551            unloadMediaPackages(processCids, uidArr, reportStatus);
18552        }
18553    }
18554
18555    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18556            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18557        final int size = infos.size();
18558        final String[] packageNames = new String[size];
18559        final int[] packageUids = new int[size];
18560        for (int i = 0; i < size; i++) {
18561            final ApplicationInfo info = infos.get(i);
18562            packageNames[i] = info.packageName;
18563            packageUids[i] = info.uid;
18564        }
18565        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18566                finishedReceiver);
18567    }
18568
18569    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18570            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18571        sendResourcesChangedBroadcast(mediaStatus, replacing,
18572                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18573    }
18574
18575    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18576            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18577        int size = pkgList.length;
18578        if (size > 0) {
18579            // Send broadcasts here
18580            Bundle extras = new Bundle();
18581            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18582            if (uidArr != null) {
18583                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18584            }
18585            if (replacing) {
18586                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18587            }
18588            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18589                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18590            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18591        }
18592    }
18593
18594   /*
18595     * Look at potentially valid container ids from processCids If package
18596     * information doesn't match the one on record or package scanning fails,
18597     * the cid is added to list of removeCids. We currently don't delete stale
18598     * containers.
18599     */
18600    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18601            boolean externalStorage) {
18602        ArrayList<String> pkgList = new ArrayList<String>();
18603        Set<AsecInstallArgs> keys = processCids.keySet();
18604
18605        for (AsecInstallArgs args : keys) {
18606            String codePath = processCids.get(args);
18607            if (DEBUG_SD_INSTALL)
18608                Log.i(TAG, "Loading container : " + args.cid);
18609            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18610            try {
18611                // Make sure there are no container errors first.
18612                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18613                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18614                            + " when installing from sdcard");
18615                    continue;
18616                }
18617                // Check code path here.
18618                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18619                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18620                            + " does not match one in settings " + codePath);
18621                    continue;
18622                }
18623                // Parse package
18624                int parseFlags = mDefParseFlags;
18625                if (args.isExternalAsec()) {
18626                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18627                }
18628                if (args.isFwdLocked()) {
18629                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18630                }
18631
18632                synchronized (mInstallLock) {
18633                    PackageParser.Package pkg = null;
18634                    try {
18635                        // Sadly we don't know the package name yet to freeze it
18636                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18637                                SCAN_IGNORE_FROZEN, 0, null);
18638                    } catch (PackageManagerException e) {
18639                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18640                    }
18641                    // Scan the package
18642                    if (pkg != null) {
18643                        /*
18644                         * TODO why is the lock being held? doPostInstall is
18645                         * called in other places without the lock. This needs
18646                         * to be straightened out.
18647                         */
18648                        // writer
18649                        synchronized (mPackages) {
18650                            retCode = PackageManager.INSTALL_SUCCEEDED;
18651                            pkgList.add(pkg.packageName);
18652                            // Post process args
18653                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18654                                    pkg.applicationInfo.uid);
18655                        }
18656                    } else {
18657                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18658                    }
18659                }
18660
18661            } finally {
18662                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18663                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18664                }
18665            }
18666        }
18667        // writer
18668        synchronized (mPackages) {
18669            // If the platform SDK has changed since the last time we booted,
18670            // we need to re-grant app permission to catch any new ones that
18671            // appear. This is really a hack, and means that apps can in some
18672            // cases get permissions that the user didn't initially explicitly
18673            // allow... it would be nice to have some better way to handle
18674            // this situation.
18675            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18676                    : mSettings.getInternalVersion();
18677            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18678                    : StorageManager.UUID_PRIVATE_INTERNAL;
18679
18680            int updateFlags = UPDATE_PERMISSIONS_ALL;
18681            if (ver.sdkVersion != mSdkVersion) {
18682                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18683                        + mSdkVersion + "; regranting permissions for external");
18684                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18685            }
18686            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18687
18688            // Yay, everything is now upgraded
18689            ver.forceCurrent();
18690
18691            // can downgrade to reader
18692            // Persist settings
18693            mSettings.writeLPr();
18694        }
18695        // Send a broadcast to let everyone know we are done processing
18696        if (pkgList.size() > 0) {
18697            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18698        }
18699    }
18700
18701   /*
18702     * Utility method to unload a list of specified containers
18703     */
18704    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18705        // Just unmount all valid containers.
18706        for (AsecInstallArgs arg : cidArgs) {
18707            synchronized (mInstallLock) {
18708                arg.doPostDeleteLI(false);
18709           }
18710       }
18711   }
18712
18713    /*
18714     * Unload packages mounted on external media. This involves deleting package
18715     * data from internal structures, sending broadcasts about disabled packages,
18716     * gc'ing to free up references, unmounting all secure containers
18717     * corresponding to packages on external media, and posting a
18718     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18719     * that we always have to post this message if status has been requested no
18720     * matter what.
18721     */
18722    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18723            final boolean reportStatus) {
18724        if (DEBUG_SD_INSTALL)
18725            Log.i(TAG, "unloading media packages");
18726        ArrayList<String> pkgList = new ArrayList<String>();
18727        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18728        final Set<AsecInstallArgs> keys = processCids.keySet();
18729        for (AsecInstallArgs args : keys) {
18730            String pkgName = args.getPackageName();
18731            if (DEBUG_SD_INSTALL)
18732                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18733            // Delete package internally
18734            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18735            synchronized (mInstallLock) {
18736                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18737                final boolean res;
18738                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18739                        "unloadMediaPackages")) {
18740                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18741                            null);
18742                }
18743                if (res) {
18744                    pkgList.add(pkgName);
18745                } else {
18746                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18747                    failedList.add(args);
18748                }
18749            }
18750        }
18751
18752        // reader
18753        synchronized (mPackages) {
18754            // We didn't update the settings after removing each package;
18755            // write them now for all packages.
18756            mSettings.writeLPr();
18757        }
18758
18759        // We have to absolutely send UPDATED_MEDIA_STATUS only
18760        // after confirming that all the receivers processed the ordered
18761        // broadcast when packages get disabled, force a gc to clean things up.
18762        // and unload all the containers.
18763        if (pkgList.size() > 0) {
18764            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18765                    new IIntentReceiver.Stub() {
18766                public void performReceive(Intent intent, int resultCode, String data,
18767                        Bundle extras, boolean ordered, boolean sticky,
18768                        int sendingUser) throws RemoteException {
18769                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18770                            reportStatus ? 1 : 0, 1, keys);
18771                    mHandler.sendMessage(msg);
18772                }
18773            });
18774        } else {
18775            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18776                    keys);
18777            mHandler.sendMessage(msg);
18778        }
18779    }
18780
18781    private void loadPrivatePackages(final VolumeInfo vol) {
18782        mHandler.post(new Runnable() {
18783            @Override
18784            public void run() {
18785                loadPrivatePackagesInner(vol);
18786            }
18787        });
18788    }
18789
18790    private void loadPrivatePackagesInner(VolumeInfo vol) {
18791        final String volumeUuid = vol.fsUuid;
18792        if (TextUtils.isEmpty(volumeUuid)) {
18793            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18794            return;
18795        }
18796
18797        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18798        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18799        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18800
18801        final VersionInfo ver;
18802        final List<PackageSetting> packages;
18803        synchronized (mPackages) {
18804            ver = mSettings.findOrCreateVersion(volumeUuid);
18805            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18806        }
18807
18808        for (PackageSetting ps : packages) {
18809            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18810            synchronized (mInstallLock) {
18811                final PackageParser.Package pkg;
18812                try {
18813                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18814                    loaded.add(pkg.applicationInfo);
18815
18816                } catch (PackageManagerException e) {
18817                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18818                }
18819
18820                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18821                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18822                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18823                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18824                }
18825            }
18826        }
18827
18828        // Reconcile app data for all started/unlocked users
18829        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18830        final UserManager um = mContext.getSystemService(UserManager.class);
18831        for (UserInfo user : um.getUsers()) {
18832            final int flags;
18833            if (um.isUserUnlockingOrUnlocked(user.id)) {
18834                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18835            } else if (um.isUserRunning(user.id)) {
18836                flags = StorageManager.FLAG_STORAGE_DE;
18837            } else {
18838                continue;
18839            }
18840
18841            try {
18842                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18843                synchronized (mInstallLock) {
18844                    reconcileAppsDataLI(volumeUuid, user.id, flags);
18845                }
18846            } catch (IllegalStateException e) {
18847                // Device was probably ejected, and we'll process that event momentarily
18848                Slog.w(TAG, "Failed to prepare storage: " + e);
18849            }
18850        }
18851
18852        synchronized (mPackages) {
18853            int updateFlags = UPDATE_PERMISSIONS_ALL;
18854            if (ver.sdkVersion != mSdkVersion) {
18855                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18856                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18857                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18858            }
18859            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18860
18861            // Yay, everything is now upgraded
18862            ver.forceCurrent();
18863
18864            mSettings.writeLPr();
18865        }
18866
18867        for (PackageFreezer freezer : freezers) {
18868            freezer.close();
18869        }
18870
18871        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18872        sendResourcesChangedBroadcast(true, false, loaded, null);
18873    }
18874
18875    private void unloadPrivatePackages(final VolumeInfo vol) {
18876        mHandler.post(new Runnable() {
18877            @Override
18878            public void run() {
18879                unloadPrivatePackagesInner(vol);
18880            }
18881        });
18882    }
18883
18884    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18885        final String volumeUuid = vol.fsUuid;
18886        if (TextUtils.isEmpty(volumeUuid)) {
18887            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18888            return;
18889        }
18890
18891        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18892        synchronized (mInstallLock) {
18893        synchronized (mPackages) {
18894            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18895            for (PackageSetting ps : packages) {
18896                if (ps.pkg == null) continue;
18897
18898                final ApplicationInfo info = ps.pkg.applicationInfo;
18899                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18900                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18901
18902                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
18903                        "unloadPrivatePackagesInner")) {
18904                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
18905                            false, null)) {
18906                        unloaded.add(info);
18907                    } else {
18908                        Slog.w(TAG, "Failed to unload " + ps.codePath);
18909                    }
18910                }
18911            }
18912
18913            mSettings.writeLPr();
18914        }
18915        }
18916
18917        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18918        sendResourcesChangedBroadcast(false, false, unloaded, null);
18919    }
18920
18921    /**
18922     * Prepare storage areas for given user on all mounted devices.
18923     */
18924    void prepareUserData(int userId, int userSerial, int flags) {
18925        synchronized (mInstallLock) {
18926            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18927            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18928                final String volumeUuid = vol.getFsUuid();
18929                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
18930            }
18931        }
18932    }
18933
18934    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
18935            boolean allowRecover) {
18936        // Prepare storage and verify that serial numbers are consistent; if
18937        // there's a mismatch we need to destroy to avoid leaking data
18938        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18939        try {
18940            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
18941
18942            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
18943                UserManagerService.enforceSerialNumber(
18944                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
18945            }
18946            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
18947                UserManagerService.enforceSerialNumber(
18948                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
18949            }
18950
18951            synchronized (mInstallLock) {
18952                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
18953            }
18954        } catch (Exception e) {
18955            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
18956                    + " because we failed to prepare: " + e);
18957            destroyUserDataLI(volumeUuid, userId,
18958                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18959
18960            if (allowRecover) {
18961                // Try one last time; if we fail again we're really in trouble
18962                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
18963            }
18964        }
18965    }
18966
18967    /**
18968     * Destroy storage areas for given user on all mounted devices.
18969     */
18970    void destroyUserData(int userId, int flags) {
18971        synchronized (mInstallLock) {
18972            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18973            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18974                final String volumeUuid = vol.getFsUuid();
18975                destroyUserDataLI(volumeUuid, userId, flags);
18976            }
18977        }
18978    }
18979
18980    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
18981        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18982        try {
18983            // Clean up app data, profile data, and media data
18984            mInstaller.destroyUserData(volumeUuid, userId, flags);
18985
18986            // Clean up system data
18987            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
18988                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18989                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
18990                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
18991                }
18992                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18993                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
18994                }
18995            }
18996
18997            // Data with special labels is now gone, so finish the job
18998            storage.destroyUserStorage(volumeUuid, userId, flags);
18999
19000        } catch (Exception e) {
19001            logCriticalInfo(Log.WARN,
19002                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19003        }
19004    }
19005
19006    /**
19007     * Examine all users present on given mounted volume, and destroy data
19008     * belonging to users that are no longer valid, or whose user ID has been
19009     * recycled.
19010     */
19011    private void reconcileUsers(String volumeUuid) {
19012        final List<File> files = new ArrayList<>();
19013        Collections.addAll(files, FileUtils
19014                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19015        Collections.addAll(files, FileUtils
19016                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19017        for (File file : files) {
19018            if (!file.isDirectory()) continue;
19019
19020            final int userId;
19021            final UserInfo info;
19022            try {
19023                userId = Integer.parseInt(file.getName());
19024                info = sUserManager.getUserInfo(userId);
19025            } catch (NumberFormatException e) {
19026                Slog.w(TAG, "Invalid user directory " + file);
19027                continue;
19028            }
19029
19030            boolean destroyUser = false;
19031            if (info == null) {
19032                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19033                        + " because no matching user was found");
19034                destroyUser = true;
19035            } else if (!mOnlyCore) {
19036                try {
19037                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19038                } catch (IOException e) {
19039                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19040                            + " because we failed to enforce serial number: " + e);
19041                    destroyUser = true;
19042                }
19043            }
19044
19045            if (destroyUser) {
19046                synchronized (mInstallLock) {
19047                    destroyUserDataLI(volumeUuid, userId,
19048                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19049                }
19050            }
19051        }
19052    }
19053
19054    private void assertPackageKnown(String volumeUuid, String packageName)
19055            throws PackageManagerException {
19056        synchronized (mPackages) {
19057            final PackageSetting ps = mSettings.mPackages.get(packageName);
19058            if (ps == null) {
19059                throw new PackageManagerException("Package " + packageName + " is unknown");
19060            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19061                throw new PackageManagerException(
19062                        "Package " + packageName + " found on unknown volume " + volumeUuid
19063                                + "; expected volume " + ps.volumeUuid);
19064            }
19065        }
19066    }
19067
19068    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19069            throws PackageManagerException {
19070        synchronized (mPackages) {
19071            final PackageSetting ps = mSettings.mPackages.get(packageName);
19072            if (ps == null) {
19073                throw new PackageManagerException("Package " + packageName + " is unknown");
19074            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19075                throw new PackageManagerException(
19076                        "Package " + packageName + " found on unknown volume " + volumeUuid
19077                                + "; expected volume " + ps.volumeUuid);
19078            } else if (!ps.getInstalled(userId)) {
19079                throw new PackageManagerException(
19080                        "Package " + packageName + " not installed for user " + userId);
19081            }
19082        }
19083    }
19084
19085    /**
19086     * Examine all apps present on given mounted volume, and destroy apps that
19087     * aren't expected, either due to uninstallation or reinstallation on
19088     * another volume.
19089     */
19090    private void reconcileApps(String volumeUuid) {
19091        final File[] files = FileUtils
19092                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19093        for (File file : files) {
19094            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19095                    && !PackageInstallerService.isStageName(file.getName());
19096            if (!isPackage) {
19097                // Ignore entries which are not packages
19098                continue;
19099            }
19100
19101            try {
19102                final PackageLite pkg = PackageParser.parsePackageLite(file,
19103                        PackageParser.PARSE_MUST_BE_APK);
19104                assertPackageKnown(volumeUuid, pkg.packageName);
19105
19106            } catch (PackageParserException | PackageManagerException e) {
19107                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19108                synchronized (mInstallLock) {
19109                    removeCodePathLI(file);
19110                }
19111            }
19112        }
19113    }
19114
19115    /**
19116     * Reconcile all app data for the given user.
19117     * <p>
19118     * Verifies that directories exist and that ownership and labeling is
19119     * correct for all installed apps on all mounted volumes.
19120     */
19121    void reconcileAppsData(int userId, int flags) {
19122        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19123        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19124            final String volumeUuid = vol.getFsUuid();
19125            synchronized (mInstallLock) {
19126                reconcileAppsDataLI(volumeUuid, userId, flags);
19127            }
19128        }
19129    }
19130
19131    /**
19132     * Reconcile all app data on given mounted volume.
19133     * <p>
19134     * Destroys app data that isn't expected, either due to uninstallation or
19135     * reinstallation on another volume.
19136     * <p>
19137     * Verifies that directories exist and that ownership and labeling is
19138     * correct for all installed apps.
19139     */
19140    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19141        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19142                + Integer.toHexString(flags));
19143
19144        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19145        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19146
19147        boolean restoreconNeeded = false;
19148
19149        // First look for stale data that doesn't belong, and check if things
19150        // have changed since we did our last restorecon
19151        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19152            if (StorageManager.isFileEncryptedNativeOrEmulated()
19153                    && !StorageManager.isUserKeyUnlocked(userId)) {
19154                throw new RuntimeException(
19155                        "Yikes, someone asked us to reconcile CE storage while " + userId
19156                                + " was still locked; this would have caused massive data loss!");
19157            }
19158
19159            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19160
19161            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19162            for (File file : files) {
19163                final String packageName = file.getName();
19164                try {
19165                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19166                } catch (PackageManagerException e) {
19167                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19168                    try {
19169                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19170                                StorageManager.FLAG_STORAGE_CE, 0);
19171                    } catch (InstallerException e2) {
19172                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19173                    }
19174                }
19175            }
19176        }
19177        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19178            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19179
19180            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19181            for (File file : files) {
19182                final String packageName = file.getName();
19183                try {
19184                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19185                } catch (PackageManagerException e) {
19186                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19187                    try {
19188                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19189                                StorageManager.FLAG_STORAGE_DE, 0);
19190                    } catch (InstallerException e2) {
19191                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19192                    }
19193                }
19194            }
19195        }
19196
19197        // Ensure that data directories are ready to roll for all packages
19198        // installed for this volume and user
19199        final List<PackageSetting> packages;
19200        synchronized (mPackages) {
19201            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19202        }
19203        int preparedCount = 0;
19204        for (PackageSetting ps : packages) {
19205            final String packageName = ps.name;
19206            if (ps.pkg == null) {
19207                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19208                // TODO: might be due to legacy ASEC apps; we should circle back
19209                // and reconcile again once they're scanned
19210                continue;
19211            }
19212
19213            if (ps.getInstalled(userId)) {
19214                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19215
19216                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19217                    // We may have just shuffled around app data directories, so
19218                    // prepare them one more time
19219                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19220                }
19221
19222                preparedCount++;
19223            }
19224        }
19225
19226        if (restoreconNeeded) {
19227            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19228                SELinuxMMAC.setRestoreconDone(ceDir);
19229            }
19230            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19231                SELinuxMMAC.setRestoreconDone(deDir);
19232            }
19233        }
19234
19235        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19236                + " packages; restoreconNeeded was " + restoreconNeeded);
19237    }
19238
19239    /**
19240     * Prepare app data for the given app just after it was installed or
19241     * upgraded. This method carefully only touches users that it's installed
19242     * for, and it forces a restorecon to handle any seinfo changes.
19243     * <p>
19244     * Verifies that directories exist and that ownership and labeling is
19245     * correct for all installed apps. If there is an ownership mismatch, it
19246     * will try recovering system apps by wiping data; third-party app data is
19247     * left intact.
19248     * <p>
19249     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19250     */
19251    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19252        final PackageSetting ps;
19253        synchronized (mPackages) {
19254            ps = mSettings.mPackages.get(pkg.packageName);
19255            mSettings.writeKernelMappingLPr(ps);
19256        }
19257
19258        final UserManager um = mContext.getSystemService(UserManager.class);
19259        for (UserInfo user : um.getUsers()) {
19260            final int flags;
19261            if (um.isUserUnlockingOrUnlocked(user.id)) {
19262                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19263            } else if (um.isUserRunning(user.id)) {
19264                flags = StorageManager.FLAG_STORAGE_DE;
19265            } else {
19266                continue;
19267            }
19268
19269            if (ps.getInstalled(user.id)) {
19270                // Whenever an app changes, force a restorecon of its data
19271                // TODO: when user data is locked, mark that we're still dirty
19272                prepareAppDataLIF(pkg, user.id, flags, true);
19273            }
19274        }
19275    }
19276
19277    /**
19278     * Prepare app data for the given app.
19279     * <p>
19280     * Verifies that directories exist and that ownership and labeling is
19281     * correct for all installed apps. If there is an ownership mismatch, this
19282     * will try recovering system apps by wiping data; third-party app data is
19283     * left intact.
19284     */
19285    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19286            boolean restoreconNeeded) {
19287        if (pkg == null) {
19288            Slog.wtf(TAG, "Package was null!", new Throwable());
19289            return;
19290        }
19291        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19292        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19293        for (int i = 0; i < childCount; i++) {
19294            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19295        }
19296    }
19297
19298    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19299            boolean restoreconNeeded) {
19300        if (DEBUG_APP_DATA) {
19301            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19302                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19303        }
19304
19305        final String volumeUuid = pkg.volumeUuid;
19306        final String packageName = pkg.packageName;
19307        final ApplicationInfo app = pkg.applicationInfo;
19308        final int appId = UserHandle.getAppId(app.uid);
19309
19310        Preconditions.checkNotNull(app.seinfo);
19311
19312        try {
19313            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19314                    appId, app.seinfo, app.targetSdkVersion);
19315        } catch (InstallerException e) {
19316            if (app.isSystemApp()) {
19317                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19318                        + ", but trying to recover: " + e);
19319                destroyAppDataLeafLIF(pkg, userId, flags);
19320                try {
19321                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19322                            appId, app.seinfo, app.targetSdkVersion);
19323                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19324                } catch (InstallerException e2) {
19325                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19326                }
19327            } else {
19328                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19329            }
19330        }
19331
19332        if (restoreconNeeded) {
19333            try {
19334                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19335                        app.seinfo);
19336            } catch (InstallerException e) {
19337                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19338            }
19339        }
19340
19341        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19342            try {
19343                // CE storage is unlocked right now, so read out the inode and
19344                // remember for use later when it's locked
19345                // TODO: mark this structure as dirty so we persist it!
19346                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19347                        StorageManager.FLAG_STORAGE_CE);
19348                synchronized (mPackages) {
19349                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19350                    if (ps != null) {
19351                        ps.setCeDataInode(ceDataInode, userId);
19352                    }
19353                }
19354            } catch (InstallerException e) {
19355                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19356            }
19357        }
19358
19359        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19360    }
19361
19362    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19363        if (pkg == null) {
19364            Slog.wtf(TAG, "Package was null!", new Throwable());
19365            return;
19366        }
19367        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19368        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19369        for (int i = 0; i < childCount; i++) {
19370            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19371        }
19372    }
19373
19374    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19375        final String volumeUuid = pkg.volumeUuid;
19376        final String packageName = pkg.packageName;
19377        final ApplicationInfo app = pkg.applicationInfo;
19378
19379        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19380            // Create a native library symlink only if we have native libraries
19381            // and if the native libraries are 32 bit libraries. We do not provide
19382            // this symlink for 64 bit libraries.
19383            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19384                final String nativeLibPath = app.nativeLibraryDir;
19385                try {
19386                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19387                            nativeLibPath, userId);
19388                } catch (InstallerException e) {
19389                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19390                }
19391            }
19392        }
19393    }
19394
19395    /**
19396     * For system apps on non-FBE devices, this method migrates any existing
19397     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19398     * requested by the app.
19399     */
19400    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19401        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19402                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19403            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19404                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19405            try {
19406                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19407                        storageTarget);
19408            } catch (InstallerException e) {
19409                logCriticalInfo(Log.WARN,
19410                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19411            }
19412            return true;
19413        } else {
19414            return false;
19415        }
19416    }
19417
19418    public PackageFreezer freezePackage(String packageName, String killReason) {
19419        return new PackageFreezer(packageName, killReason);
19420    }
19421
19422    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19423            String killReason) {
19424        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19425            return new PackageFreezer();
19426        } else {
19427            return freezePackage(packageName, killReason);
19428        }
19429    }
19430
19431    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19432            String killReason) {
19433        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19434            return new PackageFreezer();
19435        } else {
19436            return freezePackage(packageName, killReason);
19437        }
19438    }
19439
19440    /**
19441     * Class that freezes and kills the given package upon creation, and
19442     * unfreezes it upon closing. This is typically used when doing surgery on
19443     * app code/data to prevent the app from running while you're working.
19444     */
19445    private class PackageFreezer implements AutoCloseable {
19446        private final String mPackageName;
19447        private final PackageFreezer[] mChildren;
19448
19449        private final boolean mWeFroze;
19450
19451        private final AtomicBoolean mClosed = new AtomicBoolean();
19452        private final CloseGuard mCloseGuard = CloseGuard.get();
19453
19454        /**
19455         * Create and return a stub freezer that doesn't actually do anything,
19456         * typically used when someone requested
19457         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19458         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19459         */
19460        public PackageFreezer() {
19461            mPackageName = null;
19462            mChildren = null;
19463            mWeFroze = false;
19464            mCloseGuard.open("close");
19465        }
19466
19467        public PackageFreezer(String packageName, String killReason) {
19468            synchronized (mPackages) {
19469                mPackageName = packageName;
19470                mWeFroze = mFrozenPackages.add(mPackageName);
19471
19472                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19473                if (ps != null) {
19474                    killApplication(ps.name, ps.appId, killReason);
19475                }
19476
19477                final PackageParser.Package p = mPackages.get(packageName);
19478                if (p != null && p.childPackages != null) {
19479                    final int N = p.childPackages.size();
19480                    mChildren = new PackageFreezer[N];
19481                    for (int i = 0; i < N; i++) {
19482                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19483                                killReason);
19484                    }
19485                } else {
19486                    mChildren = null;
19487                }
19488            }
19489            mCloseGuard.open("close");
19490        }
19491
19492        @Override
19493        protected void finalize() throws Throwable {
19494            try {
19495                mCloseGuard.warnIfOpen();
19496                close();
19497            } finally {
19498                super.finalize();
19499            }
19500        }
19501
19502        @Override
19503        public void close() {
19504            mCloseGuard.close();
19505            if (mClosed.compareAndSet(false, true)) {
19506                synchronized (mPackages) {
19507                    if (mWeFroze) {
19508                        mFrozenPackages.remove(mPackageName);
19509                    }
19510
19511                    if (mChildren != null) {
19512                        for (PackageFreezer freezer : mChildren) {
19513                            freezer.close();
19514                        }
19515                    }
19516                }
19517            }
19518        }
19519    }
19520
19521    /**
19522     * Verify that given package is currently frozen.
19523     */
19524    private void checkPackageFrozen(String packageName) {
19525        synchronized (mPackages) {
19526            if (!mFrozenPackages.contains(packageName)) {
19527                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19528            }
19529        }
19530    }
19531
19532    @Override
19533    public int movePackage(final String packageName, final String volumeUuid) {
19534        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19535
19536        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19537        final int moveId = mNextMoveId.getAndIncrement();
19538        mHandler.post(new Runnable() {
19539            @Override
19540            public void run() {
19541                try {
19542                    movePackageInternal(packageName, volumeUuid, moveId, user);
19543                } catch (PackageManagerException e) {
19544                    Slog.w(TAG, "Failed to move " + packageName, e);
19545                    mMoveCallbacks.notifyStatusChanged(moveId,
19546                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19547                }
19548            }
19549        });
19550        return moveId;
19551    }
19552
19553    private void movePackageInternal(final String packageName, final String volumeUuid,
19554            final int moveId, UserHandle user) throws PackageManagerException {
19555        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19556        final PackageManager pm = mContext.getPackageManager();
19557
19558        final boolean currentAsec;
19559        final String currentVolumeUuid;
19560        final File codeFile;
19561        final String installerPackageName;
19562        final String packageAbiOverride;
19563        final int appId;
19564        final String seinfo;
19565        final String label;
19566        final int targetSdkVersion;
19567        final PackageFreezer freezer;
19568
19569        // reader
19570        synchronized (mPackages) {
19571            final PackageParser.Package pkg = mPackages.get(packageName);
19572            final PackageSetting ps = mSettings.mPackages.get(packageName);
19573            if (pkg == null || ps == null) {
19574                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19575            }
19576
19577            if (pkg.applicationInfo.isSystemApp()) {
19578                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19579                        "Cannot move system application");
19580            }
19581
19582            if (pkg.applicationInfo.isExternalAsec()) {
19583                currentAsec = true;
19584                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19585            } else if (pkg.applicationInfo.isForwardLocked()) {
19586                currentAsec = true;
19587                currentVolumeUuid = "forward_locked";
19588            } else {
19589                currentAsec = false;
19590                currentVolumeUuid = ps.volumeUuid;
19591
19592                final File probe = new File(pkg.codePath);
19593                final File probeOat = new File(probe, "oat");
19594                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19595                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19596                            "Move only supported for modern cluster style installs");
19597                }
19598            }
19599
19600            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19601                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19602                        "Package already moved to " + volumeUuid);
19603            }
19604            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19605                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19606                        "Device admin cannot be moved");
19607            }
19608
19609            if (mFrozenPackages.contains(packageName)) {
19610                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19611                        "Failed to move already frozen package");
19612            }
19613
19614            codeFile = new File(pkg.codePath);
19615            installerPackageName = ps.installerPackageName;
19616            packageAbiOverride = ps.cpuAbiOverrideString;
19617            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19618            seinfo = pkg.applicationInfo.seinfo;
19619            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19620            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19621            freezer = new PackageFreezer(packageName, "movePackageInternal");
19622        }
19623
19624        final Bundle extras = new Bundle();
19625        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19626        extras.putString(Intent.EXTRA_TITLE, label);
19627        mMoveCallbacks.notifyCreated(moveId, extras);
19628
19629        int installFlags;
19630        final boolean moveCompleteApp;
19631        final File measurePath;
19632
19633        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19634            installFlags = INSTALL_INTERNAL;
19635            moveCompleteApp = !currentAsec;
19636            measurePath = Environment.getDataAppDirectory(volumeUuid);
19637        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19638            installFlags = INSTALL_EXTERNAL;
19639            moveCompleteApp = false;
19640            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19641        } else {
19642            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19643            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19644                    || !volume.isMountedWritable()) {
19645                freezer.close();
19646                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19647                        "Move location not mounted private volume");
19648            }
19649
19650            Preconditions.checkState(!currentAsec);
19651
19652            installFlags = INSTALL_INTERNAL;
19653            moveCompleteApp = true;
19654            measurePath = Environment.getDataAppDirectory(volumeUuid);
19655        }
19656
19657        final PackageStats stats = new PackageStats(null, -1);
19658        synchronized (mInstaller) {
19659            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19660                freezer.close();
19661                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19662                        "Failed to measure package size");
19663            }
19664        }
19665
19666        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19667                + stats.dataSize);
19668
19669        final long startFreeBytes = measurePath.getFreeSpace();
19670        final long sizeBytes;
19671        if (moveCompleteApp) {
19672            sizeBytes = stats.codeSize + stats.dataSize;
19673        } else {
19674            sizeBytes = stats.codeSize;
19675        }
19676
19677        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19678            freezer.close();
19679            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19680                    "Not enough free space to move");
19681        }
19682
19683        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19684
19685        final CountDownLatch installedLatch = new CountDownLatch(1);
19686        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19687            @Override
19688            public void onUserActionRequired(Intent intent) throws RemoteException {
19689                throw new IllegalStateException();
19690            }
19691
19692            @Override
19693            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19694                    Bundle extras) throws RemoteException {
19695                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19696                        + PackageManager.installStatusToString(returnCode, msg));
19697
19698                installedLatch.countDown();
19699                freezer.close();
19700
19701                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19702                switch (status) {
19703                    case PackageInstaller.STATUS_SUCCESS:
19704                        mMoveCallbacks.notifyStatusChanged(moveId,
19705                                PackageManager.MOVE_SUCCEEDED);
19706                        break;
19707                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19708                        mMoveCallbacks.notifyStatusChanged(moveId,
19709                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19710                        break;
19711                    default:
19712                        mMoveCallbacks.notifyStatusChanged(moveId,
19713                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19714                        break;
19715                }
19716            }
19717        };
19718
19719        final MoveInfo move;
19720        if (moveCompleteApp) {
19721            // Kick off a thread to report progress estimates
19722            new Thread() {
19723                @Override
19724                public void run() {
19725                    while (true) {
19726                        try {
19727                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19728                                break;
19729                            }
19730                        } catch (InterruptedException ignored) {
19731                        }
19732
19733                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19734                        final int progress = 10 + (int) MathUtils.constrain(
19735                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19736                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19737                    }
19738                }
19739            }.start();
19740
19741            final String dataAppName = codeFile.getName();
19742            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19743                    dataAppName, appId, seinfo, targetSdkVersion);
19744        } else {
19745            move = null;
19746        }
19747
19748        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19749
19750        final Message msg = mHandler.obtainMessage(INIT_COPY);
19751        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19752        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19753                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19754                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19755        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19756        msg.obj = params;
19757
19758        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19759                System.identityHashCode(msg.obj));
19760        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19761                System.identityHashCode(msg.obj));
19762
19763        mHandler.sendMessage(msg);
19764    }
19765
19766    @Override
19767    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19769
19770        final int realMoveId = mNextMoveId.getAndIncrement();
19771        final Bundle extras = new Bundle();
19772        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19773        mMoveCallbacks.notifyCreated(realMoveId, extras);
19774
19775        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19776            @Override
19777            public void onCreated(int moveId, Bundle extras) {
19778                // Ignored
19779            }
19780
19781            @Override
19782            public void onStatusChanged(int moveId, int status, long estMillis) {
19783                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19784            }
19785        };
19786
19787        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19788        storage.setPrimaryStorageUuid(volumeUuid, callback);
19789        return realMoveId;
19790    }
19791
19792    @Override
19793    public int getMoveStatus(int moveId) {
19794        mContext.enforceCallingOrSelfPermission(
19795                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19796        return mMoveCallbacks.mLastStatus.get(moveId);
19797    }
19798
19799    @Override
19800    public void registerMoveCallback(IPackageMoveObserver callback) {
19801        mContext.enforceCallingOrSelfPermission(
19802                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19803        mMoveCallbacks.register(callback);
19804    }
19805
19806    @Override
19807    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19808        mContext.enforceCallingOrSelfPermission(
19809                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19810        mMoveCallbacks.unregister(callback);
19811    }
19812
19813    @Override
19814    public boolean setInstallLocation(int loc) {
19815        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19816                null);
19817        if (getInstallLocation() == loc) {
19818            return true;
19819        }
19820        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19821                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19822            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19823                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19824            return true;
19825        }
19826        return false;
19827   }
19828
19829    @Override
19830    public int getInstallLocation() {
19831        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19832                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19833                PackageHelper.APP_INSTALL_AUTO);
19834    }
19835
19836    /** Called by UserManagerService */
19837    void cleanUpUser(UserManagerService userManager, int userHandle) {
19838        synchronized (mPackages) {
19839            mDirtyUsers.remove(userHandle);
19840            mUserNeedsBadging.delete(userHandle);
19841            mSettings.removeUserLPw(userHandle);
19842            mPendingBroadcasts.remove(userHandle);
19843            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19844            removeUnusedPackagesLPw(userManager, userHandle);
19845        }
19846    }
19847
19848    /**
19849     * We're removing userHandle and would like to remove any downloaded packages
19850     * that are no longer in use by any other user.
19851     * @param userHandle the user being removed
19852     */
19853    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19854        final boolean DEBUG_CLEAN_APKS = false;
19855        int [] users = userManager.getUserIds();
19856        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19857        while (psit.hasNext()) {
19858            PackageSetting ps = psit.next();
19859            if (ps.pkg == null) {
19860                continue;
19861            }
19862            final String packageName = ps.pkg.packageName;
19863            // Skip over if system app
19864            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19865                continue;
19866            }
19867            if (DEBUG_CLEAN_APKS) {
19868                Slog.i(TAG, "Checking package " + packageName);
19869            }
19870            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19871            if (keep) {
19872                if (DEBUG_CLEAN_APKS) {
19873                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19874                }
19875            } else {
19876                for (int i = 0; i < users.length; i++) {
19877                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19878                        keep = true;
19879                        if (DEBUG_CLEAN_APKS) {
19880                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19881                                    + users[i]);
19882                        }
19883                        break;
19884                    }
19885                }
19886            }
19887            if (!keep) {
19888                if (DEBUG_CLEAN_APKS) {
19889                    Slog.i(TAG, "  Removing package " + packageName);
19890                }
19891                mHandler.post(new Runnable() {
19892                    public void run() {
19893                        deletePackageX(packageName, userHandle, 0);
19894                    } //end run
19895                });
19896            }
19897        }
19898    }
19899
19900    /** Called by UserManagerService */
19901    void createNewUser(int userHandle) {
19902        synchronized (mInstallLock) {
19903            mSettings.createNewUserLI(this, mInstaller, userHandle);
19904        }
19905        synchronized (mPackages) {
19906            applyFactoryDefaultBrowserLPw(userHandle);
19907            primeDomainVerificationsLPw(userHandle);
19908        }
19909    }
19910
19911    void newUserCreated(final int userHandle) {
19912        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19913        // If permission review for legacy apps is required, we represent
19914        // dagerous permissions for such apps as always granted runtime
19915        // permissions to keep per user flag state whether review is needed.
19916        // Hence, if a new user is added we have to propagate dangerous
19917        // permission grants for these legacy apps.
19918        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19919            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19920                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19921        }
19922    }
19923
19924    @Override
19925    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19926        mContext.enforceCallingOrSelfPermission(
19927                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19928                "Only package verification agents can read the verifier device identity");
19929
19930        synchronized (mPackages) {
19931            return mSettings.getVerifierDeviceIdentityLPw();
19932        }
19933    }
19934
19935    @Override
19936    public void setPermissionEnforced(String permission, boolean enforced) {
19937        // TODO: Now that we no longer change GID for storage, this should to away.
19938        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19939                "setPermissionEnforced");
19940        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19941            synchronized (mPackages) {
19942                if (mSettings.mReadExternalStorageEnforced == null
19943                        || mSettings.mReadExternalStorageEnforced != enforced) {
19944                    mSettings.mReadExternalStorageEnforced = enforced;
19945                    mSettings.writeLPr();
19946                }
19947            }
19948            // kill any non-foreground processes so we restart them and
19949            // grant/revoke the GID.
19950            final IActivityManager am = ActivityManagerNative.getDefault();
19951            if (am != null) {
19952                final long token = Binder.clearCallingIdentity();
19953                try {
19954                    am.killProcessesBelowForeground("setPermissionEnforcement");
19955                } catch (RemoteException e) {
19956                } finally {
19957                    Binder.restoreCallingIdentity(token);
19958                }
19959            }
19960        } else {
19961            throw new IllegalArgumentException("No selective enforcement for " + permission);
19962        }
19963    }
19964
19965    @Override
19966    @Deprecated
19967    public boolean isPermissionEnforced(String permission) {
19968        return true;
19969    }
19970
19971    @Override
19972    public boolean isStorageLow() {
19973        final long token = Binder.clearCallingIdentity();
19974        try {
19975            final DeviceStorageMonitorInternal
19976                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19977            if (dsm != null) {
19978                return dsm.isMemoryLow();
19979            } else {
19980                return false;
19981            }
19982        } finally {
19983            Binder.restoreCallingIdentity(token);
19984        }
19985    }
19986
19987    @Override
19988    public IPackageInstaller getPackageInstaller() {
19989        return mInstallerService;
19990    }
19991
19992    private boolean userNeedsBadging(int userId) {
19993        int index = mUserNeedsBadging.indexOfKey(userId);
19994        if (index < 0) {
19995            final UserInfo userInfo;
19996            final long token = Binder.clearCallingIdentity();
19997            try {
19998                userInfo = sUserManager.getUserInfo(userId);
19999            } finally {
20000                Binder.restoreCallingIdentity(token);
20001            }
20002            final boolean b;
20003            if (userInfo != null && userInfo.isManagedProfile()) {
20004                b = true;
20005            } else {
20006                b = false;
20007            }
20008            mUserNeedsBadging.put(userId, b);
20009            return b;
20010        }
20011        return mUserNeedsBadging.valueAt(index);
20012    }
20013
20014    @Override
20015    public KeySet getKeySetByAlias(String packageName, String alias) {
20016        if (packageName == null || alias == null) {
20017            return null;
20018        }
20019        synchronized(mPackages) {
20020            final PackageParser.Package pkg = mPackages.get(packageName);
20021            if (pkg == null) {
20022                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20023                throw new IllegalArgumentException("Unknown package: " + packageName);
20024            }
20025            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20026            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20027        }
20028    }
20029
20030    @Override
20031    public KeySet getSigningKeySet(String packageName) {
20032        if (packageName == null) {
20033            return null;
20034        }
20035        synchronized(mPackages) {
20036            final PackageParser.Package pkg = mPackages.get(packageName);
20037            if (pkg == null) {
20038                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20039                throw new IllegalArgumentException("Unknown package: " + packageName);
20040            }
20041            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20042                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20043                throw new SecurityException("May not access signing KeySet of other apps.");
20044            }
20045            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20046            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20047        }
20048    }
20049
20050    @Override
20051    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20052        if (packageName == null || ks == null) {
20053            return false;
20054        }
20055        synchronized(mPackages) {
20056            final PackageParser.Package pkg = mPackages.get(packageName);
20057            if (pkg == null) {
20058                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20059                throw new IllegalArgumentException("Unknown package: " + packageName);
20060            }
20061            IBinder ksh = ks.getToken();
20062            if (ksh instanceof KeySetHandle) {
20063                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20064                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20065            }
20066            return false;
20067        }
20068    }
20069
20070    @Override
20071    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20072        if (packageName == null || ks == null) {
20073            return false;
20074        }
20075        synchronized(mPackages) {
20076            final PackageParser.Package pkg = mPackages.get(packageName);
20077            if (pkg == null) {
20078                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20079                throw new IllegalArgumentException("Unknown package: " + packageName);
20080            }
20081            IBinder ksh = ks.getToken();
20082            if (ksh instanceof KeySetHandle) {
20083                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20084                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20085            }
20086            return false;
20087        }
20088    }
20089
20090    private void deletePackageIfUnusedLPr(final String packageName) {
20091        PackageSetting ps = mSettings.mPackages.get(packageName);
20092        if (ps == null) {
20093            return;
20094        }
20095        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20096            // TODO Implement atomic delete if package is unused
20097            // It is currently possible that the package will be deleted even if it is installed
20098            // after this method returns.
20099            mHandler.post(new Runnable() {
20100                public void run() {
20101                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20102                }
20103            });
20104        }
20105    }
20106
20107    /**
20108     * Check and throw if the given before/after packages would be considered a
20109     * downgrade.
20110     */
20111    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20112            throws PackageManagerException {
20113        if (after.versionCode < before.mVersionCode) {
20114            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20115                    "Update version code " + after.versionCode + " is older than current "
20116                    + before.mVersionCode);
20117        } else if (after.versionCode == before.mVersionCode) {
20118            if (after.baseRevisionCode < before.baseRevisionCode) {
20119                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20120                        "Update base revision code " + after.baseRevisionCode
20121                        + " is older than current " + before.baseRevisionCode);
20122            }
20123
20124            if (!ArrayUtils.isEmpty(after.splitNames)) {
20125                for (int i = 0; i < after.splitNames.length; i++) {
20126                    final String splitName = after.splitNames[i];
20127                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20128                    if (j != -1) {
20129                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20130                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20131                                    "Update split " + splitName + " revision code "
20132                                    + after.splitRevisionCodes[i] + " is older than current "
20133                                    + before.splitRevisionCodes[j]);
20134                        }
20135                    }
20136                }
20137            }
20138        }
20139    }
20140
20141    private static class MoveCallbacks extends Handler {
20142        private static final int MSG_CREATED = 1;
20143        private static final int MSG_STATUS_CHANGED = 2;
20144
20145        private final RemoteCallbackList<IPackageMoveObserver>
20146                mCallbacks = new RemoteCallbackList<>();
20147
20148        private final SparseIntArray mLastStatus = new SparseIntArray();
20149
20150        public MoveCallbacks(Looper looper) {
20151            super(looper);
20152        }
20153
20154        public void register(IPackageMoveObserver callback) {
20155            mCallbacks.register(callback);
20156        }
20157
20158        public void unregister(IPackageMoveObserver callback) {
20159            mCallbacks.unregister(callback);
20160        }
20161
20162        @Override
20163        public void handleMessage(Message msg) {
20164            final SomeArgs args = (SomeArgs) msg.obj;
20165            final int n = mCallbacks.beginBroadcast();
20166            for (int i = 0; i < n; i++) {
20167                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20168                try {
20169                    invokeCallback(callback, msg.what, args);
20170                } catch (RemoteException ignored) {
20171                }
20172            }
20173            mCallbacks.finishBroadcast();
20174            args.recycle();
20175        }
20176
20177        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20178                throws RemoteException {
20179            switch (what) {
20180                case MSG_CREATED: {
20181                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20182                    break;
20183                }
20184                case MSG_STATUS_CHANGED: {
20185                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20186                    break;
20187                }
20188            }
20189        }
20190
20191        private void notifyCreated(int moveId, Bundle extras) {
20192            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20193
20194            final SomeArgs args = SomeArgs.obtain();
20195            args.argi1 = moveId;
20196            args.arg2 = extras;
20197            obtainMessage(MSG_CREATED, args).sendToTarget();
20198        }
20199
20200        private void notifyStatusChanged(int moveId, int status) {
20201            notifyStatusChanged(moveId, status, -1);
20202        }
20203
20204        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20205            Slog.v(TAG, "Move " + moveId + " status " + status);
20206
20207            final SomeArgs args = SomeArgs.obtain();
20208            args.argi1 = moveId;
20209            args.argi2 = status;
20210            args.arg3 = estMillis;
20211            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20212
20213            synchronized (mLastStatus) {
20214                mLastStatus.put(moveId, status);
20215            }
20216        }
20217    }
20218
20219    private final static class OnPermissionChangeListeners extends Handler {
20220        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20221
20222        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20223                new RemoteCallbackList<>();
20224
20225        public OnPermissionChangeListeners(Looper looper) {
20226            super(looper);
20227        }
20228
20229        @Override
20230        public void handleMessage(Message msg) {
20231            switch (msg.what) {
20232                case MSG_ON_PERMISSIONS_CHANGED: {
20233                    final int uid = msg.arg1;
20234                    handleOnPermissionsChanged(uid);
20235                } break;
20236            }
20237        }
20238
20239        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20240            mPermissionListeners.register(listener);
20241
20242        }
20243
20244        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20245            mPermissionListeners.unregister(listener);
20246        }
20247
20248        public void onPermissionsChanged(int uid) {
20249            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20250                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20251            }
20252        }
20253
20254        private void handleOnPermissionsChanged(int uid) {
20255            final int count = mPermissionListeners.beginBroadcast();
20256            try {
20257                for (int i = 0; i < count; i++) {
20258                    IOnPermissionsChangeListener callback = mPermissionListeners
20259                            .getBroadcastItem(i);
20260                    try {
20261                        callback.onPermissionsChanged(uid);
20262                    } catch (RemoteException e) {
20263                        Log.e(TAG, "Permission listener is dead", e);
20264                    }
20265                }
20266            } finally {
20267                mPermissionListeners.finishBroadcast();
20268            }
20269        }
20270    }
20271
20272    private class PackageManagerInternalImpl extends PackageManagerInternal {
20273        @Override
20274        public void setLocationPackagesProvider(PackagesProvider provider) {
20275            synchronized (mPackages) {
20276                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20277            }
20278        }
20279
20280        @Override
20281        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20282            synchronized (mPackages) {
20283                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20284            }
20285        }
20286
20287        @Override
20288        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20289            synchronized (mPackages) {
20290                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20291            }
20292        }
20293
20294        @Override
20295        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20296            synchronized (mPackages) {
20297                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20298            }
20299        }
20300
20301        @Override
20302        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20303            synchronized (mPackages) {
20304                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20305            }
20306        }
20307
20308        @Override
20309        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20310            synchronized (mPackages) {
20311                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20312            }
20313        }
20314
20315        @Override
20316        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20317            synchronized (mPackages) {
20318                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20319                        packageName, userId);
20320            }
20321        }
20322
20323        @Override
20324        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20325            synchronized (mPackages) {
20326                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20327                        packageName, userId);
20328            }
20329        }
20330
20331        @Override
20332        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20333            synchronized (mPackages) {
20334                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20335                        packageName, userId);
20336            }
20337        }
20338
20339        @Override
20340        public void setKeepUninstalledPackages(final List<String> packageList) {
20341            Preconditions.checkNotNull(packageList);
20342            List<String> removedFromList = null;
20343            synchronized (mPackages) {
20344                if (mKeepUninstalledPackages != null) {
20345                    final int packagesCount = mKeepUninstalledPackages.size();
20346                    for (int i = 0; i < packagesCount; i++) {
20347                        String oldPackage = mKeepUninstalledPackages.get(i);
20348                        if (packageList != null && packageList.contains(oldPackage)) {
20349                            continue;
20350                        }
20351                        if (removedFromList == null) {
20352                            removedFromList = new ArrayList<>();
20353                        }
20354                        removedFromList.add(oldPackage);
20355                    }
20356                }
20357                mKeepUninstalledPackages = new ArrayList<>(packageList);
20358                if (removedFromList != null) {
20359                    final int removedCount = removedFromList.size();
20360                    for (int i = 0; i < removedCount; i++) {
20361                        deletePackageIfUnusedLPr(removedFromList.get(i));
20362                    }
20363                }
20364            }
20365        }
20366
20367        @Override
20368        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20369            synchronized (mPackages) {
20370                // If we do not support permission review, done.
20371                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20372                    return false;
20373                }
20374
20375                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20376                if (packageSetting == null) {
20377                    return false;
20378                }
20379
20380                // Permission review applies only to apps not supporting the new permission model.
20381                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20382                    return false;
20383                }
20384
20385                // Legacy apps have the permission and get user consent on launch.
20386                PermissionsState permissionsState = packageSetting.getPermissionsState();
20387                return permissionsState.isPermissionReviewRequired(userId);
20388            }
20389        }
20390
20391        @Override
20392        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20393            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20394        }
20395
20396        @Override
20397        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20398                int userId) {
20399            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20400        }
20401    }
20402
20403    @Override
20404    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20405        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20406        synchronized (mPackages) {
20407            final long identity = Binder.clearCallingIdentity();
20408            try {
20409                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20410                        packageNames, userId);
20411            } finally {
20412                Binder.restoreCallingIdentity(identity);
20413            }
20414        }
20415    }
20416
20417    private static void enforceSystemOrPhoneCaller(String tag) {
20418        int callingUid = Binder.getCallingUid();
20419        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20420            throw new SecurityException(
20421                    "Cannot call " + tag + " from UID " + callingUid);
20422        }
20423    }
20424
20425    boolean isHistoricalPackageUsageAvailable() {
20426        return mPackageUsage.isHistoricalPackageUsageAvailable();
20427    }
20428
20429    /**
20430     * Return a <b>copy</b> of the collection of packages known to the package manager.
20431     * @return A copy of the values of mPackages.
20432     */
20433    Collection<PackageParser.Package> getPackages() {
20434        synchronized (mPackages) {
20435            return new ArrayList<>(mPackages.values());
20436        }
20437    }
20438
20439    /**
20440     * Logs process start information (including base APK hash) to the security log.
20441     * @hide
20442     */
20443    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20444            String apkFile, int pid) {
20445        if (!SecurityLog.isLoggingEnabled()) {
20446            return;
20447        }
20448        Bundle data = new Bundle();
20449        data.putLong("startTimestamp", System.currentTimeMillis());
20450        data.putString("processName", processName);
20451        data.putInt("uid", uid);
20452        data.putString("seinfo", seinfo);
20453        data.putString("apkFile", apkFile);
20454        data.putInt("pid", pid);
20455        Message msg = mProcessLoggingHandler.obtainMessage(
20456                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20457        msg.setData(data);
20458        mProcessLoggingHandler.sendMessage(msg);
20459    }
20460}
20461