PackageManagerService.java revision 295f5108f1984a4aade683ae73da3b69f0a29cc4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.Context;
113import android.content.IIntentReceiver;
114import android.content.Intent;
115import android.content.IntentFilter;
116import android.content.IntentSender;
117import android.content.IntentSender.SendIntentException;
118import android.content.ServiceConnection;
119import android.content.pm.ActivityInfo;
120import android.content.pm.ApplicationInfo;
121import android.content.pm.AppsQueryHelper;
122import android.content.pm.ComponentInfo;
123import android.content.pm.EphemeralApplicationInfo;
124import android.content.pm.EphemeralResolveInfo;
125import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
126import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
127import android.content.pm.FeatureInfo;
128import android.content.pm.IOnPermissionsChangeListener;
129import android.content.pm.IPackageDataObserver;
130import android.content.pm.IPackageDeleteObserver;
131import android.content.pm.IPackageDeleteObserver2;
132import android.content.pm.IPackageInstallObserver2;
133import android.content.pm.IPackageInstaller;
134import android.content.pm.IPackageManager;
135import android.content.pm.IPackageMoveObserver;
136import android.content.pm.IPackageStatsObserver;
137import android.content.pm.InstrumentationInfo;
138import android.content.pm.IntentFilterVerificationInfo;
139import android.content.pm.KeySet;
140import android.content.pm.PackageCleanItem;
141import android.content.pm.PackageInfo;
142import android.content.pm.PackageInfoLite;
143import android.content.pm.PackageInstaller;
144import android.content.pm.PackageManager;
145import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
146import android.content.pm.PackageManagerInternal;
147import android.content.pm.PackageParser;
148import android.content.pm.PackageParser.ActivityIntentInfo;
149import android.content.pm.PackageParser.PackageLite;
150import android.content.pm.PackageParser.PackageParserException;
151import android.content.pm.PackageStats;
152import android.content.pm.PackageUserState;
153import android.content.pm.ParceledListSlice;
154import android.content.pm.PermissionGroupInfo;
155import android.content.pm.PermissionInfo;
156import android.content.pm.ProviderInfo;
157import android.content.pm.ResolveInfo;
158import android.content.pm.ServiceInfo;
159import android.content.pm.Signature;
160import android.content.pm.UserInfo;
161import android.content.pm.VerifierDeviceIdentity;
162import android.content.pm.VerifierInfo;
163import android.content.res.Resources;
164import android.graphics.Bitmap;
165import android.hardware.display.DisplayManager;
166import android.net.Uri;
167import android.os.Binder;
168import android.os.Build;
169import android.os.Bundle;
170import android.os.Debug;
171import android.os.Environment;
172import android.os.Environment.UserEnvironment;
173import android.os.FileUtils;
174import android.os.Handler;
175import android.os.IBinder;
176import android.os.Looper;
177import android.os.Message;
178import android.os.Parcel;
179import android.os.ParcelFileDescriptor;
180import android.os.PatternMatcher;
181import android.os.Process;
182import android.os.RemoteCallbackList;
183import android.os.RemoteException;
184import android.os.ResultReceiver;
185import android.os.SELinux;
186import android.os.ServiceManager;
187import android.os.SystemClock;
188import android.os.SystemProperties;
189import android.os.Trace;
190import android.os.UserHandle;
191import android.os.UserManager;
192import android.os.UserManagerInternal;
193import android.os.storage.IMountService;
194import android.os.storage.MountServiceInternal;
195import android.os.storage.StorageEventListener;
196import android.os.storage.StorageManager;
197import android.os.storage.VolumeInfo;
198import android.os.storage.VolumeRecord;
199import android.provider.Settings.Global;
200import android.provider.Settings.Secure;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.Pair;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.util.jar.StrictJarFile;
223import android.view.Display;
224
225import com.android.internal.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.app.IMediaContainerService;
228import com.android.internal.app.ResolverActivity;
229import com.android.internal.content.NativeLibraryHelper;
230import com.android.internal.content.PackageHelper;
231import com.android.internal.logging.MetricsLogger;
232import com.android.internal.os.IParcelFileDescriptorFactory;
233import com.android.internal.os.InstallerConnection.InstallerException;
234import com.android.internal.os.SomeArgs;
235import com.android.internal.os.Zygote;
236import com.android.internal.telephony.CarrierAppUtils;
237import com.android.internal.util.ArrayUtils;
238import com.android.internal.util.FastPrintWriter;
239import com.android.internal.util.FastXmlSerializer;
240import com.android.internal.util.IndentingPrintWriter;
241import com.android.internal.util.Preconditions;
242import com.android.internal.util.XmlUtils;
243import com.android.server.AttributeCache;
244import com.android.server.EventLogTags;
245import com.android.server.FgThread;
246import com.android.server.IntentResolver;
247import com.android.server.LocalServices;
248import com.android.server.ServiceThread;
249import com.android.server.SystemConfig;
250import com.android.server.Watchdog;
251import com.android.server.net.NetworkPolicyManagerInternal;
252import com.android.server.pm.PermissionsState.PermissionState;
253import com.android.server.pm.Settings.DatabaseVersion;
254import com.android.server.pm.Settings.VersionInfo;
255import com.android.server.storage.DeviceStorageMonitorInternal;
256
257import dalvik.system.CloseGuard;
258import dalvik.system.DexFile;
259import dalvik.system.VMRuntime;
260
261import libcore.io.IoUtils;
262import libcore.util.EmptyArray;
263
264import org.xmlpull.v1.XmlPullParser;
265import org.xmlpull.v1.XmlPullParserException;
266import org.xmlpull.v1.XmlSerializer;
267
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306
307/**
308 * Keep track of all those APKs everywhere.
309 * <p>
310 * Internally there are two important locks:
311 * <ul>
312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
313 * and other related state. It is a fine-grained lock that should only be held
314 * momentarily, as it's one of the most contended locks in the system.
315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
316 * operations typically involve heavy lifting of application data on disk. Since
317 * {@code installd} is single-threaded, and it's operations can often be slow,
318 * this lock should never be acquired while already holding {@link #mPackages}.
319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
320 * holding {@link #mInstallLock}.
321 * </ul>
322 * Many internal methods rely on the caller to hold the appropriate locks, and
323 * this contract is expressed through method name suffixes:
324 * <ul>
325 * <li>fooLI(): the caller must hold {@link #mInstallLock}
326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
327 * being modified must be frozen
328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
330 * </ul>
331 * <p>
332 * Because this class is very central to the platform's security; please run all
333 * CTS and unit tests whenever making modifications:
334 *
335 * <pre>
336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
338 * </pre>
339 */
340public class PackageManagerService extends IPackageManager.Stub {
341    static final String TAG = "PackageManager";
342    static final boolean DEBUG_SETTINGS = false;
343    static final boolean DEBUG_PREFERRED = false;
344    static final boolean DEBUG_UPGRADE = false;
345    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
346    private static final boolean DEBUG_BACKUP = false;
347    private static final boolean DEBUG_INSTALL = false;
348    private static final boolean DEBUG_REMOVE = false;
349    private static final boolean DEBUG_BROADCASTS = false;
350    private static final boolean DEBUG_SHOW_INFO = false;
351    private static final boolean DEBUG_PACKAGE_INFO = false;
352    private static final boolean DEBUG_INTENT_MATCHING = false;
353    private static final boolean DEBUG_PACKAGE_SCANNING = false;
354    private static final boolean DEBUG_VERIFY = false;
355    private static final boolean DEBUG_FILTERS = false;
356
357    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359    // user, but by default initialize to this.
360    static final boolean DEBUG_DEXOPT = false;
361
362    private static final boolean DEBUG_ABI_SELECTION = false;
363    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
364    private static final boolean DEBUG_TRIAGED_MISSING = false;
365    private static final boolean DEBUG_APP_DATA = false;
366
367    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
368
369    // STOPSHIP; b/30256615
370    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
371
372    private static final int RADIO_UID = Process.PHONE_UID;
373    private static final int LOG_UID = Process.LOG_UID;
374    private static final int NFC_UID = Process.NFC_UID;
375    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
376    private static final int SHELL_UID = Process.SHELL_UID;
377
378    // Cap the size of permission trees that 3rd party apps can define
379    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
380
381    // Suffix used during package installation when copying/moving
382    // package apks to install directory.
383    private static final String INSTALL_PACKAGE_SUFFIX = "-";
384
385    static final int SCAN_NO_DEX = 1<<1;
386    static final int SCAN_FORCE_DEX = 1<<2;
387    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
388    static final int SCAN_NEW_INSTALL = 1<<4;
389    static final int SCAN_NO_PATHS = 1<<5;
390    static final int SCAN_UPDATE_TIME = 1<<6;
391    static final int SCAN_DEFER_DEX = 1<<7;
392    static final int SCAN_BOOTING = 1<<8;
393    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
394    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
395    static final int SCAN_REPLACING = 1<<11;
396    static final int SCAN_REQUIRE_KNOWN = 1<<12;
397    static final int SCAN_MOVE = 1<<13;
398    static final int SCAN_INITIAL = 1<<14;
399    static final int SCAN_CHECK_ONLY = 1<<15;
400    static final int SCAN_DONT_KILL_APP = 1<<17;
401    static final int SCAN_IGNORE_FROZEN = 1<<18;
402
403    static final int REMOVE_CHATTY = 1<<16;
404
405    private static final int[] EMPTY_INT_ARRAY = new int[0];
406
407    /**
408     * Timeout (in milliseconds) after which the watchdog should declare that
409     * our handler thread is wedged.  The usual default for such things is one
410     * minute but we sometimes do very lengthy I/O operations on this thread,
411     * such as installing multi-gigabyte applications, so ours needs to be longer.
412     */
413    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
414
415    /**
416     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
417     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
418     * settings entry if available, otherwise we use the hardcoded default.  If it's been
419     * more than this long since the last fstrim, we force one during the boot sequence.
420     *
421     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
422     * one gets run at the next available charging+idle time.  This final mandatory
423     * no-fstrim check kicks in only of the other scheduling criteria is never met.
424     */
425    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
426
427    /**
428     * Whether verification is enabled by default.
429     */
430    private static final boolean DEFAULT_VERIFY_ENABLE = true;
431
432    /**
433     * The default maximum time to wait for the verification agent to return in
434     * milliseconds.
435     */
436    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
437
438    /**
439     * The default response for package verification timeout.
440     *
441     * This can be either PackageManager.VERIFICATION_ALLOW or
442     * PackageManager.VERIFICATION_REJECT.
443     */
444    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
445
446    static final String PLATFORM_PACKAGE_NAME = "android";
447
448    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
449
450    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
451            DEFAULT_CONTAINER_PACKAGE,
452            "com.android.defcontainer.DefaultContainerService");
453
454    private static final String KILL_APP_REASON_GIDS_CHANGED =
455            "permission grant or revoke changed gids";
456
457    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
458            "permissions revoked";
459
460    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
461
462    private static final String PACKAGE_SCHEME = "package";
463
464    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
465
466    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
467    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
468
469    /** Permission grant: not grant the permission. */
470    private static final int GRANT_DENIED = 1;
471
472    /** Permission grant: grant the permission as an install permission. */
473    private static final int GRANT_INSTALL = 2;
474
475    /** Permission grant: grant the permission as a runtime one. */
476    private static final int GRANT_RUNTIME = 3;
477
478    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
479    private static final int GRANT_UPGRADE = 4;
480
481    /** Canonical intent used to identify what counts as a "web browser" app */
482    private static final Intent sBrowserIntent;
483    static {
484        sBrowserIntent = new Intent();
485        sBrowserIntent.setAction(Intent.ACTION_VIEW);
486        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
487        sBrowserIntent.setData(Uri.parse("http:"));
488    }
489
490    /**
491     * The set of all protected actions [i.e. those actions for which a high priority
492     * intent filter is disallowed].
493     */
494    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
495    static {
496        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
497        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
498        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
499        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
500    }
501
502    // Compilation reasons.
503    public static final int REASON_FIRST_BOOT = 0;
504    public static final int REASON_BOOT = 1;
505    public static final int REASON_INSTALL = 2;
506    public static final int REASON_BACKGROUND_DEXOPT = 3;
507    public static final int REASON_AB_OTA = 4;
508    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
509    public static final int REASON_SHARED_APK = 6;
510    public static final int REASON_FORCED_DEXOPT = 7;
511    public static final int REASON_CORE_APP = 8;
512
513    public static final int REASON_LAST = REASON_CORE_APP;
514
515    /** Special library name that skips shared libraries check during compilation. */
516    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
517
518    final ServiceThread mHandlerThread;
519
520    final PackageHandler mHandler;
521
522    private final ProcessLoggingHandler mProcessLoggingHandler;
523
524    /**
525     * Messages for {@link #mHandler} that need to wait for system ready before
526     * being dispatched.
527     */
528    private ArrayList<Message> mPostSystemReadyMessages;
529
530    final int mSdkVersion = Build.VERSION.SDK_INT;
531
532    final Context mContext;
533    final boolean mFactoryTest;
534    final boolean mOnlyCore;
535    final DisplayMetrics mMetrics;
536    final int mDefParseFlags;
537    final String[] mSeparateProcesses;
538    final boolean mIsUpgrade;
539    final boolean mIsPreNUpgrade;
540    final boolean mIsPreNMR1Upgrade;
541
542    @GuardedBy("mPackages")
543    private boolean mDexOptDialogShown;
544
545    /** The location for ASEC container files on internal storage. */
546    final String mAsecInternalPath;
547
548    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
549    // LOCK HELD.  Can be called with mInstallLock held.
550    @GuardedBy("mInstallLock")
551    final Installer mInstaller;
552
553    /** Directory where installed third-party apps stored */
554    final File mAppInstallDir;
555    final File mEphemeralInstallDir;
556
557    /**
558     * Directory to which applications installed internally have their
559     * 32 bit native libraries copied.
560     */
561    private File mAppLib32InstallDir;
562
563    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
564    // apps.
565    final File mDrmAppPrivateInstallDir;
566
567    // ----------------------------------------------------------------
568
569    // Lock for state used when installing and doing other long running
570    // operations.  Methods that must be called with this lock held have
571    // the suffix "LI".
572    final Object mInstallLock = new Object();
573
574    // ----------------------------------------------------------------
575
576    // Keys are String (package name), values are Package.  This also serves
577    // as the lock for the global state.  Methods that must be called with
578    // this lock held have the prefix "LP".
579    @GuardedBy("mPackages")
580    final ArrayMap<String, PackageParser.Package> mPackages =
581            new ArrayMap<String, PackageParser.Package>();
582
583    final ArrayMap<String, Set<String>> mKnownCodebase =
584            new ArrayMap<String, Set<String>>();
585
586    // Tracks available target package names -> overlay package paths.
587    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
588        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
589
590    /**
591     * Tracks new system packages [received in an OTA] that we expect to
592     * find updated user-installed versions. Keys are package name, values
593     * are package location.
594     */
595    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
596    /**
597     * Tracks high priority intent filters for protected actions. During boot, certain
598     * filter actions are protected and should never be allowed to have a high priority
599     * intent filter for them. However, there is one, and only one exception -- the
600     * setup wizard. It must be able to define a high priority intent filter for these
601     * actions to ensure there are no escapes from the wizard. We need to delay processing
602     * of these during boot as we need to look at all of the system packages in order
603     * to know which component is the setup wizard.
604     */
605    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
606    /**
607     * Whether or not processing protected filters should be deferred.
608     */
609    private boolean mDeferProtectedFilters = true;
610
611    /**
612     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
613     */
614    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
615    /**
616     * Whether or not system app permissions should be promoted from install to runtime.
617     */
618    boolean mPromoteSystemApps;
619
620    @GuardedBy("mPackages")
621    final Settings mSettings;
622
623    /**
624     * Set of package names that are currently "frozen", which means active
625     * surgery is being done on the code/data for that package. The platform
626     * will refuse to launch frozen packages to avoid race conditions.
627     *
628     * @see PackageFreezer
629     */
630    @GuardedBy("mPackages")
631    final ArraySet<String> mFrozenPackages = new ArraySet<>();
632
633    final ProtectedPackages mProtectedPackages;
634
635    boolean mFirstBoot;
636
637    // System configuration read by SystemConfig.
638    final int[] mGlobalGids;
639    final SparseArray<ArraySet<String>> mSystemPermissions;
640    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
641
642    // If mac_permissions.xml was found for seinfo labeling.
643    boolean mFoundPolicyFile;
644
645    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
646
647    public static final class SharedLibraryEntry {
648        public final String path;
649        public final String apk;
650
651        SharedLibraryEntry(String _path, String _apk) {
652            path = _path;
653            apk = _apk;
654        }
655    }
656
657    // Currently known shared libraries.
658    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
659            new ArrayMap<String, SharedLibraryEntry>();
660
661    // All available activities, for your resolving pleasure.
662    final ActivityIntentResolver mActivities =
663            new ActivityIntentResolver();
664
665    // All available receivers, for your resolving pleasure.
666    final ActivityIntentResolver mReceivers =
667            new ActivityIntentResolver();
668
669    // All available services, for your resolving pleasure.
670    final ServiceIntentResolver mServices = new ServiceIntentResolver();
671
672    // All available providers, for your resolving pleasure.
673    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
674
675    // Mapping from provider base names (first directory in content URI codePath)
676    // to the provider information.
677    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
678            new ArrayMap<String, PackageParser.Provider>();
679
680    // Mapping from instrumentation class names to info about them.
681    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
682            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
683
684    // Mapping from permission names to info about them.
685    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
686            new ArrayMap<String, PackageParser.PermissionGroup>();
687
688    // Packages whose data we have transfered into another package, thus
689    // should no longer exist.
690    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
691
692    // Broadcast actions that are only available to the system.
693    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
694
695    /** List of packages waiting for verification. */
696    final SparseArray<PackageVerificationState> mPendingVerification
697            = new SparseArray<PackageVerificationState>();
698
699    /** Set of packages associated with each app op permission. */
700    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
701
702    final PackageInstallerService mInstallerService;
703
704    private final PackageDexOptimizer mPackageDexOptimizer;
705
706    private AtomicInteger mNextMoveId = new AtomicInteger();
707    private final MoveCallbacks mMoveCallbacks;
708
709    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
710
711    // Cache of users who need badging.
712    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
713
714    /** Token for keys in mPendingVerification. */
715    private int mPendingVerificationToken = 0;
716
717    volatile boolean mSystemReady;
718    volatile boolean mSafeMode;
719    volatile boolean mHasSystemUidErrors;
720
721    ApplicationInfo mAndroidApplication;
722    final ActivityInfo mResolveActivity = new ActivityInfo();
723    final ResolveInfo mResolveInfo = new ResolveInfo();
724    ComponentName mResolveComponentName;
725    PackageParser.Package mPlatformPackage;
726    ComponentName mCustomResolverComponentName;
727
728    boolean mResolverReplaced = false;
729
730    private final @Nullable ComponentName mIntentFilterVerifierComponent;
731    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
732
733    private int mIntentFilterVerificationToken = 0;
734
735    /** Component that knows whether or not an ephemeral application exists */
736    final ComponentName mEphemeralResolverComponent;
737    /** The service connection to the ephemeral resolver */
738    final EphemeralResolverConnection mEphemeralResolverConnection;
739
740    /** Component used to install ephemeral applications */
741    final ComponentName mEphemeralInstallerComponent;
742    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
743    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
744
745    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
746            = new SparseArray<IntentFilterVerificationState>();
747
748    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
749
750    // List of packages names to keep cached, even if they are uninstalled for all users
751    private List<String> mKeepUninstalledPackages;
752
753    private UserManagerInternal mUserManagerInternal;
754
755    private static class IFVerificationParams {
756        PackageParser.Package pkg;
757        boolean replacing;
758        int userId;
759        int verifierUid;
760
761        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
762                int _userId, int _verifierUid) {
763            pkg = _pkg;
764            replacing = _replacing;
765            userId = _userId;
766            replacing = _replacing;
767            verifierUid = _verifierUid;
768        }
769    }
770
771    private interface IntentFilterVerifier<T extends IntentFilter> {
772        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
773                                               T filter, String packageName);
774        void startVerifications(int userId);
775        void receiveVerificationResponse(int verificationId);
776    }
777
778    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
779        private Context mContext;
780        private ComponentName mIntentFilterVerifierComponent;
781        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
782
783        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
784            mContext = context;
785            mIntentFilterVerifierComponent = verifierComponent;
786        }
787
788        private String getDefaultScheme() {
789            return IntentFilter.SCHEME_HTTPS;
790        }
791
792        @Override
793        public void startVerifications(int userId) {
794            // Launch verifications requests
795            int count = mCurrentIntentFilterVerifications.size();
796            for (int n=0; n<count; n++) {
797                int verificationId = mCurrentIntentFilterVerifications.get(n);
798                final IntentFilterVerificationState ivs =
799                        mIntentFilterVerificationStates.get(verificationId);
800
801                String packageName = ivs.getPackageName();
802
803                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
804                final int filterCount = filters.size();
805                ArraySet<String> domainsSet = new ArraySet<>();
806                for (int m=0; m<filterCount; m++) {
807                    PackageParser.ActivityIntentInfo filter = filters.get(m);
808                    domainsSet.addAll(filter.getHostsList());
809                }
810                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
811                synchronized (mPackages) {
812                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
813                            packageName, domainsList) != null) {
814                        scheduleWriteSettingsLocked();
815                    }
816                }
817                sendVerificationRequest(userId, verificationId, ivs);
818            }
819            mCurrentIntentFilterVerifications.clear();
820        }
821
822        private void sendVerificationRequest(int userId, int verificationId,
823                IntentFilterVerificationState ivs) {
824
825            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
828                    verificationId);
829            verificationIntent.putExtra(
830                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
831                    getDefaultScheme());
832            verificationIntent.putExtra(
833                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
834                    ivs.getHostsString());
835            verificationIntent.putExtra(
836                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
837                    ivs.getPackageName());
838            verificationIntent.setComponent(mIntentFilterVerifierComponent);
839            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
840
841            UserHandle user = new UserHandle(userId);
842            mContext.sendBroadcastAsUser(verificationIntent, user);
843            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
844                    "Sending IntentFilter verification broadcast");
845        }
846
847        public void receiveVerificationResponse(int verificationId) {
848            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
849
850            final boolean verified = ivs.isVerified();
851
852            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
853            final int count = filters.size();
854            if (DEBUG_DOMAIN_VERIFICATION) {
855                Slog.i(TAG, "Received verification response " + verificationId
856                        + " for " + count + " filters, verified=" + verified);
857            }
858            for (int n=0; n<count; n++) {
859                PackageParser.ActivityIntentInfo filter = filters.get(n);
860                filter.setVerified(verified);
861
862                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
863                        + " verified with result:" + verified + " and hosts:"
864                        + ivs.getHostsString());
865            }
866
867            mIntentFilterVerificationStates.remove(verificationId);
868
869            final String packageName = ivs.getPackageName();
870            IntentFilterVerificationInfo ivi = null;
871
872            synchronized (mPackages) {
873                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
874            }
875            if (ivi == null) {
876                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
877                        + verificationId + " packageName:" + packageName);
878                return;
879            }
880            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
881                    "Updating IntentFilterVerificationInfo for package " + packageName
882                            +" verificationId:" + verificationId);
883
884            synchronized (mPackages) {
885                if (verified) {
886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
887                } else {
888                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
889                }
890                scheduleWriteSettingsLocked();
891
892                final int userId = ivs.getUserId();
893                if (userId != UserHandle.USER_ALL) {
894                    final int userStatus =
895                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
896
897                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
898                    boolean needUpdate = false;
899
900                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
901                    // already been set by the User thru the Disambiguation dialog
902                    switch (userStatus) {
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                            } else {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
908                            }
909                            needUpdate = true;
910                            break;
911
912                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
913                            if (verified) {
914                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
915                                needUpdate = true;
916                            }
917                            break;
918
919                        default:
920                            // Nothing to do
921                    }
922
923                    if (needUpdate) {
924                        mSettings.updateIntentFilterVerificationStatusLPw(
925                                packageName, updatedStatus, userId);
926                        scheduleWritePackageRestrictionsLocked(userId);
927                    }
928                }
929            }
930        }
931
932        @Override
933        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
934                    ActivityIntentInfo filter, String packageName) {
935            if (!hasValidDomains(filter)) {
936                return false;
937            }
938            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
939            if (ivs == null) {
940                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
941                        packageName);
942            }
943            if (DEBUG_DOMAIN_VERIFICATION) {
944                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
945            }
946            ivs.addFilter(filter);
947            return true;
948        }
949
950        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
951                int userId, int verificationId, String packageName) {
952            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
953                    verifierUid, userId, packageName);
954            ivs.setPendingState();
955            synchronized (mPackages) {
956                mIntentFilterVerificationStates.append(verificationId, ivs);
957                mCurrentIntentFilterVerifications.add(verificationId);
958            }
959            return ivs;
960        }
961    }
962
963    private static boolean hasValidDomains(ActivityIntentInfo filter) {
964        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
965                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
966                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
967    }
968
969    // Set of pending broadcasts for aggregating enable/disable of components.
970    static class PendingPackageBroadcasts {
971        // for each user id, a map of <package name -> components within that package>
972        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
973
974        public PendingPackageBroadcasts() {
975            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
976        }
977
978        public ArrayList<String> get(int userId, String packageName) {
979            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
980            return packages.get(packageName);
981        }
982
983        public void put(int userId, String packageName, ArrayList<String> components) {
984            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
985            packages.put(packageName, components);
986        }
987
988        public void remove(int userId, String packageName) {
989            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
990            if (packages != null) {
991                packages.remove(packageName);
992            }
993        }
994
995        public void remove(int userId) {
996            mUidMap.remove(userId);
997        }
998
999        public int userIdCount() {
1000            return mUidMap.size();
1001        }
1002
1003        public int userIdAt(int n) {
1004            return mUidMap.keyAt(n);
1005        }
1006
1007        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1008            return mUidMap.get(userId);
1009        }
1010
1011        public int size() {
1012            // total number of pending broadcast entries across all userIds
1013            int num = 0;
1014            for (int i = 0; i< mUidMap.size(); i++) {
1015                num += mUidMap.valueAt(i).size();
1016            }
1017            return num;
1018        }
1019
1020        public void clear() {
1021            mUidMap.clear();
1022        }
1023
1024        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1025            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1026            if (map == null) {
1027                map = new ArrayMap<String, ArrayList<String>>();
1028                mUidMap.put(userId, map);
1029            }
1030            return map;
1031        }
1032    }
1033    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1034
1035    // Service Connection to remote media container service to copy
1036    // package uri's from external media onto secure containers
1037    // or internal storage.
1038    private IMediaContainerService mContainerService = null;
1039
1040    static final int SEND_PENDING_BROADCAST = 1;
1041    static final int MCS_BOUND = 3;
1042    static final int END_COPY = 4;
1043    static final int INIT_COPY = 5;
1044    static final int MCS_UNBIND = 6;
1045    static final int START_CLEANING_PACKAGE = 7;
1046    static final int FIND_INSTALL_LOC = 8;
1047    static final int POST_INSTALL = 9;
1048    static final int MCS_RECONNECT = 10;
1049    static final int MCS_GIVE_UP = 11;
1050    static final int UPDATED_MEDIA_STATUS = 12;
1051    static final int WRITE_SETTINGS = 13;
1052    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1053    static final int PACKAGE_VERIFIED = 15;
1054    static final int CHECK_PENDING_VERIFICATION = 16;
1055    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1056    static final int INTENT_FILTER_VERIFIED = 18;
1057    static final int WRITE_PACKAGE_LIST = 19;
1058
1059    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1060
1061    // Delay time in millisecs
1062    static final int BROADCAST_DELAY = 10 * 1000;
1063
1064    static UserManagerService sUserManager;
1065
1066    // Stores a list of users whose package restrictions file needs to be updated
1067    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1068
1069    final private DefaultContainerConnection mDefContainerConn =
1070            new DefaultContainerConnection();
1071    class DefaultContainerConnection implements ServiceConnection {
1072        public void onServiceConnected(ComponentName name, IBinder service) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1074            IMediaContainerService imcs =
1075                IMediaContainerService.Stub.asInterface(service);
1076            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1077        }
1078
1079        public void onServiceDisconnected(ComponentName name) {
1080            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1081        }
1082    }
1083
1084    // Recordkeeping of restore-after-install operations that are currently in flight
1085    // between the Package Manager and the Backup Manager
1086    static class PostInstallData {
1087        public InstallArgs args;
1088        public PackageInstalledInfo res;
1089
1090        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1091            args = _a;
1092            res = _r;
1093        }
1094    }
1095
1096    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1097    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1098
1099    // XML tags for backup/restore of various bits of state
1100    private static final String TAG_PREFERRED_BACKUP = "pa";
1101    private static final String TAG_DEFAULT_APPS = "da";
1102    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1103
1104    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1105    private static final String TAG_ALL_GRANTS = "rt-grants";
1106    private static final String TAG_GRANT = "grant";
1107    private static final String ATTR_PACKAGE_NAME = "pkg";
1108
1109    private static final String TAG_PERMISSION = "perm";
1110    private static final String ATTR_PERMISSION_NAME = "name";
1111    private static final String ATTR_IS_GRANTED = "g";
1112    private static final String ATTR_USER_SET = "set";
1113    private static final String ATTR_USER_FIXED = "fixed";
1114    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1115
1116    // System/policy permission grants are not backed up
1117    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1118            FLAG_PERMISSION_POLICY_FIXED
1119            | FLAG_PERMISSION_SYSTEM_FIXED
1120            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1121
1122    // And we back up these user-adjusted states
1123    private static final int USER_RUNTIME_GRANT_MASK =
1124            FLAG_PERMISSION_USER_SET
1125            | FLAG_PERMISSION_USER_FIXED
1126            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1127
1128    final @Nullable String mRequiredVerifierPackage;
1129    final @NonNull String mRequiredInstallerPackage;
1130    final @NonNull String mRequiredUninstallerPackage;
1131    final @Nullable String mSetupWizardPackage;
1132    final @Nullable String mStorageManagerPackage;
1133    final @NonNull String mServicesSystemSharedLibraryPackageName;
1134    final @NonNull String mSharedSystemSharedLibraryPackageName;
1135
1136    private final PackageUsage mPackageUsage = new PackageUsage();
1137    private final CompilerStats mCompilerStats = new CompilerStats();
1138
1139    class PackageHandler extends Handler {
1140        private boolean mBound = false;
1141        final ArrayList<HandlerParams> mPendingInstalls =
1142            new ArrayList<HandlerParams>();
1143
1144        private boolean connectToService() {
1145            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1146                    " DefaultContainerService");
1147            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1148            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1149            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1150                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1151                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1152                mBound = true;
1153                return true;
1154            }
1155            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1156            return false;
1157        }
1158
1159        private void disconnectService() {
1160            mContainerService = null;
1161            mBound = false;
1162            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1163            mContext.unbindService(mDefContainerConn);
1164            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165        }
1166
1167        PackageHandler(Looper looper) {
1168            super(looper);
1169        }
1170
1171        public void handleMessage(Message msg) {
1172            try {
1173                doHandleMessage(msg);
1174            } finally {
1175                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1176            }
1177        }
1178
1179        void doHandleMessage(Message msg) {
1180            switch (msg.what) {
1181                case INIT_COPY: {
1182                    HandlerParams params = (HandlerParams) msg.obj;
1183                    int idx = mPendingInstalls.size();
1184                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1185                    // If a bind was already initiated we dont really
1186                    // need to do anything. The pending install
1187                    // will be processed later on.
1188                    if (!mBound) {
1189                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1190                                System.identityHashCode(mHandler));
1191                        // If this is the only one pending we might
1192                        // have to bind to the service again.
1193                        if (!connectToService()) {
1194                            Slog.e(TAG, "Failed to bind to media container service");
1195                            params.serviceError();
1196                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                    System.identityHashCode(mHandler));
1198                            if (params.traceMethod != null) {
1199                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1200                                        params.traceCookie);
1201                            }
1202                            return;
1203                        } else {
1204                            // Once we bind to the service, the first
1205                            // pending request will be processed.
1206                            mPendingInstalls.add(idx, params);
1207                        }
1208                    } else {
1209                        mPendingInstalls.add(idx, params);
1210                        // Already bound to the service. Just make
1211                        // sure we trigger off processing the first request.
1212                        if (idx == 0) {
1213                            mHandler.sendEmptyMessage(MCS_BOUND);
1214                        }
1215                    }
1216                    break;
1217                }
1218                case MCS_BOUND: {
1219                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1220                    if (msg.obj != null) {
1221                        mContainerService = (IMediaContainerService) msg.obj;
1222                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1223                                System.identityHashCode(mHandler));
1224                    }
1225                    if (mContainerService == null) {
1226                        if (!mBound) {
1227                            // Something seriously wrong since we are not bound and we are not
1228                            // waiting for connection. Bail out.
1229                            Slog.e(TAG, "Cannot bind to media container service");
1230                            for (HandlerParams params : mPendingInstalls) {
1231                                // Indicate service bind error
1232                                params.serviceError();
1233                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1234                                        System.identityHashCode(params));
1235                                if (params.traceMethod != null) {
1236                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1237                                            params.traceMethod, params.traceCookie);
1238                                }
1239                                return;
1240                            }
1241                            mPendingInstalls.clear();
1242                        } else {
1243                            Slog.w(TAG, "Waiting to connect to media container service");
1244                        }
1245                    } else if (mPendingInstalls.size() > 0) {
1246                        HandlerParams params = mPendingInstalls.get(0);
1247                        if (params != null) {
1248                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1249                                    System.identityHashCode(params));
1250                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1251                            if (params.startCopy()) {
1252                                // We are done...  look for more work or to
1253                                // go idle.
1254                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1255                                        "Checking for more work or unbind...");
1256                                // Delete pending install
1257                                if (mPendingInstalls.size() > 0) {
1258                                    mPendingInstalls.remove(0);
1259                                }
1260                                if (mPendingInstalls.size() == 0) {
1261                                    if (mBound) {
1262                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1263                                                "Posting delayed MCS_UNBIND");
1264                                        removeMessages(MCS_UNBIND);
1265                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1266                                        // Unbind after a little delay, to avoid
1267                                        // continual thrashing.
1268                                        sendMessageDelayed(ubmsg, 10000);
1269                                    }
1270                                } else {
1271                                    // There are more pending requests in queue.
1272                                    // Just post MCS_BOUND message to trigger processing
1273                                    // of next pending install.
1274                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1275                                            "Posting MCS_BOUND for next work");
1276                                    mHandler.sendEmptyMessage(MCS_BOUND);
1277                                }
1278                            }
1279                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1280                        }
1281                    } else {
1282                        // Should never happen ideally.
1283                        Slog.w(TAG, "Empty queue");
1284                    }
1285                    break;
1286                }
1287                case MCS_RECONNECT: {
1288                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1289                    if (mPendingInstalls.size() > 0) {
1290                        if (mBound) {
1291                            disconnectService();
1292                        }
1293                        if (!connectToService()) {
1294                            Slog.e(TAG, "Failed to bind to media container service");
1295                            for (HandlerParams params : mPendingInstalls) {
1296                                // Indicate service bind error
1297                                params.serviceError();
1298                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1299                                        System.identityHashCode(params));
1300                            }
1301                            mPendingInstalls.clear();
1302                        }
1303                    }
1304                    break;
1305                }
1306                case MCS_UNBIND: {
1307                    // If there is no actual work left, then time to unbind.
1308                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1309
1310                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1311                        if (mBound) {
1312                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1313
1314                            disconnectService();
1315                        }
1316                    } else if (mPendingInstalls.size() > 0) {
1317                        // There are more pending requests in queue.
1318                        // Just post MCS_BOUND message to trigger processing
1319                        // of next pending install.
1320                        mHandler.sendEmptyMessage(MCS_BOUND);
1321                    }
1322
1323                    break;
1324                }
1325                case MCS_GIVE_UP: {
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1327                    HandlerParams params = mPendingInstalls.remove(0);
1328                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1329                            System.identityHashCode(params));
1330                    break;
1331                }
1332                case SEND_PENDING_BROADCAST: {
1333                    String packages[];
1334                    ArrayList<String> components[];
1335                    int size = 0;
1336                    int uids[];
1337                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1338                    synchronized (mPackages) {
1339                        if (mPendingBroadcasts == null) {
1340                            return;
1341                        }
1342                        size = mPendingBroadcasts.size();
1343                        if (size <= 0) {
1344                            // Nothing to be done. Just return
1345                            return;
1346                        }
1347                        packages = new String[size];
1348                        components = new ArrayList[size];
1349                        uids = new int[size];
1350                        int i = 0;  // filling out the above arrays
1351
1352                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1353                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1354                            Iterator<Map.Entry<String, ArrayList<String>>> it
1355                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1356                                            .entrySet().iterator();
1357                            while (it.hasNext() && i < size) {
1358                                Map.Entry<String, ArrayList<String>> ent = it.next();
1359                                packages[i] = ent.getKey();
1360                                components[i] = ent.getValue();
1361                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1362                                uids[i] = (ps != null)
1363                                        ? UserHandle.getUid(packageUserId, ps.appId)
1364                                        : -1;
1365                                i++;
1366                            }
1367                        }
1368                        size = i;
1369                        mPendingBroadcasts.clear();
1370                    }
1371                    // Send broadcasts
1372                    for (int i = 0; i < size; i++) {
1373                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1374                    }
1375                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1376                    break;
1377                }
1378                case START_CLEANING_PACKAGE: {
1379                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1380                    final String packageName = (String)msg.obj;
1381                    final int userId = msg.arg1;
1382                    final boolean andCode = msg.arg2 != 0;
1383                    synchronized (mPackages) {
1384                        if (userId == UserHandle.USER_ALL) {
1385                            int[] users = sUserManager.getUserIds();
1386                            for (int user : users) {
1387                                mSettings.addPackageToCleanLPw(
1388                                        new PackageCleanItem(user, packageName, andCode));
1389                            }
1390                        } else {
1391                            mSettings.addPackageToCleanLPw(
1392                                    new PackageCleanItem(userId, packageName, andCode));
1393                        }
1394                    }
1395                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1396                    startCleaningPackages();
1397                } break;
1398                case POST_INSTALL: {
1399                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1400
1401                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1402                    final boolean didRestore = (msg.arg2 != 0);
1403                    mRunningInstalls.delete(msg.arg1);
1404
1405                    if (data != null) {
1406                        InstallArgs args = data.args;
1407                        PackageInstalledInfo parentRes = data.res;
1408
1409                        final boolean grantPermissions = (args.installFlags
1410                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1411                        final boolean killApp = (args.installFlags
1412                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1413                        final String[] grantedPermissions = args.installGrantPermissions;
1414
1415                        // Handle the parent package
1416                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1417                                grantedPermissions, didRestore, args.installerPackageName,
1418                                args.observer);
1419
1420                        // Handle the child packages
1421                        final int childCount = (parentRes.addedChildPackages != null)
1422                                ? parentRes.addedChildPackages.size() : 0;
1423                        for (int i = 0; i < childCount; i++) {
1424                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1425                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1426                                    grantedPermissions, false, args.installerPackageName,
1427                                    args.observer);
1428                        }
1429
1430                        // Log tracing if needed
1431                        if (args.traceMethod != null) {
1432                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1433                                    args.traceCookie);
1434                        }
1435                    } else {
1436                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1437                    }
1438
1439                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1440                } break;
1441                case UPDATED_MEDIA_STATUS: {
1442                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1443                    boolean reportStatus = msg.arg1 == 1;
1444                    boolean doGc = msg.arg2 == 1;
1445                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1446                    if (doGc) {
1447                        // Force a gc to clear up stale containers.
1448                        Runtime.getRuntime().gc();
1449                    }
1450                    if (msg.obj != null) {
1451                        @SuppressWarnings("unchecked")
1452                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1453                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1454                        // Unload containers
1455                        unloadAllContainers(args);
1456                    }
1457                    if (reportStatus) {
1458                        try {
1459                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1460                            PackageHelper.getMountService().finishMediaUpdate();
1461                        } catch (RemoteException e) {
1462                            Log.e(TAG, "MountService not running?");
1463                        }
1464                    }
1465                } break;
1466                case WRITE_SETTINGS: {
1467                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1468                    synchronized (mPackages) {
1469                        removeMessages(WRITE_SETTINGS);
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        mSettings.writeLPr();
1472                        mDirtyUsers.clear();
1473                    }
1474                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1475                } break;
1476                case WRITE_PACKAGE_RESTRICTIONS: {
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                    synchronized (mPackages) {
1479                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480                        for (int userId : mDirtyUsers) {
1481                            mSettings.writePackageRestrictionsLPr(userId);
1482                        }
1483                        mDirtyUsers.clear();
1484                    }
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486                } break;
1487                case WRITE_PACKAGE_LIST: {
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1489                    synchronized (mPackages) {
1490                        removeMessages(WRITE_PACKAGE_LIST);
1491                        mSettings.writePackageListLPr(msg.arg1);
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case CHECK_PENDING_VERIFICATION: {
1496                    final int verificationId = msg.arg1;
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                    if ((state != null) && !state.timeoutExtended()) {
1500                        final InstallArgs args = state.getInstallArgs();
1501                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                        Slog.i(TAG, "Verification timed out for " + originUri);
1504                        mPendingVerification.remove(verificationId);
1505
1506                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                            Slog.i(TAG, "Continuing with installation of " + originUri);
1510                            state.setVerifierResponse(Binder.getCallingUid(),
1511                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_ALLOW,
1514                                    state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            broadcastPackageVerified(verificationId, originUri,
1522                                    PackageManager.VERIFICATION_REJECT,
1523                                    state.getInstallArgs().getUser());
1524                        }
1525
1526                        Trace.asyncTraceEnd(
1527                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1528
1529                        processPendingInstall(args, ret);
1530                        mHandler.sendEmptyMessage(MCS_UNBIND);
1531                    }
1532                    break;
1533                }
1534                case PACKAGE_VERIFIED: {
1535                    final int verificationId = msg.arg1;
1536
1537                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1538                    if (state == null) {
1539                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1540                        break;
1541                    }
1542
1543                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1544
1545                    state.setVerifierResponse(response.callerUid, response.code);
1546
1547                    if (state.isVerificationComplete()) {
1548                        mPendingVerification.remove(verificationId);
1549
1550                        final InstallArgs args = state.getInstallArgs();
1551                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1552
1553                        int ret;
1554                        if (state.isInstallAllowed()) {
1555                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1556                            broadcastPackageVerified(verificationId, originUri,
1557                                    response.code, state.getInstallArgs().getUser());
1558                            try {
1559                                ret = args.copyApk(mContainerService, true);
1560                            } catch (RemoteException e) {
1561                                Slog.e(TAG, "Could not contact the ContainerService");
1562                            }
1563                        } else {
1564                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1565                        }
1566
1567                        Trace.asyncTraceEnd(
1568                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1569
1570                        processPendingInstall(args, ret);
1571                        mHandler.sendEmptyMessage(MCS_UNBIND);
1572                    }
1573
1574                    break;
1575                }
1576                case START_INTENT_FILTER_VERIFICATIONS: {
1577                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1578                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1579                            params.replacing, params.pkg);
1580                    break;
1581                }
1582                case INTENT_FILTER_VERIFIED: {
1583                    final int verificationId = msg.arg1;
1584
1585                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1586                            verificationId);
1587                    if (state == null) {
1588                        Slog.w(TAG, "Invalid IntentFilter verification token "
1589                                + verificationId + " received");
1590                        break;
1591                    }
1592
1593                    final int userId = state.getUserId();
1594
1595                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1596                            "Processing IntentFilter verification with token:"
1597                            + verificationId + " and userId:" + userId);
1598
1599                    final IntentFilterVerificationResponse response =
1600                            (IntentFilterVerificationResponse) msg.obj;
1601
1602                    state.setVerifierResponse(response.callerUid, response.code);
1603
1604                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1605                            "IntentFilter verification with token:" + verificationId
1606                            + " and userId:" + userId
1607                            + " is settings verifier response with response code:"
1608                            + response.code);
1609
1610                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1611                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1612                                + response.getFailedDomainsString());
1613                    }
1614
1615                    if (state.isVerificationComplete()) {
1616                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1617                    } else {
1618                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1619                                "IntentFilter verification with token:" + verificationId
1620                                + " was not said to be complete");
1621                    }
1622
1623                    break;
1624                }
1625            }
1626        }
1627    }
1628
1629    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1630            boolean killApp, String[] grantedPermissions,
1631            boolean launchedForRestore, String installerPackage,
1632            IPackageInstallObserver2 installObserver) {
1633        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1634            // Send the removed broadcasts
1635            if (res.removedInfo != null) {
1636                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1637            }
1638
1639            // Now that we successfully installed the package, grant runtime
1640            // permissions if requested before broadcasting the install.
1641            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1642                    >= Build.VERSION_CODES.M) {
1643                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1644            }
1645
1646            final boolean update = res.removedInfo != null
1647                    && res.removedInfo.removedPackage != null;
1648
1649            // If this is the first time we have child packages for a disabled privileged
1650            // app that had no children, we grant requested runtime permissions to the new
1651            // children if the parent on the system image had them already granted.
1652            if (res.pkg.parentPackage != null) {
1653                synchronized (mPackages) {
1654                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1655                }
1656            }
1657
1658            synchronized (mPackages) {
1659                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1660            }
1661
1662            final String packageName = res.pkg.applicationInfo.packageName;
1663            Bundle extras = new Bundle(1);
1664            extras.putInt(Intent.EXTRA_UID, res.uid);
1665
1666            // Determine the set of users who are adding this package for
1667            // the first time vs. those who are seeing an update.
1668            int[] firstUsers = EMPTY_INT_ARRAY;
1669            int[] updateUsers = EMPTY_INT_ARRAY;
1670            if (res.origUsers == null || res.origUsers.length == 0) {
1671                firstUsers = res.newUsers;
1672            } else {
1673                for (int newUser : res.newUsers) {
1674                    boolean isNew = true;
1675                    for (int origUser : res.origUsers) {
1676                        if (origUser == newUser) {
1677                            isNew = false;
1678                            break;
1679                        }
1680                    }
1681                    if (isNew) {
1682                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1683                    } else {
1684                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1685                    }
1686                }
1687            }
1688
1689            // Send installed broadcasts if the install/update is not ephemeral
1690            if (!isEphemeral(res.pkg)) {
1691                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1692
1693                // Send added for users that see the package for the first time
1694                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1695                        extras, 0 /*flags*/, null /*targetPackage*/,
1696                        null /*finishedReceiver*/, firstUsers);
1697
1698                // Send added for users that don't see the package for the first time
1699                if (update) {
1700                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1701                }
1702                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1703                        extras, 0 /*flags*/, null /*targetPackage*/,
1704                        null /*finishedReceiver*/, updateUsers);
1705
1706                // Send replaced for users that don't see the package for the first time
1707                if (update) {
1708                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1709                            packageName, extras, 0 /*flags*/,
1710                            null /*targetPackage*/, null /*finishedReceiver*/,
1711                            updateUsers);
1712                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1713                            null /*package*/, null /*extras*/, 0 /*flags*/,
1714                            packageName /*targetPackage*/,
1715                            null /*finishedReceiver*/, updateUsers);
1716                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1717                    // First-install and we did a restore, so we're responsible for the
1718                    // first-launch broadcast.
1719                    if (DEBUG_BACKUP) {
1720                        Slog.i(TAG, "Post-restore of " + packageName
1721                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1722                    }
1723                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1724                }
1725
1726                // Send broadcast package appeared if forward locked/external for all users
1727                // treat asec-hosted packages like removable media on upgrade
1728                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1729                    if (DEBUG_INSTALL) {
1730                        Slog.i(TAG, "upgrading pkg " + res.pkg
1731                                + " is ASEC-hosted -> AVAILABLE");
1732                    }
1733                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1734                    ArrayList<String> pkgList = new ArrayList<>(1);
1735                    pkgList.add(packageName);
1736                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1737                }
1738            }
1739
1740            // Work that needs to happen on first install within each user
1741            if (firstUsers != null && firstUsers.length > 0) {
1742                synchronized (mPackages) {
1743                    for (int userId : firstUsers) {
1744                        // If this app is a browser and it's newly-installed for some
1745                        // users, clear any default-browser state in those users. The
1746                        // app's nature doesn't depend on the user, so we can just check
1747                        // its browser nature in any user and generalize.
1748                        if (packageIsBrowser(packageName, userId)) {
1749                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1750                        }
1751
1752                        // We may also need to apply pending (restored) runtime
1753                        // permission grants within these users.
1754                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1755                    }
1756                }
1757            }
1758
1759            // Log current value of "unknown sources" setting
1760            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1761                    getUnknownSourcesSettings());
1762
1763            // Force a gc to clear up things
1764            Runtime.getRuntime().gc();
1765
1766            // Remove the replaced package's older resources safely now
1767            // We delete after a gc for applications  on sdcard.
1768            if (res.removedInfo != null && res.removedInfo.args != null) {
1769                synchronized (mInstallLock) {
1770                    res.removedInfo.args.doPostDeleteLI(true);
1771                }
1772            }
1773        }
1774
1775        // If someone is watching installs - notify them
1776        if (installObserver != null) {
1777            try {
1778                Bundle extras = extrasForInstallResult(res);
1779                installObserver.onPackageInstalled(res.name, res.returnCode,
1780                        res.returnMsg, extras);
1781            } catch (RemoteException e) {
1782                Slog.i(TAG, "Observer no longer exists.");
1783            }
1784        }
1785    }
1786
1787    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1788            PackageParser.Package pkg) {
1789        if (pkg.parentPackage == null) {
1790            return;
1791        }
1792        if (pkg.requestedPermissions == null) {
1793            return;
1794        }
1795        final PackageSetting disabledSysParentPs = mSettings
1796                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1797        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1798                || !disabledSysParentPs.isPrivileged()
1799                || (disabledSysParentPs.childPackageNames != null
1800                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1801            return;
1802        }
1803        final int[] allUserIds = sUserManager.getUserIds();
1804        final int permCount = pkg.requestedPermissions.size();
1805        for (int i = 0; i < permCount; i++) {
1806            String permission = pkg.requestedPermissions.get(i);
1807            BasePermission bp = mSettings.mPermissions.get(permission);
1808            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1809                continue;
1810            }
1811            for (int userId : allUserIds) {
1812                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1813                        permission, userId)) {
1814                    grantRuntimePermission(pkg.packageName, permission, userId);
1815                }
1816            }
1817        }
1818    }
1819
1820    private StorageEventListener mStorageListener = new StorageEventListener() {
1821        @Override
1822        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1823            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1824                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1825                    final String volumeUuid = vol.getFsUuid();
1826
1827                    // Clean up any users or apps that were removed or recreated
1828                    // while this volume was missing
1829                    reconcileUsers(volumeUuid);
1830                    reconcileApps(volumeUuid);
1831
1832                    // Clean up any install sessions that expired or were
1833                    // cancelled while this volume was missing
1834                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1835
1836                    loadPrivatePackages(vol);
1837
1838                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1839                    unloadPrivatePackages(vol);
1840                }
1841            }
1842
1843            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1844                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1845                    updateExternalMediaStatus(true, false);
1846                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1847                    updateExternalMediaStatus(false, false);
1848                }
1849            }
1850        }
1851
1852        @Override
1853        public void onVolumeForgotten(String fsUuid) {
1854            if (TextUtils.isEmpty(fsUuid)) {
1855                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1856                return;
1857            }
1858
1859            // Remove any apps installed on the forgotten volume
1860            synchronized (mPackages) {
1861                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1862                for (PackageSetting ps : packages) {
1863                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1864                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1865                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1866                }
1867
1868                mSettings.onVolumeForgotten(fsUuid);
1869                mSettings.writeLPr();
1870            }
1871        }
1872    };
1873
1874    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1875            String[] grantedPermissions) {
1876        for (int userId : userIds) {
1877            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1878        }
1879
1880        // We could have touched GID membership, so flush out packages.list
1881        synchronized (mPackages) {
1882            mSettings.writePackageListLPr();
1883        }
1884    }
1885
1886    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1887            String[] grantedPermissions) {
1888        SettingBase sb = (SettingBase) pkg.mExtras;
1889        if (sb == null) {
1890            return;
1891        }
1892
1893        PermissionsState permissionsState = sb.getPermissionsState();
1894
1895        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1896                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1897
1898        for (String permission : pkg.requestedPermissions) {
1899            final BasePermission bp;
1900            synchronized (mPackages) {
1901                bp = mSettings.mPermissions.get(permission);
1902            }
1903            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1904                    && (grantedPermissions == null
1905                           || ArrayUtils.contains(grantedPermissions, permission))) {
1906                final int flags = permissionsState.getPermissionFlags(permission, userId);
1907                // Installer cannot change immutable permissions.
1908                if ((flags & immutableFlags) == 0) {
1909                    grantRuntimePermission(pkg.packageName, permission, userId);
1910                }
1911            }
1912        }
1913    }
1914
1915    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1916        Bundle extras = null;
1917        switch (res.returnCode) {
1918            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1919                extras = new Bundle();
1920                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1921                        res.origPermission);
1922                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1923                        res.origPackage);
1924                break;
1925            }
1926            case PackageManager.INSTALL_SUCCEEDED: {
1927                extras = new Bundle();
1928                extras.putBoolean(Intent.EXTRA_REPLACING,
1929                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1930                break;
1931            }
1932        }
1933        return extras;
1934    }
1935
1936    void scheduleWriteSettingsLocked() {
1937        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1938            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1939        }
1940    }
1941
1942    void scheduleWritePackageListLocked(int userId) {
1943        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1944            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1945            msg.arg1 = userId;
1946            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1947        }
1948    }
1949
1950    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1951        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1952        scheduleWritePackageRestrictionsLocked(userId);
1953    }
1954
1955    void scheduleWritePackageRestrictionsLocked(int userId) {
1956        final int[] userIds = (userId == UserHandle.USER_ALL)
1957                ? sUserManager.getUserIds() : new int[]{userId};
1958        for (int nextUserId : userIds) {
1959            if (!sUserManager.exists(nextUserId)) return;
1960            mDirtyUsers.add(nextUserId);
1961            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1962                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1963            }
1964        }
1965    }
1966
1967    public static PackageManagerService main(Context context, Installer installer,
1968            boolean factoryTest, boolean onlyCore) {
1969        // Self-check for initial settings.
1970        PackageManagerServiceCompilerMapping.checkProperties();
1971
1972        PackageManagerService m = new PackageManagerService(context, installer,
1973                factoryTest, onlyCore);
1974        m.enableSystemUserPackages();
1975        ServiceManager.addService("package", m);
1976        return m;
1977    }
1978
1979    private void enableSystemUserPackages() {
1980        if (!UserManager.isSplitSystemUser()) {
1981            return;
1982        }
1983        // For system user, enable apps based on the following conditions:
1984        // - app is whitelisted or belong to one of these groups:
1985        //   -- system app which has no launcher icons
1986        //   -- system app which has INTERACT_ACROSS_USERS permission
1987        //   -- system IME app
1988        // - app is not in the blacklist
1989        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1990        Set<String> enableApps = new ArraySet<>();
1991        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1992                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1993                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1994        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1995        enableApps.addAll(wlApps);
1996        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1997                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1998        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1999        enableApps.removeAll(blApps);
2000        Log.i(TAG, "Applications installed for system user: " + enableApps);
2001        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2002                UserHandle.SYSTEM);
2003        final int allAppsSize = allAps.size();
2004        synchronized (mPackages) {
2005            for (int i = 0; i < allAppsSize; i++) {
2006                String pName = allAps.get(i);
2007                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2008                // Should not happen, but we shouldn't be failing if it does
2009                if (pkgSetting == null) {
2010                    continue;
2011                }
2012                boolean install = enableApps.contains(pName);
2013                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2014                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2015                            + " for system user");
2016                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2017                }
2018            }
2019        }
2020    }
2021
2022    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2023        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2024                Context.DISPLAY_SERVICE);
2025        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2026    }
2027
2028    /**
2029     * Requests that files preopted on a secondary system partition be copied to the data partition
2030     * if possible.  Note that the actual copying of the files is accomplished by init for security
2031     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2032     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2033     */
2034    private static void requestCopyPreoptedFiles() {
2035        final int WAIT_TIME_MS = 100;
2036        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2037        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2038            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2039            // We will wait for up to 100 seconds.
2040            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2041            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2042                try {
2043                    Thread.sleep(WAIT_TIME_MS);
2044                } catch (InterruptedException e) {
2045                    // Do nothing
2046                }
2047                if (SystemClock.uptimeMillis() > timeEnd) {
2048                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2049                    Slog.wtf(TAG, "cppreopt did not finish!");
2050                    break;
2051                }
2052            }
2053        }
2054    }
2055
2056    public PackageManagerService(Context context, Installer installer,
2057            boolean factoryTest, boolean onlyCore) {
2058        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2059                SystemClock.uptimeMillis());
2060
2061        if (mSdkVersion <= 0) {
2062            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2063        }
2064
2065        mContext = context;
2066        mFactoryTest = factoryTest;
2067        mOnlyCore = onlyCore;
2068        mMetrics = new DisplayMetrics();
2069        mSettings = new Settings(mPackages);
2070        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2075                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2076        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2077                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2079                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2080        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2081                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2082
2083        String separateProcesses = SystemProperties.get("debug.separate_processes");
2084        if (separateProcesses != null && separateProcesses.length() > 0) {
2085            if ("*".equals(separateProcesses)) {
2086                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2087                mSeparateProcesses = null;
2088                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2089            } else {
2090                mDefParseFlags = 0;
2091                mSeparateProcesses = separateProcesses.split(",");
2092                Slog.w(TAG, "Running with debug.separate_processes: "
2093                        + separateProcesses);
2094            }
2095        } else {
2096            mDefParseFlags = 0;
2097            mSeparateProcesses = null;
2098        }
2099
2100        mInstaller = installer;
2101        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2102                "*dexopt*");
2103        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2104
2105        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2106                FgThread.get().getLooper());
2107
2108        getDefaultDisplayMetrics(context, mMetrics);
2109
2110        SystemConfig systemConfig = SystemConfig.getInstance();
2111        mGlobalGids = systemConfig.getGlobalGids();
2112        mSystemPermissions = systemConfig.getSystemPermissions();
2113        mAvailableFeatures = systemConfig.getAvailableFeatures();
2114
2115        mProtectedPackages = new ProtectedPackages(mContext);
2116
2117        synchronized (mInstallLock) {
2118        // writer
2119        synchronized (mPackages) {
2120            mHandlerThread = new ServiceThread(TAG,
2121                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2122            mHandlerThread.start();
2123            mHandler = new PackageHandler(mHandlerThread.getLooper());
2124            mProcessLoggingHandler = new ProcessLoggingHandler();
2125            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2126
2127            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2128
2129            File dataDir = Environment.getDataDirectory();
2130            mAppInstallDir = new File(dataDir, "app");
2131            mAppLib32InstallDir = new File(dataDir, "app-lib");
2132            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2133            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2134            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2135
2136            sUserManager = new UserManagerService(context, this, mPackages);
2137
2138            // Propagate permission configuration in to package manager.
2139            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2140                    = systemConfig.getPermissions();
2141            for (int i=0; i<permConfig.size(); i++) {
2142                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2143                BasePermission bp = mSettings.mPermissions.get(perm.name);
2144                if (bp == null) {
2145                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2146                    mSettings.mPermissions.put(perm.name, bp);
2147                }
2148                if (perm.gids != null) {
2149                    bp.setGids(perm.gids, perm.perUser);
2150                }
2151            }
2152
2153            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2154            for (int i=0; i<libConfig.size(); i++) {
2155                mSharedLibraries.put(libConfig.keyAt(i),
2156                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2157            }
2158
2159            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2160
2161            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2162
2163            if (mFirstBoot) {
2164                requestCopyPreoptedFiles();
2165            }
2166
2167            String customResolverActivity = Resources.getSystem().getString(
2168                    R.string.config_customResolverActivity);
2169            if (TextUtils.isEmpty(customResolverActivity)) {
2170                customResolverActivity = null;
2171            } else {
2172                mCustomResolverComponentName = ComponentName.unflattenFromString(
2173                        customResolverActivity);
2174            }
2175
2176            long startTime = SystemClock.uptimeMillis();
2177
2178            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2179                    startTime);
2180
2181            // Set flag to monitor and not change apk file paths when
2182            // scanning install directories.
2183            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2184
2185            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2186            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2187
2188            if (bootClassPath == null) {
2189                Slog.w(TAG, "No BOOTCLASSPATH found!");
2190            }
2191
2192            if (systemServerClassPath == null) {
2193                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2194            }
2195
2196            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2197            final String[] dexCodeInstructionSets =
2198                    getDexCodeInstructionSets(
2199                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2200
2201            /**
2202             * Ensure all external libraries have had dexopt run on them.
2203             */
2204            if (mSharedLibraries.size() > 0) {
2205                // NOTE: For now, we're compiling these system "shared libraries"
2206                // (and framework jars) into all available architectures. It's possible
2207                // to compile them only when we come across an app that uses them (there's
2208                // already logic for that in scanPackageLI) but that adds some complexity.
2209                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2210                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2211                        final String lib = libEntry.path;
2212                        if (lib == null) {
2213                            continue;
2214                        }
2215
2216                        try {
2217                            // Shared libraries do not have profiles so we perform a full
2218                            // AOT compilation (if needed).
2219                            int dexoptNeeded = DexFile.getDexOptNeeded(
2220                                    lib, dexCodeInstructionSet,
2221                                    getCompilerFilterForReason(REASON_SHARED_APK),
2222                                    false /* newProfile */);
2223                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2224                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2225                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2226                                        getCompilerFilterForReason(REASON_SHARED_APK),
2227                                        StorageManager.UUID_PRIVATE_INTERNAL,
2228                                        SKIP_SHARED_LIBRARY_CHECK);
2229                            }
2230                        } catch (FileNotFoundException e) {
2231                            Slog.w(TAG, "Library not found: " + lib);
2232                        } catch (IOException | InstallerException e) {
2233                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2234                                    + e.getMessage());
2235                        }
2236                    }
2237                }
2238            }
2239
2240            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2241
2242            final VersionInfo ver = mSettings.getInternalVersion();
2243            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2244
2245            // when upgrading from pre-M, promote system app permissions from install to runtime
2246            mPromoteSystemApps =
2247                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2248
2249            // When upgrading from pre-N, we need to handle package extraction like first boot,
2250            // as there is no profiling data available.
2251            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2252
2253            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2254
2255            // save off the names of pre-existing system packages prior to scanning; we don't
2256            // want to automatically grant runtime permissions for new system apps
2257            if (mPromoteSystemApps) {
2258                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2259                while (pkgSettingIter.hasNext()) {
2260                    PackageSetting ps = pkgSettingIter.next();
2261                    if (isSystemApp(ps)) {
2262                        mExistingSystemPackages.add(ps.name);
2263                    }
2264                }
2265            }
2266
2267            // Collect vendor overlay packages.
2268            // (Do this before scanning any apps.)
2269            // For security and version matching reason, only consider
2270            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2271            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2272            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2273                    | PackageParser.PARSE_IS_SYSTEM
2274                    | PackageParser.PARSE_IS_SYSTEM_DIR
2275                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2276
2277            // Find base frameworks (resource packages without code).
2278            scanDirTracedLI(frameworkDir, mDefParseFlags
2279                    | PackageParser.PARSE_IS_SYSTEM
2280                    | PackageParser.PARSE_IS_SYSTEM_DIR
2281                    | PackageParser.PARSE_IS_PRIVILEGED,
2282                    scanFlags | SCAN_NO_DEX, 0);
2283
2284            // Collected privileged system packages.
2285            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2286            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2287                    | PackageParser.PARSE_IS_SYSTEM
2288                    | PackageParser.PARSE_IS_SYSTEM_DIR
2289                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2290
2291            // Collect ordinary system packages.
2292            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2293            scanDirTracedLI(systemAppDir, mDefParseFlags
2294                    | PackageParser.PARSE_IS_SYSTEM
2295                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2296
2297            // Collect all vendor packages.
2298            File vendorAppDir = new File("/vendor/app");
2299            try {
2300                vendorAppDir = vendorAppDir.getCanonicalFile();
2301            } catch (IOException e) {
2302                // failed to look up canonical path, continue with original one
2303            }
2304            scanDirTracedLI(vendorAppDir, mDefParseFlags
2305                    | PackageParser.PARSE_IS_SYSTEM
2306                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2307
2308            // Collect all OEM packages.
2309            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2310            scanDirTracedLI(oemAppDir, mDefParseFlags
2311                    | PackageParser.PARSE_IS_SYSTEM
2312                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2313
2314            // Prune any system packages that no longer exist.
2315            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2316            if (!mOnlyCore) {
2317                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2318                while (psit.hasNext()) {
2319                    PackageSetting ps = psit.next();
2320
2321                    /*
2322                     * If this is not a system app, it can't be a
2323                     * disable system app.
2324                     */
2325                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2326                        continue;
2327                    }
2328
2329                    /*
2330                     * If the package is scanned, it's not erased.
2331                     */
2332                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2333                    if (scannedPkg != null) {
2334                        /*
2335                         * If the system app is both scanned and in the
2336                         * disabled packages list, then it must have been
2337                         * added via OTA. Remove it from the currently
2338                         * scanned package so the previously user-installed
2339                         * application can be scanned.
2340                         */
2341                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2342                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2343                                    + ps.name + "; removing system app.  Last known codePath="
2344                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2345                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2346                                    + scannedPkg.mVersionCode);
2347                            removePackageLI(scannedPkg, true);
2348                            mExpectingBetter.put(ps.name, ps.codePath);
2349                        }
2350
2351                        continue;
2352                    }
2353
2354                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2355                        psit.remove();
2356                        logCriticalInfo(Log.WARN, "System package " + ps.name
2357                                + " no longer exists; it's data will be wiped");
2358                        // Actual deletion of code and data will be handled by later
2359                        // reconciliation step
2360                    } else {
2361                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2362                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2363                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2364                        }
2365                    }
2366                }
2367            }
2368
2369            //look for any incomplete package installations
2370            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2371            for (int i = 0; i < deletePkgsList.size(); i++) {
2372                // Actual deletion of code and data will be handled by later
2373                // reconciliation step
2374                final String packageName = deletePkgsList.get(i).name;
2375                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2376                synchronized (mPackages) {
2377                    mSettings.removePackageLPw(packageName);
2378                }
2379            }
2380
2381            //delete tmp files
2382            deleteTempPackageFiles();
2383
2384            // Remove any shared userIDs that have no associated packages
2385            mSettings.pruneSharedUsersLPw();
2386
2387            if (!mOnlyCore) {
2388                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2389                        SystemClock.uptimeMillis());
2390                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2391
2392                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2393                        | PackageParser.PARSE_FORWARD_LOCK,
2394                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2395
2396                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2397                        | PackageParser.PARSE_IS_EPHEMERAL,
2398                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2399
2400                /**
2401                 * Remove disable package settings for any updated system
2402                 * apps that were removed via an OTA. If they're not a
2403                 * previously-updated app, remove them completely.
2404                 * Otherwise, just revoke their system-level permissions.
2405                 */
2406                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2407                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2408                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2409
2410                    String msg;
2411                    if (deletedPkg == null) {
2412                        msg = "Updated system package " + deletedAppName
2413                                + " no longer exists; it's data will be wiped";
2414                        // Actual deletion of code and data will be handled by later
2415                        // reconciliation step
2416                    } else {
2417                        msg = "Updated system app + " + deletedAppName
2418                                + " no longer present; removing system privileges for "
2419                                + deletedAppName;
2420
2421                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2422
2423                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2424                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2425                    }
2426                    logCriticalInfo(Log.WARN, msg);
2427                }
2428
2429                /**
2430                 * Make sure all system apps that we expected to appear on
2431                 * the userdata partition actually showed up. If they never
2432                 * appeared, crawl back and revive the system version.
2433                 */
2434                for (int i = 0; i < mExpectingBetter.size(); i++) {
2435                    final String packageName = mExpectingBetter.keyAt(i);
2436                    if (!mPackages.containsKey(packageName)) {
2437                        final File scanFile = mExpectingBetter.valueAt(i);
2438
2439                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2440                                + " but never showed up; reverting to system");
2441
2442                        int reparseFlags = mDefParseFlags;
2443                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2444                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2445                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2446                                    | PackageParser.PARSE_IS_PRIVILEGED;
2447                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2448                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2449                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2450                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2451                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2452                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2453                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2454                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2455                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2456                        } else {
2457                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2458                            continue;
2459                        }
2460
2461                        mSettings.enableSystemPackageLPw(packageName);
2462
2463                        try {
2464                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2465                        } catch (PackageManagerException e) {
2466                            Slog.e(TAG, "Failed to parse original system package: "
2467                                    + e.getMessage());
2468                        }
2469                    }
2470                }
2471            }
2472            mExpectingBetter.clear();
2473
2474            // Resolve the storage manager.
2475            mStorageManagerPackage = getStorageManagerPackageName();
2476
2477            // Resolve protected action filters. Only the setup wizard is allowed to
2478            // have a high priority filter for these actions.
2479            mSetupWizardPackage = getSetupWizardPackageName();
2480            if (mProtectedFilters.size() > 0) {
2481                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2482                    Slog.i(TAG, "No setup wizard;"
2483                        + " All protected intents capped to priority 0");
2484                }
2485                for (ActivityIntentInfo filter : mProtectedFilters) {
2486                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2487                        if (DEBUG_FILTERS) {
2488                            Slog.i(TAG, "Found setup wizard;"
2489                                + " allow priority " + filter.getPriority() + ";"
2490                                + " package: " + filter.activity.info.packageName
2491                                + " activity: " + filter.activity.className
2492                                + " priority: " + filter.getPriority());
2493                        }
2494                        // skip setup wizard; allow it to keep the high priority filter
2495                        continue;
2496                    }
2497                    Slog.w(TAG, "Protected action; cap priority to 0;"
2498                            + " package: " + filter.activity.info.packageName
2499                            + " activity: " + filter.activity.className
2500                            + " origPrio: " + filter.getPriority());
2501                    filter.setPriority(0);
2502                }
2503            }
2504            mDeferProtectedFilters = false;
2505            mProtectedFilters.clear();
2506
2507            // Now that we know all of the shared libraries, update all clients to have
2508            // the correct library paths.
2509            updateAllSharedLibrariesLPw();
2510
2511            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2512                // NOTE: We ignore potential failures here during a system scan (like
2513                // the rest of the commands above) because there's precious little we
2514                // can do about it. A settings error is reported, though.
2515                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2516                        false /* boot complete */);
2517            }
2518
2519            // Now that we know all the packages we are keeping,
2520            // read and update their last usage times.
2521            mPackageUsage.read(mPackages);
2522            mCompilerStats.read();
2523
2524            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2525                    SystemClock.uptimeMillis());
2526            Slog.i(TAG, "Time to scan packages: "
2527                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2528                    + " seconds");
2529
2530            // If the platform SDK has changed since the last time we booted,
2531            // we need to re-grant app permission to catch any new ones that
2532            // appear.  This is really a hack, and means that apps can in some
2533            // cases get permissions that the user didn't initially explicitly
2534            // allow...  it would be nice to have some better way to handle
2535            // this situation.
2536            int updateFlags = UPDATE_PERMISSIONS_ALL;
2537            if (ver.sdkVersion != mSdkVersion) {
2538                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2539                        + mSdkVersion + "; regranting permissions for internal storage");
2540                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2541            }
2542            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2543            ver.sdkVersion = mSdkVersion;
2544
2545            // If this is the first boot or an update from pre-M, and it is a normal
2546            // boot, then we need to initialize the default preferred apps across
2547            // all defined users.
2548            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2549                for (UserInfo user : sUserManager.getUsers(true)) {
2550                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2551                    applyFactoryDefaultBrowserLPw(user.id);
2552                    primeDomainVerificationsLPw(user.id);
2553                }
2554            }
2555
2556            // Prepare storage for system user really early during boot,
2557            // since core system apps like SettingsProvider and SystemUI
2558            // can't wait for user to start
2559            final int storageFlags;
2560            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2561                storageFlags = StorageManager.FLAG_STORAGE_DE;
2562            } else {
2563                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2564            }
2565            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2566                    storageFlags);
2567
2568            // If this is first boot after an OTA, and a normal boot, then
2569            // we need to clear code cache directories.
2570            // Note that we do *not* clear the application profiles. These remain valid
2571            // across OTAs and are used to drive profile verification (post OTA) and
2572            // profile compilation (without waiting to collect a fresh set of profiles).
2573            if (mIsUpgrade && !onlyCore) {
2574                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2575                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2576                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2577                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2578                        // No apps are running this early, so no need to freeze
2579                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2580                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2581                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2582                    }
2583                }
2584                ver.fingerprint = Build.FINGERPRINT;
2585            }
2586
2587            checkDefaultBrowser();
2588
2589            // clear only after permissions and other defaults have been updated
2590            mExistingSystemPackages.clear();
2591            mPromoteSystemApps = false;
2592
2593            // All the changes are done during package scanning.
2594            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2595
2596            // can downgrade to reader
2597            mSettings.writeLPr();
2598
2599            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2600            // early on (before the package manager declares itself as early) because other
2601            // components in the system server might ask for package contexts for these apps.
2602            //
2603            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2604            // (i.e, that the data partition is unavailable).
2605            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2606                long start = System.nanoTime();
2607                List<PackageParser.Package> coreApps = new ArrayList<>();
2608                for (PackageParser.Package pkg : mPackages.values()) {
2609                    if (pkg.coreApp) {
2610                        coreApps.add(pkg);
2611                    }
2612                }
2613
2614                int[] stats = performDexOptUpgrade(coreApps, false,
2615                        getCompilerFilterForReason(REASON_CORE_APP));
2616
2617                final int elapsedTimeSeconds =
2618                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2619                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2620
2621                if (DEBUG_DEXOPT) {
2622                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2623                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2624                }
2625
2626
2627                // TODO: Should we log these stats to tron too ?
2628                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2629                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2630                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2631                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2632            }
2633
2634            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2635                    SystemClock.uptimeMillis());
2636
2637            if (!mOnlyCore) {
2638                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2639                mRequiredInstallerPackage = getRequiredInstallerLPr();
2640                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2641                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2642                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2643                        mIntentFilterVerifierComponent);
2644                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2645                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2646                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2647                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2648            } else {
2649                mRequiredVerifierPackage = null;
2650                mRequiredInstallerPackage = null;
2651                mRequiredUninstallerPackage = null;
2652                mIntentFilterVerifierComponent = null;
2653                mIntentFilterVerifier = null;
2654                mServicesSystemSharedLibraryPackageName = null;
2655                mSharedSystemSharedLibraryPackageName = null;
2656            }
2657
2658            mInstallerService = new PackageInstallerService(context, this);
2659
2660            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2661            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2662            // both the installer and resolver must be present to enable ephemeral
2663            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2664                if (DEBUG_EPHEMERAL) {
2665                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2666                            + " installer:" + ephemeralInstallerComponent);
2667                }
2668                mEphemeralResolverComponent = ephemeralResolverComponent;
2669                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2670                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2671                mEphemeralResolverConnection =
2672                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2673            } else {
2674                if (DEBUG_EPHEMERAL) {
2675                    final String missingComponent =
2676                            (ephemeralResolverComponent == null)
2677                            ? (ephemeralInstallerComponent == null)
2678                                    ? "resolver and installer"
2679                                    : "resolver"
2680                            : "installer";
2681                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2682                }
2683                mEphemeralResolverComponent = null;
2684                mEphemeralInstallerComponent = null;
2685                mEphemeralResolverConnection = null;
2686            }
2687
2688            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2689        } // synchronized (mPackages)
2690        } // synchronized (mInstallLock)
2691
2692        // Now after opening every single application zip, make sure they
2693        // are all flushed.  Not really needed, but keeps things nice and
2694        // tidy.
2695        Runtime.getRuntime().gc();
2696
2697        // The initial scanning above does many calls into installd while
2698        // holding the mPackages lock, but we're mostly interested in yelling
2699        // once we have a booted system.
2700        mInstaller.setWarnIfHeld(mPackages);
2701
2702        // Expose private service for system components to use.
2703        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2704    }
2705
2706    @Override
2707    public boolean isFirstBoot() {
2708        return mFirstBoot;
2709    }
2710
2711    @Override
2712    public boolean isOnlyCoreApps() {
2713        return mOnlyCore;
2714    }
2715
2716    @Override
2717    public boolean isUpgrade() {
2718        return mIsUpgrade;
2719    }
2720
2721    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2722        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2723
2724        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2725                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2726                UserHandle.USER_SYSTEM);
2727        if (matches.size() == 1) {
2728            return matches.get(0).getComponentInfo().packageName;
2729        } else if (matches.size() == 0) {
2730            Log.e(TAG, "There should probably be a verifier, but, none were found");
2731            return null;
2732        }
2733        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2734    }
2735
2736    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2737        synchronized (mPackages) {
2738            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2739            if (libraryEntry == null) {
2740                throw new IllegalStateException("Missing required shared library:" + libraryName);
2741            }
2742            return libraryEntry.apk;
2743        }
2744    }
2745
2746    private @NonNull String getRequiredInstallerLPr() {
2747        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2748        intent.addCategory(Intent.CATEGORY_DEFAULT);
2749        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2750
2751        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2752                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2753                UserHandle.USER_SYSTEM);
2754        if (matches.size() == 1) {
2755            ResolveInfo resolveInfo = matches.get(0);
2756            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2757                throw new RuntimeException("The installer must be a privileged app");
2758            }
2759            return matches.get(0).getComponentInfo().packageName;
2760        } else {
2761            throw new RuntimeException("There must be exactly one installer; found " + matches);
2762        }
2763    }
2764
2765    private @NonNull String getRequiredUninstallerLPr() {
2766        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2767        intent.addCategory(Intent.CATEGORY_DEFAULT);
2768        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2769
2770        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2771                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2772                UserHandle.USER_SYSTEM);
2773        if (resolveInfo == null ||
2774                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2775            throw new RuntimeException("There must be exactly one uninstaller; found "
2776                    + resolveInfo);
2777        }
2778        return resolveInfo.getComponentInfo().packageName;
2779    }
2780
2781    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2782        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2783
2784        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2785                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2786                UserHandle.USER_SYSTEM);
2787        ResolveInfo best = null;
2788        final int N = matches.size();
2789        for (int i = 0; i < N; i++) {
2790            final ResolveInfo cur = matches.get(i);
2791            final String packageName = cur.getComponentInfo().packageName;
2792            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2793                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2794                continue;
2795            }
2796
2797            if (best == null || cur.priority > best.priority) {
2798                best = cur;
2799            }
2800        }
2801
2802        if (best != null) {
2803            return best.getComponentInfo().getComponentName();
2804        } else {
2805            throw new RuntimeException("There must be at least one intent filter verifier");
2806        }
2807    }
2808
2809    private @Nullable ComponentName getEphemeralResolverLPr() {
2810        final String[] packageArray =
2811                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2812        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2813            if (DEBUG_EPHEMERAL) {
2814                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2815            }
2816            return null;
2817        }
2818
2819        final int resolveFlags =
2820                MATCH_DIRECT_BOOT_AWARE
2821                | MATCH_DIRECT_BOOT_UNAWARE
2822                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2823        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2824        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2825                resolveFlags, UserHandle.USER_SYSTEM);
2826
2827        final int N = resolvers.size();
2828        if (N == 0) {
2829            if (DEBUG_EPHEMERAL) {
2830                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2831            }
2832            return null;
2833        }
2834
2835        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2836        for (int i = 0; i < N; i++) {
2837            final ResolveInfo info = resolvers.get(i);
2838
2839            if (info.serviceInfo == null) {
2840                continue;
2841            }
2842
2843            final String packageName = info.serviceInfo.packageName;
2844            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2845                if (DEBUG_EPHEMERAL) {
2846                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2847                            + " pkg: " + packageName + ", info:" + info);
2848                }
2849                continue;
2850            }
2851
2852            if (DEBUG_EPHEMERAL) {
2853                Slog.v(TAG, "Ephemeral resolver found;"
2854                        + " pkg: " + packageName + ", info:" + info);
2855            }
2856            return new ComponentName(packageName, info.serviceInfo.name);
2857        }
2858        if (DEBUG_EPHEMERAL) {
2859            Slog.v(TAG, "Ephemeral resolver NOT found");
2860        }
2861        return null;
2862    }
2863
2864    private @Nullable ComponentName getEphemeralInstallerLPr() {
2865        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2866        intent.addCategory(Intent.CATEGORY_DEFAULT);
2867        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2868
2869        final int resolveFlags =
2870                MATCH_DIRECT_BOOT_AWARE
2871                | MATCH_DIRECT_BOOT_UNAWARE
2872                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2873        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2874                resolveFlags, UserHandle.USER_SYSTEM);
2875        if (matches.size() == 0) {
2876            return null;
2877        } else if (matches.size() == 1) {
2878            return matches.get(0).getComponentInfo().getComponentName();
2879        } else {
2880            throw new RuntimeException(
2881                    "There must be at most one ephemeral installer; found " + matches);
2882        }
2883    }
2884
2885    private void primeDomainVerificationsLPw(int userId) {
2886        if (DEBUG_DOMAIN_VERIFICATION) {
2887            Slog.d(TAG, "Priming domain verifications in user " + userId);
2888        }
2889
2890        SystemConfig systemConfig = SystemConfig.getInstance();
2891        ArraySet<String> packages = systemConfig.getLinkedApps();
2892        ArraySet<String> domains = new ArraySet<String>();
2893
2894        for (String packageName : packages) {
2895            PackageParser.Package pkg = mPackages.get(packageName);
2896            if (pkg != null) {
2897                if (!pkg.isSystemApp()) {
2898                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2899                    continue;
2900                }
2901
2902                domains.clear();
2903                for (PackageParser.Activity a : pkg.activities) {
2904                    for (ActivityIntentInfo filter : a.intents) {
2905                        if (hasValidDomains(filter)) {
2906                            domains.addAll(filter.getHostsList());
2907                        }
2908                    }
2909                }
2910
2911                if (domains.size() > 0) {
2912                    if (DEBUG_DOMAIN_VERIFICATION) {
2913                        Slog.v(TAG, "      + " + packageName);
2914                    }
2915                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2916                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2917                    // and then 'always' in the per-user state actually used for intent resolution.
2918                    final IntentFilterVerificationInfo ivi;
2919                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2920                            new ArrayList<String>(domains));
2921                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2922                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2923                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2924                } else {
2925                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2926                            + "' does not handle web links");
2927                }
2928            } else {
2929                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2930            }
2931        }
2932
2933        scheduleWritePackageRestrictionsLocked(userId);
2934        scheduleWriteSettingsLocked();
2935    }
2936
2937    private void applyFactoryDefaultBrowserLPw(int userId) {
2938        // The default browser app's package name is stored in a string resource,
2939        // with a product-specific overlay used for vendor customization.
2940        String browserPkg = mContext.getResources().getString(
2941                com.android.internal.R.string.default_browser);
2942        if (!TextUtils.isEmpty(browserPkg)) {
2943            // non-empty string => required to be a known package
2944            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2945            if (ps == null) {
2946                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2947                browserPkg = null;
2948            } else {
2949                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2950            }
2951        }
2952
2953        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2954        // default.  If there's more than one, just leave everything alone.
2955        if (browserPkg == null) {
2956            calculateDefaultBrowserLPw(userId);
2957        }
2958    }
2959
2960    private void calculateDefaultBrowserLPw(int userId) {
2961        List<String> allBrowsers = resolveAllBrowserApps(userId);
2962        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2963        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2964    }
2965
2966    private List<String> resolveAllBrowserApps(int userId) {
2967        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2968        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2969                PackageManager.MATCH_ALL, userId);
2970
2971        final int count = list.size();
2972        List<String> result = new ArrayList<String>(count);
2973        for (int i=0; i<count; i++) {
2974            ResolveInfo info = list.get(i);
2975            if (info.activityInfo == null
2976                    || !info.handleAllWebDataURI
2977                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2978                    || result.contains(info.activityInfo.packageName)) {
2979                continue;
2980            }
2981            result.add(info.activityInfo.packageName);
2982        }
2983
2984        return result;
2985    }
2986
2987    private boolean packageIsBrowser(String packageName, int userId) {
2988        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2989                PackageManager.MATCH_ALL, userId);
2990        final int N = list.size();
2991        for (int i = 0; i < N; i++) {
2992            ResolveInfo info = list.get(i);
2993            if (packageName.equals(info.activityInfo.packageName)) {
2994                return true;
2995            }
2996        }
2997        return false;
2998    }
2999
3000    private void checkDefaultBrowser() {
3001        final int myUserId = UserHandle.myUserId();
3002        final String packageName = getDefaultBrowserPackageName(myUserId);
3003        if (packageName != null) {
3004            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3005            if (info == null) {
3006                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3007                synchronized (mPackages) {
3008                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3009                }
3010            }
3011        }
3012    }
3013
3014    @Override
3015    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3016            throws RemoteException {
3017        try {
3018            return super.onTransact(code, data, reply, flags);
3019        } catch (RuntimeException e) {
3020            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3021                Slog.wtf(TAG, "Package Manager Crash", e);
3022            }
3023            throw e;
3024        }
3025    }
3026
3027    static int[] appendInts(int[] cur, int[] add) {
3028        if (add == null) return cur;
3029        if (cur == null) return add;
3030        final int N = add.length;
3031        for (int i=0; i<N; i++) {
3032            cur = appendInt(cur, add[i]);
3033        }
3034        return cur;
3035    }
3036
3037    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3038        if (!sUserManager.exists(userId)) return null;
3039        if (ps == null) {
3040            return null;
3041        }
3042        final PackageParser.Package p = ps.pkg;
3043        if (p == null) {
3044            return null;
3045        }
3046
3047        final PermissionsState permissionsState = ps.getPermissionsState();
3048
3049        // Compute GIDs only if requested
3050        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3051                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3052        // Compute granted permissions only if package has requested permissions
3053        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3054                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3055        final PackageUserState state = ps.readUserState(userId);
3056
3057        return PackageParser.generatePackageInfo(p, gids, flags,
3058                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3059    }
3060
3061    @Override
3062    public void checkPackageStartable(String packageName, int userId) {
3063        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3064
3065        synchronized (mPackages) {
3066            final PackageSetting ps = mSettings.mPackages.get(packageName);
3067            if (ps == null) {
3068                throw new SecurityException("Package " + packageName + " was not found!");
3069            }
3070
3071            if (!ps.getInstalled(userId)) {
3072                throw new SecurityException(
3073                        "Package " + packageName + " was not installed for user " + userId + "!");
3074            }
3075
3076            if (mSafeMode && !ps.isSystem()) {
3077                throw new SecurityException("Package " + packageName + " not a system app!");
3078            }
3079
3080            if (mFrozenPackages.contains(packageName)) {
3081                throw new SecurityException("Package " + packageName + " is currently frozen!");
3082            }
3083
3084            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3085                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3086                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3087            }
3088        }
3089    }
3090
3091    @Override
3092    public boolean isPackageAvailable(String packageName, int userId) {
3093        if (!sUserManager.exists(userId)) return false;
3094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3095                false /* requireFullPermission */, false /* checkShell */, "is package available");
3096        synchronized (mPackages) {
3097            PackageParser.Package p = mPackages.get(packageName);
3098            if (p != null) {
3099                final PackageSetting ps = (PackageSetting) p.mExtras;
3100                if (ps != null) {
3101                    final PackageUserState state = ps.readUserState(userId);
3102                    if (state != null) {
3103                        return PackageParser.isAvailable(state);
3104                    }
3105                }
3106            }
3107        }
3108        return false;
3109    }
3110
3111    @Override
3112    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3113        if (!sUserManager.exists(userId)) return null;
3114        flags = updateFlagsForPackage(flags, userId, packageName);
3115        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3116                false /* requireFullPermission */, false /* checkShell */, "get package info");
3117        // reader
3118        synchronized (mPackages) {
3119            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3120            PackageParser.Package p = null;
3121            if (matchFactoryOnly) {
3122                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3123                if (ps != null) {
3124                    return generatePackageInfo(ps, flags, userId);
3125                }
3126            }
3127            if (p == null) {
3128                p = mPackages.get(packageName);
3129                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3130                    return null;
3131                }
3132            }
3133            if (DEBUG_PACKAGE_INFO)
3134                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3135            if (p != null) {
3136                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3137            }
3138            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3139                final PackageSetting ps = mSettings.mPackages.get(packageName);
3140                return generatePackageInfo(ps, flags, userId);
3141            }
3142        }
3143        return null;
3144    }
3145
3146    @Override
3147    public String[] currentToCanonicalPackageNames(String[] names) {
3148        String[] out = new String[names.length];
3149        // reader
3150        synchronized (mPackages) {
3151            for (int i=names.length-1; i>=0; i--) {
3152                PackageSetting ps = mSettings.mPackages.get(names[i]);
3153                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3154            }
3155        }
3156        return out;
3157    }
3158
3159    @Override
3160    public String[] canonicalToCurrentPackageNames(String[] names) {
3161        String[] out = new String[names.length];
3162        // reader
3163        synchronized (mPackages) {
3164            for (int i=names.length-1; i>=0; i--) {
3165                String cur = mSettings.mRenamedPackages.get(names[i]);
3166                out[i] = cur != null ? cur : names[i];
3167            }
3168        }
3169        return out;
3170    }
3171
3172    @Override
3173    public int getPackageUid(String packageName, int flags, int userId) {
3174        if (!sUserManager.exists(userId)) return -1;
3175        flags = updateFlagsForPackage(flags, userId, packageName);
3176        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3177                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3178
3179        // reader
3180        synchronized (mPackages) {
3181            final PackageParser.Package p = mPackages.get(packageName);
3182            if (p != null && p.isMatch(flags)) {
3183                return UserHandle.getUid(userId, p.applicationInfo.uid);
3184            }
3185            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3186                final PackageSetting ps = mSettings.mPackages.get(packageName);
3187                if (ps != null && ps.isMatch(flags)) {
3188                    return UserHandle.getUid(userId, ps.appId);
3189                }
3190            }
3191        }
3192
3193        return -1;
3194    }
3195
3196    @Override
3197    public int[] getPackageGids(String packageName, int flags, int userId) {
3198        if (!sUserManager.exists(userId)) return null;
3199        flags = updateFlagsForPackage(flags, userId, packageName);
3200        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3201                false /* requireFullPermission */, false /* checkShell */,
3202                "getPackageGids");
3203
3204        // reader
3205        synchronized (mPackages) {
3206            final PackageParser.Package p = mPackages.get(packageName);
3207            if (p != null && p.isMatch(flags)) {
3208                PackageSetting ps = (PackageSetting) p.mExtras;
3209                return ps.getPermissionsState().computeGids(userId);
3210            }
3211            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3212                final PackageSetting ps = mSettings.mPackages.get(packageName);
3213                if (ps != null && ps.isMatch(flags)) {
3214                    return ps.getPermissionsState().computeGids(userId);
3215                }
3216            }
3217        }
3218
3219        return null;
3220    }
3221
3222    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3223        if (bp.perm != null) {
3224            return PackageParser.generatePermissionInfo(bp.perm, flags);
3225        }
3226        PermissionInfo pi = new PermissionInfo();
3227        pi.name = bp.name;
3228        pi.packageName = bp.sourcePackage;
3229        pi.nonLocalizedLabel = bp.name;
3230        pi.protectionLevel = bp.protectionLevel;
3231        return pi;
3232    }
3233
3234    @Override
3235    public PermissionInfo getPermissionInfo(String name, int flags) {
3236        // reader
3237        synchronized (mPackages) {
3238            final BasePermission p = mSettings.mPermissions.get(name);
3239            if (p != null) {
3240                return generatePermissionInfo(p, flags);
3241            }
3242            return null;
3243        }
3244    }
3245
3246    @Override
3247    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3248            int flags) {
3249        // reader
3250        synchronized (mPackages) {
3251            if (group != null && !mPermissionGroups.containsKey(group)) {
3252                // This is thrown as NameNotFoundException
3253                return null;
3254            }
3255
3256            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3257            for (BasePermission p : mSettings.mPermissions.values()) {
3258                if (group == null) {
3259                    if (p.perm == null || p.perm.info.group == null) {
3260                        out.add(generatePermissionInfo(p, flags));
3261                    }
3262                } else {
3263                    if (p.perm != null && group.equals(p.perm.info.group)) {
3264                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3265                    }
3266                }
3267            }
3268            return new ParceledListSlice<>(out);
3269        }
3270    }
3271
3272    @Override
3273    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3274        // reader
3275        synchronized (mPackages) {
3276            return PackageParser.generatePermissionGroupInfo(
3277                    mPermissionGroups.get(name), flags);
3278        }
3279    }
3280
3281    @Override
3282    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3283        // reader
3284        synchronized (mPackages) {
3285            final int N = mPermissionGroups.size();
3286            ArrayList<PermissionGroupInfo> out
3287                    = new ArrayList<PermissionGroupInfo>(N);
3288            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3289                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3290            }
3291            return new ParceledListSlice<>(out);
3292        }
3293    }
3294
3295    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3296            int userId) {
3297        if (!sUserManager.exists(userId)) return null;
3298        PackageSetting ps = mSettings.mPackages.get(packageName);
3299        if (ps != null) {
3300            if (ps.pkg == null) {
3301                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3302                if (pInfo != null) {
3303                    return pInfo.applicationInfo;
3304                }
3305                return null;
3306            }
3307            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3308                    ps.readUserState(userId), userId);
3309        }
3310        return null;
3311    }
3312
3313    @Override
3314    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3315        if (!sUserManager.exists(userId)) return null;
3316        flags = updateFlagsForApplication(flags, userId, packageName);
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3318                false /* requireFullPermission */, false /* checkShell */, "get application info");
3319        // writer
3320        synchronized (mPackages) {
3321            PackageParser.Package p = mPackages.get(packageName);
3322            if (DEBUG_PACKAGE_INFO) Log.v(
3323                    TAG, "getApplicationInfo " + packageName
3324                    + ": " + p);
3325            if (p != null) {
3326                PackageSetting ps = mSettings.mPackages.get(packageName);
3327                if (ps == null) return null;
3328                // Note: isEnabledLP() does not apply here - always return info
3329                return PackageParser.generateApplicationInfo(
3330                        p, flags, ps.readUserState(userId), userId);
3331            }
3332            if ("android".equals(packageName)||"system".equals(packageName)) {
3333                return mAndroidApplication;
3334            }
3335            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3336                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3337            }
3338        }
3339        return null;
3340    }
3341
3342    @Override
3343    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3344            final IPackageDataObserver observer) {
3345        mContext.enforceCallingOrSelfPermission(
3346                android.Manifest.permission.CLEAR_APP_CACHE, null);
3347        // Queue up an async operation since clearing cache may take a little while.
3348        mHandler.post(new Runnable() {
3349            public void run() {
3350                mHandler.removeCallbacks(this);
3351                boolean success = true;
3352                synchronized (mInstallLock) {
3353                    try {
3354                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3355                    } catch (InstallerException e) {
3356                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3357                        success = false;
3358                    }
3359                }
3360                if (observer != null) {
3361                    try {
3362                        observer.onRemoveCompleted(null, success);
3363                    } catch (RemoteException e) {
3364                        Slog.w(TAG, "RemoveException when invoking call back");
3365                    }
3366                }
3367            }
3368        });
3369    }
3370
3371    @Override
3372    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3373            final IntentSender pi) {
3374        mContext.enforceCallingOrSelfPermission(
3375                android.Manifest.permission.CLEAR_APP_CACHE, null);
3376        // Queue up an async operation since clearing cache may take a little while.
3377        mHandler.post(new Runnable() {
3378            public void run() {
3379                mHandler.removeCallbacks(this);
3380                boolean success = true;
3381                synchronized (mInstallLock) {
3382                    try {
3383                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3384                    } catch (InstallerException e) {
3385                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3386                        success = false;
3387                    }
3388                }
3389                if(pi != null) {
3390                    try {
3391                        // Callback via pending intent
3392                        int code = success ? 1 : 0;
3393                        pi.sendIntent(null, code, null,
3394                                null, null);
3395                    } catch (SendIntentException e1) {
3396                        Slog.i(TAG, "Failed to send pending intent");
3397                    }
3398                }
3399            }
3400        });
3401    }
3402
3403    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3404        synchronized (mInstallLock) {
3405            try {
3406                mInstaller.freeCache(volumeUuid, freeStorageSize);
3407            } catch (InstallerException e) {
3408                throw new IOException("Failed to free enough space", e);
3409            }
3410        }
3411    }
3412
3413    /**
3414     * Update given flags based on encryption status of current user.
3415     */
3416    private int updateFlags(int flags, int userId) {
3417        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3418                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3419            // Caller expressed an explicit opinion about what encryption
3420            // aware/unaware components they want to see, so fall through and
3421            // give them what they want
3422        } else {
3423            // Caller expressed no opinion, so match based on user state
3424            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3425                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3426            } else {
3427                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3428            }
3429        }
3430        return flags;
3431    }
3432
3433    private UserManagerInternal getUserManagerInternal() {
3434        if (mUserManagerInternal == null) {
3435            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3436        }
3437        return mUserManagerInternal;
3438    }
3439
3440    /**
3441     * Update given flags when being used to request {@link PackageInfo}.
3442     */
3443    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3444        boolean triaged = true;
3445        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3446                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3447            // Caller is asking for component details, so they'd better be
3448            // asking for specific encryption matching behavior, or be triaged
3449            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3450                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3451                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3452                triaged = false;
3453            }
3454        }
3455        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3456                | PackageManager.MATCH_SYSTEM_ONLY
3457                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3458            triaged = false;
3459        }
3460        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3461            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3462                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3463        }
3464        return updateFlags(flags, userId);
3465    }
3466
3467    /**
3468     * Update given flags when being used to request {@link ApplicationInfo}.
3469     */
3470    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3471        return updateFlagsForPackage(flags, userId, cookie);
3472    }
3473
3474    /**
3475     * Update given flags when being used to request {@link ComponentInfo}.
3476     */
3477    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3478        if (cookie instanceof Intent) {
3479            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3480                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3481            }
3482        }
3483
3484        boolean triaged = true;
3485        // Caller is asking for component details, so they'd better be
3486        // asking for specific encryption matching behavior, or be triaged
3487        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3488                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3489                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3490            triaged = false;
3491        }
3492        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3493            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3494                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3495        }
3496
3497        return updateFlags(flags, userId);
3498    }
3499
3500    /**
3501     * Update given flags when being used to request {@link ResolveInfo}.
3502     */
3503    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3504        // Safe mode means we shouldn't match any third-party components
3505        if (mSafeMode) {
3506            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3507        }
3508
3509        return updateFlagsForComponent(flags, userId, cookie);
3510    }
3511
3512    @Override
3513    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3514        if (!sUserManager.exists(userId)) return null;
3515        flags = updateFlagsForComponent(flags, userId, component);
3516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3517                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3518        synchronized (mPackages) {
3519            PackageParser.Activity a = mActivities.mActivities.get(component);
3520
3521            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3522            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3523                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3524                if (ps == null) return null;
3525                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3526                        userId);
3527            }
3528            if (mResolveComponentName.equals(component)) {
3529                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3530                        new PackageUserState(), userId);
3531            }
3532        }
3533        return null;
3534    }
3535
3536    @Override
3537    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3538            String resolvedType) {
3539        synchronized (mPackages) {
3540            if (component.equals(mResolveComponentName)) {
3541                // The resolver supports EVERYTHING!
3542                return true;
3543            }
3544            PackageParser.Activity a = mActivities.mActivities.get(component);
3545            if (a == null) {
3546                return false;
3547            }
3548            for (int i=0; i<a.intents.size(); i++) {
3549                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3550                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3551                    return true;
3552                }
3553            }
3554            return false;
3555        }
3556    }
3557
3558    @Override
3559    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3560        if (!sUserManager.exists(userId)) return null;
3561        flags = updateFlagsForComponent(flags, userId, component);
3562        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3563                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3564        synchronized (mPackages) {
3565            PackageParser.Activity a = mReceivers.mActivities.get(component);
3566            if (DEBUG_PACKAGE_INFO) Log.v(
3567                TAG, "getReceiverInfo " + component + ": " + a);
3568            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3569                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3570                if (ps == null) return null;
3571                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3572                        userId);
3573            }
3574        }
3575        return null;
3576    }
3577
3578    @Override
3579    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3580        if (!sUserManager.exists(userId)) return null;
3581        flags = updateFlagsForComponent(flags, userId, component);
3582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3583                false /* requireFullPermission */, false /* checkShell */, "get service info");
3584        synchronized (mPackages) {
3585            PackageParser.Service s = mServices.mServices.get(component);
3586            if (DEBUG_PACKAGE_INFO) Log.v(
3587                TAG, "getServiceInfo " + component + ": " + s);
3588            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3589                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3590                if (ps == null) return null;
3591                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3592                        userId);
3593            }
3594        }
3595        return null;
3596    }
3597
3598    @Override
3599    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3600        if (!sUserManager.exists(userId)) return null;
3601        flags = updateFlagsForComponent(flags, userId, component);
3602        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3603                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3604        synchronized (mPackages) {
3605            PackageParser.Provider p = mProviders.mProviders.get(component);
3606            if (DEBUG_PACKAGE_INFO) Log.v(
3607                TAG, "getProviderInfo " + component + ": " + p);
3608            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3609                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3610                if (ps == null) return null;
3611                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3612                        userId);
3613            }
3614        }
3615        return null;
3616    }
3617
3618    @Override
3619    public String[] getSystemSharedLibraryNames() {
3620        Set<String> libSet;
3621        synchronized (mPackages) {
3622            libSet = mSharedLibraries.keySet();
3623            int size = libSet.size();
3624            if (size > 0) {
3625                String[] libs = new String[size];
3626                libSet.toArray(libs);
3627                return libs;
3628            }
3629        }
3630        return null;
3631    }
3632
3633    @Override
3634    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3635        synchronized (mPackages) {
3636            return mServicesSystemSharedLibraryPackageName;
3637        }
3638    }
3639
3640    @Override
3641    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3642        synchronized (mPackages) {
3643            return mSharedSystemSharedLibraryPackageName;
3644        }
3645    }
3646
3647    @Override
3648    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3649        synchronized (mPackages) {
3650            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3651
3652            final FeatureInfo fi = new FeatureInfo();
3653            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3654                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3655            res.add(fi);
3656
3657            return new ParceledListSlice<>(res);
3658        }
3659    }
3660
3661    @Override
3662    public boolean hasSystemFeature(String name, int version) {
3663        synchronized (mPackages) {
3664            final FeatureInfo feat = mAvailableFeatures.get(name);
3665            if (feat == null) {
3666                return false;
3667            } else {
3668                return feat.version >= version;
3669            }
3670        }
3671    }
3672
3673    @Override
3674    public int checkPermission(String permName, String pkgName, int userId) {
3675        if (!sUserManager.exists(userId)) {
3676            return PackageManager.PERMISSION_DENIED;
3677        }
3678
3679        synchronized (mPackages) {
3680            final PackageParser.Package p = mPackages.get(pkgName);
3681            if (p != null && p.mExtras != null) {
3682                final PackageSetting ps = (PackageSetting) p.mExtras;
3683                final PermissionsState permissionsState = ps.getPermissionsState();
3684                if (permissionsState.hasPermission(permName, userId)) {
3685                    return PackageManager.PERMISSION_GRANTED;
3686                }
3687                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3688                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3689                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3690                    return PackageManager.PERMISSION_GRANTED;
3691                }
3692            }
3693        }
3694
3695        return PackageManager.PERMISSION_DENIED;
3696    }
3697
3698    @Override
3699    public int checkUidPermission(String permName, int uid) {
3700        final int userId = UserHandle.getUserId(uid);
3701
3702        if (!sUserManager.exists(userId)) {
3703            return PackageManager.PERMISSION_DENIED;
3704        }
3705
3706        synchronized (mPackages) {
3707            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3708            if (obj != null) {
3709                final SettingBase ps = (SettingBase) obj;
3710                final PermissionsState permissionsState = ps.getPermissionsState();
3711                if (permissionsState.hasPermission(permName, userId)) {
3712                    return PackageManager.PERMISSION_GRANTED;
3713                }
3714                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3715                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3716                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3717                    return PackageManager.PERMISSION_GRANTED;
3718                }
3719            } else {
3720                ArraySet<String> perms = mSystemPermissions.get(uid);
3721                if (perms != null) {
3722                    if (perms.contains(permName)) {
3723                        return PackageManager.PERMISSION_GRANTED;
3724                    }
3725                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3726                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3727                        return PackageManager.PERMISSION_GRANTED;
3728                    }
3729                }
3730            }
3731        }
3732
3733        return PackageManager.PERMISSION_DENIED;
3734    }
3735
3736    @Override
3737    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3738        if (UserHandle.getCallingUserId() != userId) {
3739            mContext.enforceCallingPermission(
3740                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3741                    "isPermissionRevokedByPolicy for user " + userId);
3742        }
3743
3744        if (checkPermission(permission, packageName, userId)
3745                == PackageManager.PERMISSION_GRANTED) {
3746            return false;
3747        }
3748
3749        final long identity = Binder.clearCallingIdentity();
3750        try {
3751            final int flags = getPermissionFlags(permission, packageName, userId);
3752            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3753        } finally {
3754            Binder.restoreCallingIdentity(identity);
3755        }
3756    }
3757
3758    @Override
3759    public String getPermissionControllerPackageName() {
3760        synchronized (mPackages) {
3761            return mRequiredInstallerPackage;
3762        }
3763    }
3764
3765    /**
3766     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3767     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3768     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3769     * @param message the message to log on security exception
3770     */
3771    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3772            boolean checkShell, String message) {
3773        if (userId < 0) {
3774            throw new IllegalArgumentException("Invalid userId " + userId);
3775        }
3776        if (checkShell) {
3777            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3778        }
3779        if (userId == UserHandle.getUserId(callingUid)) return;
3780        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3781            if (requireFullPermission) {
3782                mContext.enforceCallingOrSelfPermission(
3783                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3784            } else {
3785                try {
3786                    mContext.enforceCallingOrSelfPermission(
3787                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3788                } catch (SecurityException se) {
3789                    mContext.enforceCallingOrSelfPermission(
3790                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3791                }
3792            }
3793        }
3794    }
3795
3796    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3797        if (callingUid == Process.SHELL_UID) {
3798            if (userHandle >= 0
3799                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3800                throw new SecurityException("Shell does not have permission to access user "
3801                        + userHandle);
3802            } else if (userHandle < 0) {
3803                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3804                        + Debug.getCallers(3));
3805            }
3806        }
3807    }
3808
3809    private BasePermission findPermissionTreeLP(String permName) {
3810        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3811            if (permName.startsWith(bp.name) &&
3812                    permName.length() > bp.name.length() &&
3813                    permName.charAt(bp.name.length()) == '.') {
3814                return bp;
3815            }
3816        }
3817        return null;
3818    }
3819
3820    private BasePermission checkPermissionTreeLP(String permName) {
3821        if (permName != null) {
3822            BasePermission bp = findPermissionTreeLP(permName);
3823            if (bp != null) {
3824                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3825                    return bp;
3826                }
3827                throw new SecurityException("Calling uid "
3828                        + Binder.getCallingUid()
3829                        + " is not allowed to add to permission tree "
3830                        + bp.name + " owned by uid " + bp.uid);
3831            }
3832        }
3833        throw new SecurityException("No permission tree found for " + permName);
3834    }
3835
3836    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3837        if (s1 == null) {
3838            return s2 == null;
3839        }
3840        if (s2 == null) {
3841            return false;
3842        }
3843        if (s1.getClass() != s2.getClass()) {
3844            return false;
3845        }
3846        return s1.equals(s2);
3847    }
3848
3849    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3850        if (pi1.icon != pi2.icon) return false;
3851        if (pi1.logo != pi2.logo) return false;
3852        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3853        if (!compareStrings(pi1.name, pi2.name)) return false;
3854        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3855        // We'll take care of setting this one.
3856        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3857        // These are not currently stored in settings.
3858        //if (!compareStrings(pi1.group, pi2.group)) return false;
3859        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3860        //if (pi1.labelRes != pi2.labelRes) return false;
3861        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3862        return true;
3863    }
3864
3865    int permissionInfoFootprint(PermissionInfo info) {
3866        int size = info.name.length();
3867        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3868        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3869        return size;
3870    }
3871
3872    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3873        int size = 0;
3874        for (BasePermission perm : mSettings.mPermissions.values()) {
3875            if (perm.uid == tree.uid) {
3876                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3877            }
3878        }
3879        return size;
3880    }
3881
3882    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3883        // We calculate the max size of permissions defined by this uid and throw
3884        // if that plus the size of 'info' would exceed our stated maximum.
3885        if (tree.uid != Process.SYSTEM_UID) {
3886            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3887            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3888                throw new SecurityException("Permission tree size cap exceeded");
3889            }
3890        }
3891    }
3892
3893    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3894        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3895            throw new SecurityException("Label must be specified in permission");
3896        }
3897        BasePermission tree = checkPermissionTreeLP(info.name);
3898        BasePermission bp = mSettings.mPermissions.get(info.name);
3899        boolean added = bp == null;
3900        boolean changed = true;
3901        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3902        if (added) {
3903            enforcePermissionCapLocked(info, tree);
3904            bp = new BasePermission(info.name, tree.sourcePackage,
3905                    BasePermission.TYPE_DYNAMIC);
3906        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3907            throw new SecurityException(
3908                    "Not allowed to modify non-dynamic permission "
3909                    + info.name);
3910        } else {
3911            if (bp.protectionLevel == fixedLevel
3912                    && bp.perm.owner.equals(tree.perm.owner)
3913                    && bp.uid == tree.uid
3914                    && comparePermissionInfos(bp.perm.info, info)) {
3915                changed = false;
3916            }
3917        }
3918        bp.protectionLevel = fixedLevel;
3919        info = new PermissionInfo(info);
3920        info.protectionLevel = fixedLevel;
3921        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3922        bp.perm.info.packageName = tree.perm.info.packageName;
3923        bp.uid = tree.uid;
3924        if (added) {
3925            mSettings.mPermissions.put(info.name, bp);
3926        }
3927        if (changed) {
3928            if (!async) {
3929                mSettings.writeLPr();
3930            } else {
3931                scheduleWriteSettingsLocked();
3932            }
3933        }
3934        return added;
3935    }
3936
3937    @Override
3938    public boolean addPermission(PermissionInfo info) {
3939        synchronized (mPackages) {
3940            return addPermissionLocked(info, false);
3941        }
3942    }
3943
3944    @Override
3945    public boolean addPermissionAsync(PermissionInfo info) {
3946        synchronized (mPackages) {
3947            return addPermissionLocked(info, true);
3948        }
3949    }
3950
3951    @Override
3952    public void removePermission(String name) {
3953        synchronized (mPackages) {
3954            checkPermissionTreeLP(name);
3955            BasePermission bp = mSettings.mPermissions.get(name);
3956            if (bp != null) {
3957                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3958                    throw new SecurityException(
3959                            "Not allowed to modify non-dynamic permission "
3960                            + name);
3961                }
3962                mSettings.mPermissions.remove(name);
3963                mSettings.writeLPr();
3964            }
3965        }
3966    }
3967
3968    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3969            BasePermission bp) {
3970        int index = pkg.requestedPermissions.indexOf(bp.name);
3971        if (index == -1) {
3972            throw new SecurityException("Package " + pkg.packageName
3973                    + " has not requested permission " + bp.name);
3974        }
3975        if (!bp.isRuntime() && !bp.isDevelopment()) {
3976            throw new SecurityException("Permission " + bp.name
3977                    + " is not a changeable permission type");
3978        }
3979    }
3980
3981    @Override
3982    public void grantRuntimePermission(String packageName, String name, final int userId) {
3983        if (!sUserManager.exists(userId)) {
3984            Log.e(TAG, "No such user:" + userId);
3985            return;
3986        }
3987
3988        mContext.enforceCallingOrSelfPermission(
3989                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3990                "grantRuntimePermission");
3991
3992        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3993                true /* requireFullPermission */, true /* checkShell */,
3994                "grantRuntimePermission");
3995
3996        final int uid;
3997        final SettingBase sb;
3998
3999        synchronized (mPackages) {
4000            final PackageParser.Package pkg = mPackages.get(packageName);
4001            if (pkg == null) {
4002                throw new IllegalArgumentException("Unknown package: " + packageName);
4003            }
4004
4005            final BasePermission bp = mSettings.mPermissions.get(name);
4006            if (bp == null) {
4007                throw new IllegalArgumentException("Unknown permission: " + name);
4008            }
4009
4010            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4011
4012            // If a permission review is required for legacy apps we represent
4013            // their permissions as always granted runtime ones since we need
4014            // to keep the review required permission flag per user while an
4015            // install permission's state is shared across all users.
4016            if (Build.PERMISSIONS_REVIEW_REQUIRED
4017                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4018                    && bp.isRuntime()) {
4019                return;
4020            }
4021
4022            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4023            sb = (SettingBase) pkg.mExtras;
4024            if (sb == null) {
4025                throw new IllegalArgumentException("Unknown package: " + packageName);
4026            }
4027
4028            final PermissionsState permissionsState = sb.getPermissionsState();
4029
4030            final int flags = permissionsState.getPermissionFlags(name, userId);
4031            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4032                throw new SecurityException("Cannot grant system fixed permission "
4033                        + name + " for package " + packageName);
4034            }
4035
4036            if (bp.isDevelopment()) {
4037                // Development permissions must be handled specially, since they are not
4038                // normal runtime permissions.  For now they apply to all users.
4039                if (permissionsState.grantInstallPermission(bp) !=
4040                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4041                    scheduleWriteSettingsLocked();
4042                }
4043                return;
4044            }
4045
4046            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4047                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4048                return;
4049            }
4050
4051            final int result = permissionsState.grantRuntimePermission(bp, userId);
4052            switch (result) {
4053                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4054                    return;
4055                }
4056
4057                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4058                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4059                    mHandler.post(new Runnable() {
4060                        @Override
4061                        public void run() {
4062                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4063                        }
4064                    });
4065                }
4066                break;
4067            }
4068
4069            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4070
4071            // Not critical if that is lost - app has to request again.
4072            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4073        }
4074
4075        // Only need to do this if user is initialized. Otherwise it's a new user
4076        // and there are no processes running as the user yet and there's no need
4077        // to make an expensive call to remount processes for the changed permissions.
4078        if (READ_EXTERNAL_STORAGE.equals(name)
4079                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4080            final long token = Binder.clearCallingIdentity();
4081            try {
4082                if (sUserManager.isInitialized(userId)) {
4083                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4084                            MountServiceInternal.class);
4085                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4086                }
4087            } finally {
4088                Binder.restoreCallingIdentity(token);
4089            }
4090        }
4091    }
4092
4093    @Override
4094    public void revokeRuntimePermission(String packageName, String name, int userId) {
4095        if (!sUserManager.exists(userId)) {
4096            Log.e(TAG, "No such user:" + userId);
4097            return;
4098        }
4099
4100        mContext.enforceCallingOrSelfPermission(
4101                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4102                "revokeRuntimePermission");
4103
4104        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4105                true /* requireFullPermission */, true /* checkShell */,
4106                "revokeRuntimePermission");
4107
4108        final int appId;
4109
4110        synchronized (mPackages) {
4111            final PackageParser.Package pkg = mPackages.get(packageName);
4112            if (pkg == null) {
4113                throw new IllegalArgumentException("Unknown package: " + packageName);
4114            }
4115
4116            final BasePermission bp = mSettings.mPermissions.get(name);
4117            if (bp == null) {
4118                throw new IllegalArgumentException("Unknown permission: " + name);
4119            }
4120
4121            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4122
4123            // If a permission review is required for legacy apps we represent
4124            // their permissions as always granted runtime ones since we need
4125            // to keep the review required permission flag per user while an
4126            // install permission's state is shared across all users.
4127            if (Build.PERMISSIONS_REVIEW_REQUIRED
4128                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4129                    && bp.isRuntime()) {
4130                return;
4131            }
4132
4133            SettingBase sb = (SettingBase) pkg.mExtras;
4134            if (sb == null) {
4135                throw new IllegalArgumentException("Unknown package: " + packageName);
4136            }
4137
4138            final PermissionsState permissionsState = sb.getPermissionsState();
4139
4140            final int flags = permissionsState.getPermissionFlags(name, userId);
4141            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4142                throw new SecurityException("Cannot revoke system fixed permission "
4143                        + name + " for package " + packageName);
4144            }
4145
4146            if (bp.isDevelopment()) {
4147                // Development permissions must be handled specially, since they are not
4148                // normal runtime permissions.  For now they apply to all users.
4149                if (permissionsState.revokeInstallPermission(bp) !=
4150                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4151                    scheduleWriteSettingsLocked();
4152                }
4153                return;
4154            }
4155
4156            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4157                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4158                return;
4159            }
4160
4161            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4162
4163            // Critical, after this call app should never have the permission.
4164            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4165
4166            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4167        }
4168
4169        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4170    }
4171
4172    @Override
4173    public void resetRuntimePermissions() {
4174        mContext.enforceCallingOrSelfPermission(
4175                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4176                "revokeRuntimePermission");
4177
4178        int callingUid = Binder.getCallingUid();
4179        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4180            mContext.enforceCallingOrSelfPermission(
4181                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4182                    "resetRuntimePermissions");
4183        }
4184
4185        synchronized (mPackages) {
4186            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4187            for (int userId : UserManagerService.getInstance().getUserIds()) {
4188                final int packageCount = mPackages.size();
4189                for (int i = 0; i < packageCount; i++) {
4190                    PackageParser.Package pkg = mPackages.valueAt(i);
4191                    if (!(pkg.mExtras instanceof PackageSetting)) {
4192                        continue;
4193                    }
4194                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4195                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4196                }
4197            }
4198        }
4199    }
4200
4201    @Override
4202    public int getPermissionFlags(String name, String packageName, int userId) {
4203        if (!sUserManager.exists(userId)) {
4204            return 0;
4205        }
4206
4207        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4208
4209        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4210                true /* requireFullPermission */, false /* checkShell */,
4211                "getPermissionFlags");
4212
4213        synchronized (mPackages) {
4214            final PackageParser.Package pkg = mPackages.get(packageName);
4215            if (pkg == null) {
4216                return 0;
4217            }
4218
4219            final BasePermission bp = mSettings.mPermissions.get(name);
4220            if (bp == null) {
4221                return 0;
4222            }
4223
4224            SettingBase sb = (SettingBase) pkg.mExtras;
4225            if (sb == null) {
4226                return 0;
4227            }
4228
4229            PermissionsState permissionsState = sb.getPermissionsState();
4230            return permissionsState.getPermissionFlags(name, userId);
4231        }
4232    }
4233
4234    @Override
4235    public void updatePermissionFlags(String name, String packageName, int flagMask,
4236            int flagValues, int userId) {
4237        if (!sUserManager.exists(userId)) {
4238            return;
4239        }
4240
4241        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4242
4243        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4244                true /* requireFullPermission */, true /* checkShell */,
4245                "updatePermissionFlags");
4246
4247        // Only the system can change these flags and nothing else.
4248        if (getCallingUid() != Process.SYSTEM_UID) {
4249            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4250            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4251            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4252            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4253            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4254        }
4255
4256        synchronized (mPackages) {
4257            final PackageParser.Package pkg = mPackages.get(packageName);
4258            if (pkg == null) {
4259                throw new IllegalArgumentException("Unknown package: " + packageName);
4260            }
4261
4262            final BasePermission bp = mSettings.mPermissions.get(name);
4263            if (bp == null) {
4264                throw new IllegalArgumentException("Unknown permission: " + name);
4265            }
4266
4267            SettingBase sb = (SettingBase) pkg.mExtras;
4268            if (sb == null) {
4269                throw new IllegalArgumentException("Unknown package: " + packageName);
4270            }
4271
4272            PermissionsState permissionsState = sb.getPermissionsState();
4273
4274            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4275
4276            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4277                // Install and runtime permissions are stored in different places,
4278                // so figure out what permission changed and persist the change.
4279                if (permissionsState.getInstallPermissionState(name) != null) {
4280                    scheduleWriteSettingsLocked();
4281                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4282                        || hadState) {
4283                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4284                }
4285            }
4286        }
4287    }
4288
4289    /**
4290     * Update the permission flags for all packages and runtime permissions of a user in order
4291     * to allow device or profile owner to remove POLICY_FIXED.
4292     */
4293    @Override
4294    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4295        if (!sUserManager.exists(userId)) {
4296            return;
4297        }
4298
4299        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4300
4301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4302                true /* requireFullPermission */, true /* checkShell */,
4303                "updatePermissionFlagsForAllApps");
4304
4305        // Only the system can change system fixed flags.
4306        if (getCallingUid() != Process.SYSTEM_UID) {
4307            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4308            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4309        }
4310
4311        synchronized (mPackages) {
4312            boolean changed = false;
4313            final int packageCount = mPackages.size();
4314            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4315                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4316                SettingBase sb = (SettingBase) pkg.mExtras;
4317                if (sb == null) {
4318                    continue;
4319                }
4320                PermissionsState permissionsState = sb.getPermissionsState();
4321                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4322                        userId, flagMask, flagValues);
4323            }
4324            if (changed) {
4325                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4326            }
4327        }
4328    }
4329
4330    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4331        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4332                != PackageManager.PERMISSION_GRANTED
4333            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4334                != PackageManager.PERMISSION_GRANTED) {
4335            throw new SecurityException(message + " requires "
4336                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4337                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4338        }
4339    }
4340
4341    @Override
4342    public boolean shouldShowRequestPermissionRationale(String permissionName,
4343            String packageName, int userId) {
4344        if (UserHandle.getCallingUserId() != userId) {
4345            mContext.enforceCallingPermission(
4346                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4347                    "canShowRequestPermissionRationale for user " + userId);
4348        }
4349
4350        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4351        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4352            return false;
4353        }
4354
4355        if (checkPermission(permissionName, packageName, userId)
4356                == PackageManager.PERMISSION_GRANTED) {
4357            return false;
4358        }
4359
4360        final int flags;
4361
4362        final long identity = Binder.clearCallingIdentity();
4363        try {
4364            flags = getPermissionFlags(permissionName,
4365                    packageName, userId);
4366        } finally {
4367            Binder.restoreCallingIdentity(identity);
4368        }
4369
4370        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4371                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4372                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4373
4374        if ((flags & fixedFlags) != 0) {
4375            return false;
4376        }
4377
4378        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4379    }
4380
4381    @Override
4382    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4383        mContext.enforceCallingOrSelfPermission(
4384                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4385                "addOnPermissionsChangeListener");
4386
4387        synchronized (mPackages) {
4388            mOnPermissionChangeListeners.addListenerLocked(listener);
4389        }
4390    }
4391
4392    @Override
4393    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4394        synchronized (mPackages) {
4395            mOnPermissionChangeListeners.removeListenerLocked(listener);
4396        }
4397    }
4398
4399    @Override
4400    public boolean isProtectedBroadcast(String actionName) {
4401        synchronized (mPackages) {
4402            if (mProtectedBroadcasts.contains(actionName)) {
4403                return true;
4404            } else if (actionName != null) {
4405                // TODO: remove these terrible hacks
4406                if (actionName.startsWith("android.net.netmon.lingerExpired")
4407                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4408                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4409                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4410                    return true;
4411                }
4412            }
4413        }
4414        return false;
4415    }
4416
4417    @Override
4418    public int checkSignatures(String pkg1, String pkg2) {
4419        synchronized (mPackages) {
4420            final PackageParser.Package p1 = mPackages.get(pkg1);
4421            final PackageParser.Package p2 = mPackages.get(pkg2);
4422            if (p1 == null || p1.mExtras == null
4423                    || p2 == null || p2.mExtras == null) {
4424                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4425            }
4426            return compareSignatures(p1.mSignatures, p2.mSignatures);
4427        }
4428    }
4429
4430    @Override
4431    public int checkUidSignatures(int uid1, int uid2) {
4432        // Map to base uids.
4433        uid1 = UserHandle.getAppId(uid1);
4434        uid2 = UserHandle.getAppId(uid2);
4435        // reader
4436        synchronized (mPackages) {
4437            Signature[] s1;
4438            Signature[] s2;
4439            Object obj = mSettings.getUserIdLPr(uid1);
4440            if (obj != null) {
4441                if (obj instanceof SharedUserSetting) {
4442                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4443                } else if (obj instanceof PackageSetting) {
4444                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4445                } else {
4446                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4447                }
4448            } else {
4449                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4450            }
4451            obj = mSettings.getUserIdLPr(uid2);
4452            if (obj != null) {
4453                if (obj instanceof SharedUserSetting) {
4454                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4455                } else if (obj instanceof PackageSetting) {
4456                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4457                } else {
4458                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4459                }
4460            } else {
4461                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4462            }
4463            return compareSignatures(s1, s2);
4464        }
4465    }
4466
4467    /**
4468     * This method should typically only be used when granting or revoking
4469     * permissions, since the app may immediately restart after this call.
4470     * <p>
4471     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4472     * guard your work against the app being relaunched.
4473     */
4474    private void killUid(int appId, int userId, String reason) {
4475        final long identity = Binder.clearCallingIdentity();
4476        try {
4477            IActivityManager am = ActivityManagerNative.getDefault();
4478            if (am != null) {
4479                try {
4480                    am.killUid(appId, userId, reason);
4481                } catch (RemoteException e) {
4482                    /* ignore - same process */
4483                }
4484            }
4485        } finally {
4486            Binder.restoreCallingIdentity(identity);
4487        }
4488    }
4489
4490    /**
4491     * Compares two sets of signatures. Returns:
4492     * <br />
4493     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4494     * <br />
4495     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4496     * <br />
4497     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4498     * <br />
4499     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4500     * <br />
4501     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4502     */
4503    static int compareSignatures(Signature[] s1, Signature[] s2) {
4504        if (s1 == null) {
4505            return s2 == null
4506                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4507                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4508        }
4509
4510        if (s2 == null) {
4511            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4512        }
4513
4514        if (s1.length != s2.length) {
4515            return PackageManager.SIGNATURE_NO_MATCH;
4516        }
4517
4518        // Since both signature sets are of size 1, we can compare without HashSets.
4519        if (s1.length == 1) {
4520            return s1[0].equals(s2[0]) ?
4521                    PackageManager.SIGNATURE_MATCH :
4522                    PackageManager.SIGNATURE_NO_MATCH;
4523        }
4524
4525        ArraySet<Signature> set1 = new ArraySet<Signature>();
4526        for (Signature sig : s1) {
4527            set1.add(sig);
4528        }
4529        ArraySet<Signature> set2 = new ArraySet<Signature>();
4530        for (Signature sig : s2) {
4531            set2.add(sig);
4532        }
4533        // Make sure s2 contains all signatures in s1.
4534        if (set1.equals(set2)) {
4535            return PackageManager.SIGNATURE_MATCH;
4536        }
4537        return PackageManager.SIGNATURE_NO_MATCH;
4538    }
4539
4540    /**
4541     * If the database version for this type of package (internal storage or
4542     * external storage) is less than the version where package signatures
4543     * were updated, return true.
4544     */
4545    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4546        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4547        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4548    }
4549
4550    /**
4551     * Used for backward compatibility to make sure any packages with
4552     * certificate chains get upgraded to the new style. {@code existingSigs}
4553     * will be in the old format (since they were stored on disk from before the
4554     * system upgrade) and {@code scannedSigs} will be in the newer format.
4555     */
4556    private int compareSignaturesCompat(PackageSignatures existingSigs,
4557            PackageParser.Package scannedPkg) {
4558        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4559            return PackageManager.SIGNATURE_NO_MATCH;
4560        }
4561
4562        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4563        for (Signature sig : existingSigs.mSignatures) {
4564            existingSet.add(sig);
4565        }
4566        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4567        for (Signature sig : scannedPkg.mSignatures) {
4568            try {
4569                Signature[] chainSignatures = sig.getChainSignatures();
4570                for (Signature chainSig : chainSignatures) {
4571                    scannedCompatSet.add(chainSig);
4572                }
4573            } catch (CertificateEncodingException e) {
4574                scannedCompatSet.add(sig);
4575            }
4576        }
4577        /*
4578         * Make sure the expanded scanned set contains all signatures in the
4579         * existing one.
4580         */
4581        if (scannedCompatSet.equals(existingSet)) {
4582            // Migrate the old signatures to the new scheme.
4583            existingSigs.assignSignatures(scannedPkg.mSignatures);
4584            // The new KeySets will be re-added later in the scanning process.
4585            synchronized (mPackages) {
4586                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4587            }
4588            return PackageManager.SIGNATURE_MATCH;
4589        }
4590        return PackageManager.SIGNATURE_NO_MATCH;
4591    }
4592
4593    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4594        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4595        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4596    }
4597
4598    private int compareSignaturesRecover(PackageSignatures existingSigs,
4599            PackageParser.Package scannedPkg) {
4600        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4601            return PackageManager.SIGNATURE_NO_MATCH;
4602        }
4603
4604        String msg = null;
4605        try {
4606            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4607                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4608                        + scannedPkg.packageName);
4609                return PackageManager.SIGNATURE_MATCH;
4610            }
4611        } catch (CertificateException e) {
4612            msg = e.getMessage();
4613        }
4614
4615        logCriticalInfo(Log.INFO,
4616                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4617        return PackageManager.SIGNATURE_NO_MATCH;
4618    }
4619
4620    @Override
4621    public List<String> getAllPackages() {
4622        synchronized (mPackages) {
4623            return new ArrayList<String>(mPackages.keySet());
4624        }
4625    }
4626
4627    @Override
4628    public String[] getPackagesForUid(int uid) {
4629        uid = UserHandle.getAppId(uid);
4630        // reader
4631        synchronized (mPackages) {
4632            Object obj = mSettings.getUserIdLPr(uid);
4633            if (obj instanceof SharedUserSetting) {
4634                final SharedUserSetting sus = (SharedUserSetting) obj;
4635                final int N = sus.packages.size();
4636                final String[] res = new String[N];
4637                for (int i = 0; i < N; i++) {
4638                    res[i] = sus.packages.valueAt(i).name;
4639                }
4640                return res;
4641            } else if (obj instanceof PackageSetting) {
4642                final PackageSetting ps = (PackageSetting) obj;
4643                return new String[] { ps.name };
4644            }
4645        }
4646        return null;
4647    }
4648
4649    @Override
4650    public String getNameForUid(int uid) {
4651        // reader
4652        synchronized (mPackages) {
4653            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4654            if (obj instanceof SharedUserSetting) {
4655                final SharedUserSetting sus = (SharedUserSetting) obj;
4656                return sus.name + ":" + sus.userId;
4657            } else if (obj instanceof PackageSetting) {
4658                final PackageSetting ps = (PackageSetting) obj;
4659                return ps.name;
4660            }
4661        }
4662        return null;
4663    }
4664
4665    @Override
4666    public int getUidForSharedUser(String sharedUserName) {
4667        if(sharedUserName == null) {
4668            return -1;
4669        }
4670        // reader
4671        synchronized (mPackages) {
4672            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4673            if (suid == null) {
4674                return -1;
4675            }
4676            return suid.userId;
4677        }
4678    }
4679
4680    @Override
4681    public int getFlagsForUid(int uid) {
4682        synchronized (mPackages) {
4683            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4684            if (obj instanceof SharedUserSetting) {
4685                final SharedUserSetting sus = (SharedUserSetting) obj;
4686                return sus.pkgFlags;
4687            } else if (obj instanceof PackageSetting) {
4688                final PackageSetting ps = (PackageSetting) obj;
4689                return ps.pkgFlags;
4690            }
4691        }
4692        return 0;
4693    }
4694
4695    @Override
4696    public int getPrivateFlagsForUid(int uid) {
4697        synchronized (mPackages) {
4698            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4699            if (obj instanceof SharedUserSetting) {
4700                final SharedUserSetting sus = (SharedUserSetting) obj;
4701                return sus.pkgPrivateFlags;
4702            } else if (obj instanceof PackageSetting) {
4703                final PackageSetting ps = (PackageSetting) obj;
4704                return ps.pkgPrivateFlags;
4705            }
4706        }
4707        return 0;
4708    }
4709
4710    @Override
4711    public boolean isUidPrivileged(int uid) {
4712        uid = UserHandle.getAppId(uid);
4713        // reader
4714        synchronized (mPackages) {
4715            Object obj = mSettings.getUserIdLPr(uid);
4716            if (obj instanceof SharedUserSetting) {
4717                final SharedUserSetting sus = (SharedUserSetting) obj;
4718                final Iterator<PackageSetting> it = sus.packages.iterator();
4719                while (it.hasNext()) {
4720                    if (it.next().isPrivileged()) {
4721                        return true;
4722                    }
4723                }
4724            } else if (obj instanceof PackageSetting) {
4725                final PackageSetting ps = (PackageSetting) obj;
4726                return ps.isPrivileged();
4727            }
4728        }
4729        return false;
4730    }
4731
4732    @Override
4733    public String[] getAppOpPermissionPackages(String permissionName) {
4734        synchronized (mPackages) {
4735            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4736            if (pkgs == null) {
4737                return null;
4738            }
4739            return pkgs.toArray(new String[pkgs.size()]);
4740        }
4741    }
4742
4743    @Override
4744    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4745            int flags, int userId) {
4746        try {
4747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4748
4749            if (!sUserManager.exists(userId)) return null;
4750            flags = updateFlagsForResolve(flags, userId, intent);
4751            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4752                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4753
4754            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4755            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4756                    flags, userId);
4757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4758
4759            final ResolveInfo bestChoice =
4760                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4761            return bestChoice;
4762        } finally {
4763            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4764        }
4765    }
4766
4767    @Override
4768    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4769            IntentFilter filter, int match, ComponentName activity) {
4770        final int userId = UserHandle.getCallingUserId();
4771        if (DEBUG_PREFERRED) {
4772            Log.v(TAG, "setLastChosenActivity intent=" + intent
4773                + " resolvedType=" + resolvedType
4774                + " flags=" + flags
4775                + " filter=" + filter
4776                + " match=" + match
4777                + " activity=" + activity);
4778            filter.dump(new PrintStreamPrinter(System.out), "    ");
4779        }
4780        intent.setComponent(null);
4781        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4782                userId);
4783        // Find any earlier preferred or last chosen entries and nuke them
4784        findPreferredActivity(intent, resolvedType,
4785                flags, query, 0, false, true, false, userId);
4786        // Add the new activity as the last chosen for this filter
4787        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4788                "Setting last chosen");
4789    }
4790
4791    @Override
4792    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4793        final int userId = UserHandle.getCallingUserId();
4794        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4795        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4796                userId);
4797        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4798                false, false, false, userId);
4799    }
4800
4801    private boolean isEphemeralDisabled() {
4802        // ephemeral apps have been disabled across the board
4803        if (DISABLE_EPHEMERAL_APPS) {
4804            return true;
4805        }
4806        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4807        if (!mSystemReady) {
4808            return true;
4809        }
4810        return Secure.getInt(mContext.getContentResolver(), Secure.WEB_ACTION_ENABLED, 1) == 0;
4811    }
4812
4813    private boolean isEphemeralAllowed(
4814            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4815            boolean skipPackageCheck) {
4816        // Short circuit and return early if possible.
4817        if (isEphemeralDisabled()) {
4818            return false;
4819        }
4820        final int callingUser = UserHandle.getCallingUserId();
4821        if (callingUser != UserHandle.USER_SYSTEM) {
4822            return false;
4823        }
4824        if (mEphemeralResolverConnection == null) {
4825            return false;
4826        }
4827        if (intent.getComponent() != null) {
4828            return false;
4829        }
4830        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4831            return false;
4832        }
4833        if (!skipPackageCheck && intent.getPackage() != null) {
4834            return false;
4835        }
4836        final boolean isWebUri = hasWebURI(intent);
4837        if (!isWebUri || intent.getData().getHost() == null) {
4838            return false;
4839        }
4840        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4841        synchronized (mPackages) {
4842            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4843            for (int n = 0; n < count; n++) {
4844                ResolveInfo info = resolvedActivities.get(n);
4845                String packageName = info.activityInfo.packageName;
4846                PackageSetting ps = mSettings.mPackages.get(packageName);
4847                if (ps != null) {
4848                    // Try to get the status from User settings first
4849                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4850                    int status = (int) (packedStatus >> 32);
4851                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4852                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4853                        if (DEBUG_EPHEMERAL) {
4854                            Slog.v(TAG, "DENY ephemeral apps;"
4855                                + " pkg: " + packageName + ", status: " + status);
4856                        }
4857                        return false;
4858                    }
4859                }
4860            }
4861        }
4862        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4863        return true;
4864    }
4865
4866    private static EphemeralResolveInfo getEphemeralResolveInfo(
4867            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4868            String resolvedType, int userId, String packageName) {
4869        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4870                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4871        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4872                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4873        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4874                ephemeralPrefixCount);
4875        final int[] shaPrefix = digest.getDigestPrefix();
4876        final byte[][] digestBytes = digest.getDigestBytes();
4877        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4878                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4879        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4880            // No hash prefix match; there are no ephemeral apps for this domain.
4881            return null;
4882        }
4883
4884        // Go in reverse order so we match the narrowest scope first.
4885        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4886            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4887                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4888                    continue;
4889                }
4890                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4891                // No filters; this should never happen.
4892                if (filters.isEmpty()) {
4893                    continue;
4894                }
4895                if (packageName != null
4896                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4897                    continue;
4898                }
4899                // We have a domain match; resolve the filters to see if anything matches.
4900                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4901                for (int j = filters.size() - 1; j >= 0; --j) {
4902                    final EphemeralResolveIntentInfo intentInfo =
4903                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4904                    ephemeralResolver.addFilter(intentInfo);
4905                }
4906                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4907                        intent, resolvedType, false /*defaultOnly*/, userId);
4908                if (!matchedResolveInfoList.isEmpty()) {
4909                    return matchedResolveInfoList.get(0);
4910                }
4911            }
4912        }
4913        // Hash or filter mis-match; no ephemeral apps for this domain.
4914        return null;
4915    }
4916
4917    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4918            int flags, List<ResolveInfo> query, int userId) {
4919        if (query != null) {
4920            final int N = query.size();
4921            if (N == 1) {
4922                return query.get(0);
4923            } else if (N > 1) {
4924                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4925                // If there is more than one activity with the same priority,
4926                // then let the user decide between them.
4927                ResolveInfo r0 = query.get(0);
4928                ResolveInfo r1 = query.get(1);
4929                if (DEBUG_INTENT_MATCHING || debug) {
4930                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4931                            + r1.activityInfo.name + "=" + r1.priority);
4932                }
4933                // If the first activity has a higher priority, or a different
4934                // default, then it is always desirable to pick it.
4935                if (r0.priority != r1.priority
4936                        || r0.preferredOrder != r1.preferredOrder
4937                        || r0.isDefault != r1.isDefault) {
4938                    return query.get(0);
4939                }
4940                // If we have saved a preference for a preferred activity for
4941                // this Intent, use that.
4942                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4943                        flags, query, r0.priority, true, false, debug, userId);
4944                if (ri != null) {
4945                    return ri;
4946                }
4947                ri = new ResolveInfo(mResolveInfo);
4948                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4949                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4950                // If all of the options come from the same package, show the application's
4951                // label and icon instead of the generic resolver's.
4952                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4953                // and then throw away the ResolveInfo itself, meaning that the caller loses
4954                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4955                // a fallback for this case; we only set the target package's resources on
4956                // the ResolveInfo, not the ActivityInfo.
4957                final String intentPackage = intent.getPackage();
4958                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4959                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4960                    ri.resolvePackageName = intentPackage;
4961                    if (userNeedsBadging(userId)) {
4962                        ri.noResourceId = true;
4963                    } else {
4964                        ri.icon = appi.icon;
4965                    }
4966                    ri.iconResourceId = appi.icon;
4967                    ri.labelRes = appi.labelRes;
4968                }
4969                ri.activityInfo.applicationInfo = new ApplicationInfo(
4970                        ri.activityInfo.applicationInfo);
4971                if (userId != 0) {
4972                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4973                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4974                }
4975                // Make sure that the resolver is displayable in car mode
4976                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4977                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4978                return ri;
4979            }
4980        }
4981        return null;
4982    }
4983
4984    /**
4985     * Return true if the given list is not empty and all of its contents have
4986     * an activityInfo with the given package name.
4987     */
4988    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4989        if (ArrayUtils.isEmpty(list)) {
4990            return false;
4991        }
4992        for (int i = 0, N = list.size(); i < N; i++) {
4993            final ResolveInfo ri = list.get(i);
4994            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4995            if (ai == null || !packageName.equals(ai.packageName)) {
4996                return false;
4997            }
4998        }
4999        return true;
5000    }
5001
5002    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5003            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5004        final int N = query.size();
5005        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5006                .get(userId);
5007        // Get the list of persistent preferred activities that handle the intent
5008        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5009        List<PersistentPreferredActivity> pprefs = ppir != null
5010                ? ppir.queryIntent(intent, resolvedType,
5011                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5012                : null;
5013        if (pprefs != null && pprefs.size() > 0) {
5014            final int M = pprefs.size();
5015            for (int i=0; i<M; i++) {
5016                final PersistentPreferredActivity ppa = pprefs.get(i);
5017                if (DEBUG_PREFERRED || debug) {
5018                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5019                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5020                            + "\n  component=" + ppa.mComponent);
5021                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5022                }
5023                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5024                        flags | MATCH_DISABLED_COMPONENTS, userId);
5025                if (DEBUG_PREFERRED || debug) {
5026                    Slog.v(TAG, "Found persistent preferred activity:");
5027                    if (ai != null) {
5028                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5029                    } else {
5030                        Slog.v(TAG, "  null");
5031                    }
5032                }
5033                if (ai == null) {
5034                    // This previously registered persistent preferred activity
5035                    // component is no longer known. Ignore it and do NOT remove it.
5036                    continue;
5037                }
5038                for (int j=0; j<N; j++) {
5039                    final ResolveInfo ri = query.get(j);
5040                    if (!ri.activityInfo.applicationInfo.packageName
5041                            .equals(ai.applicationInfo.packageName)) {
5042                        continue;
5043                    }
5044                    if (!ri.activityInfo.name.equals(ai.name)) {
5045                        continue;
5046                    }
5047                    //  Found a persistent preference that can handle the intent.
5048                    if (DEBUG_PREFERRED || debug) {
5049                        Slog.v(TAG, "Returning persistent preferred activity: " +
5050                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5051                    }
5052                    return ri;
5053                }
5054            }
5055        }
5056        return null;
5057    }
5058
5059    // TODO: handle preferred activities missing while user has amnesia
5060    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5061            List<ResolveInfo> query, int priority, boolean always,
5062            boolean removeMatches, boolean debug, int userId) {
5063        if (!sUserManager.exists(userId)) return null;
5064        flags = updateFlagsForResolve(flags, userId, intent);
5065        // writer
5066        synchronized (mPackages) {
5067            if (intent.getSelector() != null) {
5068                intent = intent.getSelector();
5069            }
5070            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5071
5072            // Try to find a matching persistent preferred activity.
5073            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5074                    debug, userId);
5075
5076            // If a persistent preferred activity matched, use it.
5077            if (pri != null) {
5078                return pri;
5079            }
5080
5081            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5082            // Get the list of preferred activities that handle the intent
5083            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5084            List<PreferredActivity> prefs = pir != null
5085                    ? pir.queryIntent(intent, resolvedType,
5086                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5087                    : null;
5088            if (prefs != null && prefs.size() > 0) {
5089                boolean changed = false;
5090                try {
5091                    // First figure out how good the original match set is.
5092                    // We will only allow preferred activities that came
5093                    // from the same match quality.
5094                    int match = 0;
5095
5096                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5097
5098                    final int N = query.size();
5099                    for (int j=0; j<N; j++) {
5100                        final ResolveInfo ri = query.get(j);
5101                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5102                                + ": 0x" + Integer.toHexString(match));
5103                        if (ri.match > match) {
5104                            match = ri.match;
5105                        }
5106                    }
5107
5108                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5109                            + Integer.toHexString(match));
5110
5111                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5112                    final int M = prefs.size();
5113                    for (int i=0; i<M; i++) {
5114                        final PreferredActivity pa = prefs.get(i);
5115                        if (DEBUG_PREFERRED || debug) {
5116                            Slog.v(TAG, "Checking PreferredActivity ds="
5117                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5118                                    + "\n  component=" + pa.mPref.mComponent);
5119                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5120                        }
5121                        if (pa.mPref.mMatch != match) {
5122                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5123                                    + Integer.toHexString(pa.mPref.mMatch));
5124                            continue;
5125                        }
5126                        // If it's not an "always" type preferred activity and that's what we're
5127                        // looking for, skip it.
5128                        if (always && !pa.mPref.mAlways) {
5129                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5130                            continue;
5131                        }
5132                        final ActivityInfo ai = getActivityInfo(
5133                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5134                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5135                                userId);
5136                        if (DEBUG_PREFERRED || debug) {
5137                            Slog.v(TAG, "Found preferred activity:");
5138                            if (ai != null) {
5139                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5140                            } else {
5141                                Slog.v(TAG, "  null");
5142                            }
5143                        }
5144                        if (ai == null) {
5145                            // This previously registered preferred activity
5146                            // component is no longer known.  Most likely an update
5147                            // to the app was installed and in the new version this
5148                            // component no longer exists.  Clean it up by removing
5149                            // it from the preferred activities list, and skip it.
5150                            Slog.w(TAG, "Removing dangling preferred activity: "
5151                                    + pa.mPref.mComponent);
5152                            pir.removeFilter(pa);
5153                            changed = true;
5154                            continue;
5155                        }
5156                        for (int j=0; j<N; j++) {
5157                            final ResolveInfo ri = query.get(j);
5158                            if (!ri.activityInfo.applicationInfo.packageName
5159                                    .equals(ai.applicationInfo.packageName)) {
5160                                continue;
5161                            }
5162                            if (!ri.activityInfo.name.equals(ai.name)) {
5163                                continue;
5164                            }
5165
5166                            if (removeMatches) {
5167                                pir.removeFilter(pa);
5168                                changed = true;
5169                                if (DEBUG_PREFERRED) {
5170                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5171                                }
5172                                break;
5173                            }
5174
5175                            // Okay we found a previously set preferred or last chosen app.
5176                            // If the result set is different from when this
5177                            // was created, we need to clear it and re-ask the
5178                            // user their preference, if we're looking for an "always" type entry.
5179                            if (always && !pa.mPref.sameSet(query)) {
5180                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5181                                        + intent + " type " + resolvedType);
5182                                if (DEBUG_PREFERRED) {
5183                                    Slog.v(TAG, "Removing preferred activity since set changed "
5184                                            + pa.mPref.mComponent);
5185                                }
5186                                pir.removeFilter(pa);
5187                                // Re-add the filter as a "last chosen" entry (!always)
5188                                PreferredActivity lastChosen = new PreferredActivity(
5189                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5190                                pir.addFilter(lastChosen);
5191                                changed = true;
5192                                return null;
5193                            }
5194
5195                            // Yay! Either the set matched or we're looking for the last chosen
5196                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5197                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5198                            return ri;
5199                        }
5200                    }
5201                } finally {
5202                    if (changed) {
5203                        if (DEBUG_PREFERRED) {
5204                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5205                        }
5206                        scheduleWritePackageRestrictionsLocked(userId);
5207                    }
5208                }
5209            }
5210        }
5211        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5212        return null;
5213    }
5214
5215    /*
5216     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5217     */
5218    @Override
5219    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5220            int targetUserId) {
5221        mContext.enforceCallingOrSelfPermission(
5222                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5223        List<CrossProfileIntentFilter> matches =
5224                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5225        if (matches != null) {
5226            int size = matches.size();
5227            for (int i = 0; i < size; i++) {
5228                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5229            }
5230        }
5231        if (hasWebURI(intent)) {
5232            // cross-profile app linking works only towards the parent.
5233            final UserInfo parent = getProfileParent(sourceUserId);
5234            synchronized(mPackages) {
5235                int flags = updateFlagsForResolve(0, parent.id, intent);
5236                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5237                        intent, resolvedType, flags, sourceUserId, parent.id);
5238                return xpDomainInfo != null;
5239            }
5240        }
5241        return false;
5242    }
5243
5244    private UserInfo getProfileParent(int userId) {
5245        final long identity = Binder.clearCallingIdentity();
5246        try {
5247            return sUserManager.getProfileParent(userId);
5248        } finally {
5249            Binder.restoreCallingIdentity(identity);
5250        }
5251    }
5252
5253    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5254            String resolvedType, int userId) {
5255        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5256        if (resolver != null) {
5257            return resolver.queryIntent(intent, resolvedType, false, userId);
5258        }
5259        return null;
5260    }
5261
5262    @Override
5263    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5264            String resolvedType, int flags, int userId) {
5265        try {
5266            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5267
5268            return new ParceledListSlice<>(
5269                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5270        } finally {
5271            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5272        }
5273    }
5274
5275    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5276            String resolvedType, int flags, int userId) {
5277        if (!sUserManager.exists(userId)) return Collections.emptyList();
5278        flags = updateFlagsForResolve(flags, userId, intent);
5279        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5280                false /* requireFullPermission */, false /* checkShell */,
5281                "query intent activities");
5282        ComponentName comp = intent.getComponent();
5283        if (comp == null) {
5284            if (intent.getSelector() != null) {
5285                intent = intent.getSelector();
5286                comp = intent.getComponent();
5287            }
5288        }
5289
5290        if (comp != null) {
5291            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5292            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5293            if (ai != null) {
5294                final ResolveInfo ri = new ResolveInfo();
5295                ri.activityInfo = ai;
5296                list.add(ri);
5297            }
5298            return list;
5299        }
5300
5301        // reader
5302        boolean sortResult = false;
5303        boolean addEphemeral = false;
5304        boolean matchEphemeralPackage = false;
5305        List<ResolveInfo> result;
5306        final String pkgName = intent.getPackage();
5307        synchronized (mPackages) {
5308            if (pkgName == null) {
5309                List<CrossProfileIntentFilter> matchingFilters =
5310                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5311                // Check for results that need to skip the current profile.
5312                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5313                        resolvedType, flags, userId);
5314                if (xpResolveInfo != null) {
5315                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5316                    xpResult.add(xpResolveInfo);
5317                    return filterIfNotSystemUser(xpResult, userId);
5318                }
5319
5320                // Check for results in the current profile.
5321                result = filterIfNotSystemUser(mActivities.queryIntent(
5322                        intent, resolvedType, flags, userId), userId);
5323                addEphemeral =
5324                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5325
5326                // Check for cross profile results.
5327                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5328                xpResolveInfo = queryCrossProfileIntents(
5329                        matchingFilters, intent, resolvedType, flags, userId,
5330                        hasNonNegativePriorityResult);
5331                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5332                    boolean isVisibleToUser = filterIfNotSystemUser(
5333                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5334                    if (isVisibleToUser) {
5335                        result.add(xpResolveInfo);
5336                        sortResult = true;
5337                    }
5338                }
5339                if (hasWebURI(intent)) {
5340                    CrossProfileDomainInfo xpDomainInfo = null;
5341                    final UserInfo parent = getProfileParent(userId);
5342                    if (parent != null) {
5343                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5344                                flags, userId, parent.id);
5345                    }
5346                    if (xpDomainInfo != null) {
5347                        if (xpResolveInfo != null) {
5348                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5349                            // in the result.
5350                            result.remove(xpResolveInfo);
5351                        }
5352                        if (result.size() == 0 && !addEphemeral) {
5353                            result.add(xpDomainInfo.resolveInfo);
5354                            return result;
5355                        }
5356                    }
5357                    if (result.size() > 1 || addEphemeral) {
5358                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5359                                intent, flags, result, xpDomainInfo, userId);
5360                        sortResult = true;
5361                    }
5362                }
5363            } else {
5364                final PackageParser.Package pkg = mPackages.get(pkgName);
5365                if (pkg != null) {
5366                    result = filterIfNotSystemUser(
5367                            mActivities.queryIntentForPackage(
5368                                    intent, resolvedType, flags, pkg.activities, userId),
5369                            userId);
5370                } else {
5371                    // the caller wants to resolve for a particular package; however, there
5372                    // were no installed results, so, try to find an ephemeral result
5373                    addEphemeral = isEphemeralAllowed(
5374                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5375                    matchEphemeralPackage = true;
5376                    result = new ArrayList<ResolveInfo>();
5377                }
5378            }
5379        }
5380        if (addEphemeral) {
5381            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5382            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5383                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5384                    matchEphemeralPackage ? pkgName : null);
5385            if (ai != null) {
5386                if (DEBUG_EPHEMERAL) {
5387                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5388                }
5389                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5390                ephemeralInstaller.ephemeralResolveInfo = ai;
5391                // make sure this resolver is the default
5392                ephemeralInstaller.isDefault = true;
5393                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5394                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5395                // add a non-generic filter
5396                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5397                ephemeralInstaller.filter.addDataPath(
5398                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5399                result.add(ephemeralInstaller);
5400            }
5401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5402        }
5403        if (sortResult) {
5404            Collections.sort(result, mResolvePrioritySorter);
5405        }
5406        return result;
5407    }
5408
5409    private static class CrossProfileDomainInfo {
5410        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5411        ResolveInfo resolveInfo;
5412        /* Best domain verification status of the activities found in the other profile */
5413        int bestDomainVerificationStatus;
5414    }
5415
5416    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5417            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5418        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5419                sourceUserId)) {
5420            return null;
5421        }
5422        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5423                resolvedType, flags, parentUserId);
5424
5425        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5426            return null;
5427        }
5428        CrossProfileDomainInfo result = null;
5429        int size = resultTargetUser.size();
5430        for (int i = 0; i < size; i++) {
5431            ResolveInfo riTargetUser = resultTargetUser.get(i);
5432            // Intent filter verification is only for filters that specify a host. So don't return
5433            // those that handle all web uris.
5434            if (riTargetUser.handleAllWebDataURI) {
5435                continue;
5436            }
5437            String packageName = riTargetUser.activityInfo.packageName;
5438            PackageSetting ps = mSettings.mPackages.get(packageName);
5439            if (ps == null) {
5440                continue;
5441            }
5442            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5443            int status = (int)(verificationState >> 32);
5444            if (result == null) {
5445                result = new CrossProfileDomainInfo();
5446                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5447                        sourceUserId, parentUserId);
5448                result.bestDomainVerificationStatus = status;
5449            } else {
5450                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5451                        result.bestDomainVerificationStatus);
5452            }
5453        }
5454        // Don't consider matches with status NEVER across profiles.
5455        if (result != null && result.bestDomainVerificationStatus
5456                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5457            return null;
5458        }
5459        return result;
5460    }
5461
5462    /**
5463     * Verification statuses are ordered from the worse to the best, except for
5464     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5465     */
5466    private int bestDomainVerificationStatus(int status1, int status2) {
5467        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5468            return status2;
5469        }
5470        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5471            return status1;
5472        }
5473        return (int) MathUtils.max(status1, status2);
5474    }
5475
5476    private boolean isUserEnabled(int userId) {
5477        long callingId = Binder.clearCallingIdentity();
5478        try {
5479            UserInfo userInfo = sUserManager.getUserInfo(userId);
5480            return userInfo != null && userInfo.isEnabled();
5481        } finally {
5482            Binder.restoreCallingIdentity(callingId);
5483        }
5484    }
5485
5486    /**
5487     * Filter out activities with systemUserOnly flag set, when current user is not System.
5488     *
5489     * @return filtered list
5490     */
5491    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5492        if (userId == UserHandle.USER_SYSTEM) {
5493            return resolveInfos;
5494        }
5495        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5496            ResolveInfo info = resolveInfos.get(i);
5497            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5498                resolveInfos.remove(i);
5499            }
5500        }
5501        return resolveInfos;
5502    }
5503
5504    /**
5505     * @param resolveInfos list of resolve infos in descending priority order
5506     * @return if the list contains a resolve info with non-negative priority
5507     */
5508    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5509        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5510    }
5511
5512    private static boolean hasWebURI(Intent intent) {
5513        if (intent.getData() == null) {
5514            return false;
5515        }
5516        final String scheme = intent.getScheme();
5517        if (TextUtils.isEmpty(scheme)) {
5518            return false;
5519        }
5520        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5521    }
5522
5523    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5524            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5525            int userId) {
5526        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5527
5528        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5529            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5530                    candidates.size());
5531        }
5532
5533        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5534        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5535        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5536        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5537        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5538        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5539
5540        synchronized (mPackages) {
5541            final int count = candidates.size();
5542            // First, try to use linked apps. Partition the candidates into four lists:
5543            // one for the final results, one for the "do not use ever", one for "undefined status"
5544            // and finally one for "browser app type".
5545            for (int n=0; n<count; n++) {
5546                ResolveInfo info = candidates.get(n);
5547                String packageName = info.activityInfo.packageName;
5548                PackageSetting ps = mSettings.mPackages.get(packageName);
5549                if (ps != null) {
5550                    // Add to the special match all list (Browser use case)
5551                    if (info.handleAllWebDataURI) {
5552                        matchAllList.add(info);
5553                        continue;
5554                    }
5555                    // Try to get the status from User settings first
5556                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5557                    int status = (int)(packedStatus >> 32);
5558                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5559                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5560                        if (DEBUG_DOMAIN_VERIFICATION) {
5561                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5562                                    + " : linkgen=" + linkGeneration);
5563                        }
5564                        // Use link-enabled generation as preferredOrder, i.e.
5565                        // prefer newly-enabled over earlier-enabled.
5566                        info.preferredOrder = linkGeneration;
5567                        alwaysList.add(info);
5568                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5569                        if (DEBUG_DOMAIN_VERIFICATION) {
5570                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5571                        }
5572                        neverList.add(info);
5573                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5574                        if (DEBUG_DOMAIN_VERIFICATION) {
5575                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5576                        }
5577                        alwaysAskList.add(info);
5578                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5579                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5580                        if (DEBUG_DOMAIN_VERIFICATION) {
5581                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5582                        }
5583                        undefinedList.add(info);
5584                    }
5585                }
5586            }
5587
5588            // We'll want to include browser possibilities in a few cases
5589            boolean includeBrowser = false;
5590
5591            // First try to add the "always" resolution(s) for the current user, if any
5592            if (alwaysList.size() > 0) {
5593                result.addAll(alwaysList);
5594            } else {
5595                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5596                result.addAll(undefinedList);
5597                // Maybe add one for the other profile.
5598                if (xpDomainInfo != null && (
5599                        xpDomainInfo.bestDomainVerificationStatus
5600                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5601                    result.add(xpDomainInfo.resolveInfo);
5602                }
5603                includeBrowser = true;
5604            }
5605
5606            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5607            // If there were 'always' entries their preferred order has been set, so we also
5608            // back that off to make the alternatives equivalent
5609            if (alwaysAskList.size() > 0) {
5610                for (ResolveInfo i : result) {
5611                    i.preferredOrder = 0;
5612                }
5613                result.addAll(alwaysAskList);
5614                includeBrowser = true;
5615            }
5616
5617            if (includeBrowser) {
5618                // Also add browsers (all of them or only the default one)
5619                if (DEBUG_DOMAIN_VERIFICATION) {
5620                    Slog.v(TAG, "   ...including browsers in candidate set");
5621                }
5622                if ((matchFlags & MATCH_ALL) != 0) {
5623                    result.addAll(matchAllList);
5624                } else {
5625                    // Browser/generic handling case.  If there's a default browser, go straight
5626                    // to that (but only if there is no other higher-priority match).
5627                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5628                    int maxMatchPrio = 0;
5629                    ResolveInfo defaultBrowserMatch = null;
5630                    final int numCandidates = matchAllList.size();
5631                    for (int n = 0; n < numCandidates; n++) {
5632                        ResolveInfo info = matchAllList.get(n);
5633                        // track the highest overall match priority...
5634                        if (info.priority > maxMatchPrio) {
5635                            maxMatchPrio = info.priority;
5636                        }
5637                        // ...and the highest-priority default browser match
5638                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5639                            if (defaultBrowserMatch == null
5640                                    || (defaultBrowserMatch.priority < info.priority)) {
5641                                if (debug) {
5642                                    Slog.v(TAG, "Considering default browser match " + info);
5643                                }
5644                                defaultBrowserMatch = info;
5645                            }
5646                        }
5647                    }
5648                    if (defaultBrowserMatch != null
5649                            && defaultBrowserMatch.priority >= maxMatchPrio
5650                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5651                    {
5652                        if (debug) {
5653                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5654                        }
5655                        result.add(defaultBrowserMatch);
5656                    } else {
5657                        result.addAll(matchAllList);
5658                    }
5659                }
5660
5661                // If there is nothing selected, add all candidates and remove the ones that the user
5662                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5663                if (result.size() == 0) {
5664                    result.addAll(candidates);
5665                    result.removeAll(neverList);
5666                }
5667            }
5668        }
5669        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5670            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5671                    result.size());
5672            for (ResolveInfo info : result) {
5673                Slog.v(TAG, "  + " + info.activityInfo);
5674            }
5675        }
5676        return result;
5677    }
5678
5679    // Returns a packed value as a long:
5680    //
5681    // high 'int'-sized word: link status: undefined/ask/never/always.
5682    // low 'int'-sized word: relative priority among 'always' results.
5683    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5684        long result = ps.getDomainVerificationStatusForUser(userId);
5685        // if none available, get the master status
5686        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5687            if (ps.getIntentFilterVerificationInfo() != null) {
5688                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5689            }
5690        }
5691        return result;
5692    }
5693
5694    private ResolveInfo querySkipCurrentProfileIntents(
5695            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5696            int flags, int sourceUserId) {
5697        if (matchingFilters != null) {
5698            int size = matchingFilters.size();
5699            for (int i = 0; i < size; i ++) {
5700                CrossProfileIntentFilter filter = matchingFilters.get(i);
5701                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5702                    // Checking if there are activities in the target user that can handle the
5703                    // intent.
5704                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5705                            resolvedType, flags, sourceUserId);
5706                    if (resolveInfo != null) {
5707                        return resolveInfo;
5708                    }
5709                }
5710            }
5711        }
5712        return null;
5713    }
5714
5715    // Return matching ResolveInfo in target user if any.
5716    private ResolveInfo queryCrossProfileIntents(
5717            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5718            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5719        if (matchingFilters != null) {
5720            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5721            // match the same intent. For performance reasons, it is better not to
5722            // run queryIntent twice for the same userId
5723            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5724            int size = matchingFilters.size();
5725            for (int i = 0; i < size; i++) {
5726                CrossProfileIntentFilter filter = matchingFilters.get(i);
5727                int targetUserId = filter.getTargetUserId();
5728                boolean skipCurrentProfile =
5729                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5730                boolean skipCurrentProfileIfNoMatchFound =
5731                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5732                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5733                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5734                    // Checking if there are activities in the target user that can handle the
5735                    // intent.
5736                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5737                            resolvedType, flags, sourceUserId);
5738                    if (resolveInfo != null) return resolveInfo;
5739                    alreadyTriedUserIds.put(targetUserId, true);
5740                }
5741            }
5742        }
5743        return null;
5744    }
5745
5746    /**
5747     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5748     * will forward the intent to the filter's target user.
5749     * Otherwise, returns null.
5750     */
5751    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5752            String resolvedType, int flags, int sourceUserId) {
5753        int targetUserId = filter.getTargetUserId();
5754        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5755                resolvedType, flags, targetUserId);
5756        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5757            // If all the matches in the target profile are suspended, return null.
5758            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5759                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5760                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5761                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5762                            targetUserId);
5763                }
5764            }
5765        }
5766        return null;
5767    }
5768
5769    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5770            int sourceUserId, int targetUserId) {
5771        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5772        long ident = Binder.clearCallingIdentity();
5773        boolean targetIsProfile;
5774        try {
5775            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5776        } finally {
5777            Binder.restoreCallingIdentity(ident);
5778        }
5779        String className;
5780        if (targetIsProfile) {
5781            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5782        } else {
5783            className = FORWARD_INTENT_TO_PARENT;
5784        }
5785        ComponentName forwardingActivityComponentName = new ComponentName(
5786                mAndroidApplication.packageName, className);
5787        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5788                sourceUserId);
5789        if (!targetIsProfile) {
5790            forwardingActivityInfo.showUserIcon = targetUserId;
5791            forwardingResolveInfo.noResourceId = true;
5792        }
5793        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5794        forwardingResolveInfo.priority = 0;
5795        forwardingResolveInfo.preferredOrder = 0;
5796        forwardingResolveInfo.match = 0;
5797        forwardingResolveInfo.isDefault = true;
5798        forwardingResolveInfo.filter = filter;
5799        forwardingResolveInfo.targetUserId = targetUserId;
5800        return forwardingResolveInfo;
5801    }
5802
5803    @Override
5804    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5805            Intent[] specifics, String[] specificTypes, Intent intent,
5806            String resolvedType, int flags, int userId) {
5807        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5808                specificTypes, intent, resolvedType, flags, userId));
5809    }
5810
5811    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5812            Intent[] specifics, String[] specificTypes, Intent intent,
5813            String resolvedType, int flags, int userId) {
5814        if (!sUserManager.exists(userId)) return Collections.emptyList();
5815        flags = updateFlagsForResolve(flags, userId, intent);
5816        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5817                false /* requireFullPermission */, false /* checkShell */,
5818                "query intent activity options");
5819        final String resultsAction = intent.getAction();
5820
5821        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5822                | PackageManager.GET_RESOLVED_FILTER, userId);
5823
5824        if (DEBUG_INTENT_MATCHING) {
5825            Log.v(TAG, "Query " + intent + ": " + results);
5826        }
5827
5828        int specificsPos = 0;
5829        int N;
5830
5831        // todo: note that the algorithm used here is O(N^2).  This
5832        // isn't a problem in our current environment, but if we start running
5833        // into situations where we have more than 5 or 10 matches then this
5834        // should probably be changed to something smarter...
5835
5836        // First we go through and resolve each of the specific items
5837        // that were supplied, taking care of removing any corresponding
5838        // duplicate items in the generic resolve list.
5839        if (specifics != null) {
5840            for (int i=0; i<specifics.length; i++) {
5841                final Intent sintent = specifics[i];
5842                if (sintent == null) {
5843                    continue;
5844                }
5845
5846                if (DEBUG_INTENT_MATCHING) {
5847                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5848                }
5849
5850                String action = sintent.getAction();
5851                if (resultsAction != null && resultsAction.equals(action)) {
5852                    // If this action was explicitly requested, then don't
5853                    // remove things that have it.
5854                    action = null;
5855                }
5856
5857                ResolveInfo ri = null;
5858                ActivityInfo ai = null;
5859
5860                ComponentName comp = sintent.getComponent();
5861                if (comp == null) {
5862                    ri = resolveIntent(
5863                        sintent,
5864                        specificTypes != null ? specificTypes[i] : null,
5865                            flags, userId);
5866                    if (ri == null) {
5867                        continue;
5868                    }
5869                    if (ri == mResolveInfo) {
5870                        // ACK!  Must do something better with this.
5871                    }
5872                    ai = ri.activityInfo;
5873                    comp = new ComponentName(ai.applicationInfo.packageName,
5874                            ai.name);
5875                } else {
5876                    ai = getActivityInfo(comp, flags, userId);
5877                    if (ai == null) {
5878                        continue;
5879                    }
5880                }
5881
5882                // Look for any generic query activities that are duplicates
5883                // of this specific one, and remove them from the results.
5884                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5885                N = results.size();
5886                int j;
5887                for (j=specificsPos; j<N; j++) {
5888                    ResolveInfo sri = results.get(j);
5889                    if ((sri.activityInfo.name.equals(comp.getClassName())
5890                            && sri.activityInfo.applicationInfo.packageName.equals(
5891                                    comp.getPackageName()))
5892                        || (action != null && sri.filter.matchAction(action))) {
5893                        results.remove(j);
5894                        if (DEBUG_INTENT_MATCHING) Log.v(
5895                            TAG, "Removing duplicate item from " + j
5896                            + " due to specific " + specificsPos);
5897                        if (ri == null) {
5898                            ri = sri;
5899                        }
5900                        j--;
5901                        N--;
5902                    }
5903                }
5904
5905                // Add this specific item to its proper place.
5906                if (ri == null) {
5907                    ri = new ResolveInfo();
5908                    ri.activityInfo = ai;
5909                }
5910                results.add(specificsPos, ri);
5911                ri.specificIndex = i;
5912                specificsPos++;
5913            }
5914        }
5915
5916        // Now we go through the remaining generic results and remove any
5917        // duplicate actions that are found here.
5918        N = results.size();
5919        for (int i=specificsPos; i<N-1; i++) {
5920            final ResolveInfo rii = results.get(i);
5921            if (rii.filter == null) {
5922                continue;
5923            }
5924
5925            // Iterate over all of the actions of this result's intent
5926            // filter...  typically this should be just one.
5927            final Iterator<String> it = rii.filter.actionsIterator();
5928            if (it == null) {
5929                continue;
5930            }
5931            while (it.hasNext()) {
5932                final String action = it.next();
5933                if (resultsAction != null && resultsAction.equals(action)) {
5934                    // If this action was explicitly requested, then don't
5935                    // remove things that have it.
5936                    continue;
5937                }
5938                for (int j=i+1; j<N; j++) {
5939                    final ResolveInfo rij = results.get(j);
5940                    if (rij.filter != null && rij.filter.hasAction(action)) {
5941                        results.remove(j);
5942                        if (DEBUG_INTENT_MATCHING) Log.v(
5943                            TAG, "Removing duplicate item from " + j
5944                            + " due to action " + action + " at " + i);
5945                        j--;
5946                        N--;
5947                    }
5948                }
5949            }
5950
5951            // If the caller didn't request filter information, drop it now
5952            // so we don't have to marshall/unmarshall it.
5953            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5954                rii.filter = null;
5955            }
5956        }
5957
5958        // Filter out the caller activity if so requested.
5959        if (caller != null) {
5960            N = results.size();
5961            for (int i=0; i<N; i++) {
5962                ActivityInfo ainfo = results.get(i).activityInfo;
5963                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5964                        && caller.getClassName().equals(ainfo.name)) {
5965                    results.remove(i);
5966                    break;
5967                }
5968            }
5969        }
5970
5971        // If the caller didn't request filter information,
5972        // drop them now so we don't have to
5973        // marshall/unmarshall it.
5974        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5975            N = results.size();
5976            for (int i=0; i<N; i++) {
5977                results.get(i).filter = null;
5978            }
5979        }
5980
5981        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5982        return results;
5983    }
5984
5985    @Override
5986    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5987            String resolvedType, int flags, int userId) {
5988        return new ParceledListSlice<>(
5989                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5990    }
5991
5992    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5993            String resolvedType, int flags, int userId) {
5994        if (!sUserManager.exists(userId)) return Collections.emptyList();
5995        flags = updateFlagsForResolve(flags, userId, intent);
5996        ComponentName comp = intent.getComponent();
5997        if (comp == null) {
5998            if (intent.getSelector() != null) {
5999                intent = intent.getSelector();
6000                comp = intent.getComponent();
6001            }
6002        }
6003        if (comp != null) {
6004            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6005            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6006            if (ai != null) {
6007                ResolveInfo ri = new ResolveInfo();
6008                ri.activityInfo = ai;
6009                list.add(ri);
6010            }
6011            return list;
6012        }
6013
6014        // reader
6015        synchronized (mPackages) {
6016            String pkgName = intent.getPackage();
6017            if (pkgName == null) {
6018                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6019            }
6020            final PackageParser.Package pkg = mPackages.get(pkgName);
6021            if (pkg != null) {
6022                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6023                        userId);
6024            }
6025            return Collections.emptyList();
6026        }
6027    }
6028
6029    @Override
6030    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6031        if (!sUserManager.exists(userId)) return null;
6032        flags = updateFlagsForResolve(flags, userId, intent);
6033        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6034        if (query != null) {
6035            if (query.size() >= 1) {
6036                // If there is more than one service with the same priority,
6037                // just arbitrarily pick the first one.
6038                return query.get(0);
6039            }
6040        }
6041        return null;
6042    }
6043
6044    @Override
6045    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6046            String resolvedType, int flags, int userId) {
6047        return new ParceledListSlice<>(
6048                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6049    }
6050
6051    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6052            String resolvedType, int flags, int userId) {
6053        if (!sUserManager.exists(userId)) return Collections.emptyList();
6054        flags = updateFlagsForResolve(flags, userId, intent);
6055        ComponentName comp = intent.getComponent();
6056        if (comp == null) {
6057            if (intent.getSelector() != null) {
6058                intent = intent.getSelector();
6059                comp = intent.getComponent();
6060            }
6061        }
6062        if (comp != null) {
6063            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6064            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6065            if (si != null) {
6066                final ResolveInfo ri = new ResolveInfo();
6067                ri.serviceInfo = si;
6068                list.add(ri);
6069            }
6070            return list;
6071        }
6072
6073        // reader
6074        synchronized (mPackages) {
6075            String pkgName = intent.getPackage();
6076            if (pkgName == null) {
6077                return mServices.queryIntent(intent, resolvedType, flags, userId);
6078            }
6079            final PackageParser.Package pkg = mPackages.get(pkgName);
6080            if (pkg != null) {
6081                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6082                        userId);
6083            }
6084            return Collections.emptyList();
6085        }
6086    }
6087
6088    @Override
6089    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6090            String resolvedType, int flags, int userId) {
6091        return new ParceledListSlice<>(
6092                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6093    }
6094
6095    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6096            Intent intent, String resolvedType, int flags, int userId) {
6097        if (!sUserManager.exists(userId)) return Collections.emptyList();
6098        flags = updateFlagsForResolve(flags, userId, intent);
6099        ComponentName comp = intent.getComponent();
6100        if (comp == null) {
6101            if (intent.getSelector() != null) {
6102                intent = intent.getSelector();
6103                comp = intent.getComponent();
6104            }
6105        }
6106        if (comp != null) {
6107            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6108            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6109            if (pi != null) {
6110                final ResolveInfo ri = new ResolveInfo();
6111                ri.providerInfo = pi;
6112                list.add(ri);
6113            }
6114            return list;
6115        }
6116
6117        // reader
6118        synchronized (mPackages) {
6119            String pkgName = intent.getPackage();
6120            if (pkgName == null) {
6121                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6122            }
6123            final PackageParser.Package pkg = mPackages.get(pkgName);
6124            if (pkg != null) {
6125                return mProviders.queryIntentForPackage(
6126                        intent, resolvedType, flags, pkg.providers, userId);
6127            }
6128            return Collections.emptyList();
6129        }
6130    }
6131
6132    @Override
6133    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6134        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6135        flags = updateFlagsForPackage(flags, userId, null);
6136        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6137        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6138                true /* requireFullPermission */, false /* checkShell */,
6139                "get installed packages");
6140
6141        // writer
6142        synchronized (mPackages) {
6143            ArrayList<PackageInfo> list;
6144            if (listUninstalled) {
6145                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6146                for (PackageSetting ps : mSettings.mPackages.values()) {
6147                    final PackageInfo pi;
6148                    if (ps.pkg != null) {
6149                        pi = generatePackageInfo(ps, flags, userId);
6150                    } else {
6151                        pi = generatePackageInfo(ps, flags, userId);
6152                    }
6153                    if (pi != null) {
6154                        list.add(pi);
6155                    }
6156                }
6157            } else {
6158                list = new ArrayList<PackageInfo>(mPackages.size());
6159                for (PackageParser.Package p : mPackages.values()) {
6160                    final PackageInfo pi =
6161                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6162                    if (pi != null) {
6163                        list.add(pi);
6164                    }
6165                }
6166            }
6167
6168            return new ParceledListSlice<PackageInfo>(list);
6169        }
6170    }
6171
6172    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6173            String[] permissions, boolean[] tmp, int flags, int userId) {
6174        int numMatch = 0;
6175        final PermissionsState permissionsState = ps.getPermissionsState();
6176        for (int i=0; i<permissions.length; i++) {
6177            final String permission = permissions[i];
6178            if (permissionsState.hasPermission(permission, userId)) {
6179                tmp[i] = true;
6180                numMatch++;
6181            } else {
6182                tmp[i] = false;
6183            }
6184        }
6185        if (numMatch == 0) {
6186            return;
6187        }
6188        final PackageInfo pi;
6189        if (ps.pkg != null) {
6190            pi = generatePackageInfo(ps, flags, userId);
6191        } else {
6192            pi = generatePackageInfo(ps, flags, userId);
6193        }
6194        // The above might return null in cases of uninstalled apps or install-state
6195        // skew across users/profiles.
6196        if (pi != null) {
6197            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6198                if (numMatch == permissions.length) {
6199                    pi.requestedPermissions = permissions;
6200                } else {
6201                    pi.requestedPermissions = new String[numMatch];
6202                    numMatch = 0;
6203                    for (int i=0; i<permissions.length; i++) {
6204                        if (tmp[i]) {
6205                            pi.requestedPermissions[numMatch] = permissions[i];
6206                            numMatch++;
6207                        }
6208                    }
6209                }
6210            }
6211            list.add(pi);
6212        }
6213    }
6214
6215    @Override
6216    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6217            String[] permissions, int flags, int userId) {
6218        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6219        flags = updateFlagsForPackage(flags, userId, permissions);
6220        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6221
6222        // writer
6223        synchronized (mPackages) {
6224            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6225            boolean[] tmpBools = new boolean[permissions.length];
6226            if (listUninstalled) {
6227                for (PackageSetting ps : mSettings.mPackages.values()) {
6228                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6229                }
6230            } else {
6231                for (PackageParser.Package pkg : mPackages.values()) {
6232                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6233                    if (ps != null) {
6234                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6235                                userId);
6236                    }
6237                }
6238            }
6239
6240            return new ParceledListSlice<PackageInfo>(list);
6241        }
6242    }
6243
6244    @Override
6245    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6246        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6247        flags = updateFlagsForApplication(flags, userId, null);
6248        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6249
6250        // writer
6251        synchronized (mPackages) {
6252            ArrayList<ApplicationInfo> list;
6253            if (listUninstalled) {
6254                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6255                for (PackageSetting ps : mSettings.mPackages.values()) {
6256                    ApplicationInfo ai;
6257                    if (ps.pkg != null) {
6258                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6259                                ps.readUserState(userId), userId);
6260                    } else {
6261                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6262                    }
6263                    if (ai != null) {
6264                        list.add(ai);
6265                    }
6266                }
6267            } else {
6268                list = new ArrayList<ApplicationInfo>(mPackages.size());
6269                for (PackageParser.Package p : mPackages.values()) {
6270                    if (p.mExtras != null) {
6271                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6272                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6273                        if (ai != null) {
6274                            list.add(ai);
6275                        }
6276                    }
6277                }
6278            }
6279
6280            return new ParceledListSlice<ApplicationInfo>(list);
6281        }
6282    }
6283
6284    @Override
6285    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6286        if (isEphemeralDisabled()) {
6287            return null;
6288        }
6289
6290        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6291                "getEphemeralApplications");
6292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6293                true /* requireFullPermission */, false /* checkShell */,
6294                "getEphemeralApplications");
6295        synchronized (mPackages) {
6296            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6297                    .getEphemeralApplicationsLPw(userId);
6298            if (ephemeralApps != null) {
6299                return new ParceledListSlice<>(ephemeralApps);
6300            }
6301        }
6302        return null;
6303    }
6304
6305    @Override
6306    public boolean isEphemeralApplication(String packageName, int userId) {
6307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6308                true /* requireFullPermission */, false /* checkShell */,
6309                "isEphemeral");
6310        if (isEphemeralDisabled()) {
6311            return false;
6312        }
6313
6314        if (!isCallerSameApp(packageName)) {
6315            return false;
6316        }
6317        synchronized (mPackages) {
6318            PackageParser.Package pkg = mPackages.get(packageName);
6319            if (pkg != null) {
6320                return pkg.applicationInfo.isEphemeralApp();
6321            }
6322        }
6323        return false;
6324    }
6325
6326    @Override
6327    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6328        if (isEphemeralDisabled()) {
6329            return null;
6330        }
6331
6332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6333                true /* requireFullPermission */, false /* checkShell */,
6334                "getCookie");
6335        if (!isCallerSameApp(packageName)) {
6336            return null;
6337        }
6338        synchronized (mPackages) {
6339            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6340                    packageName, userId);
6341        }
6342    }
6343
6344    @Override
6345    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6346        if (isEphemeralDisabled()) {
6347            return true;
6348        }
6349
6350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6351                true /* requireFullPermission */, true /* checkShell */,
6352                "setCookie");
6353        if (!isCallerSameApp(packageName)) {
6354            return false;
6355        }
6356        synchronized (mPackages) {
6357            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6358                    packageName, cookie, userId);
6359        }
6360    }
6361
6362    @Override
6363    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6364        if (isEphemeralDisabled()) {
6365            return null;
6366        }
6367
6368        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6369                "getEphemeralApplicationIcon");
6370        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6371                true /* requireFullPermission */, false /* checkShell */,
6372                "getEphemeralApplicationIcon");
6373        synchronized (mPackages) {
6374            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6375                    packageName, userId);
6376        }
6377    }
6378
6379    private boolean isCallerSameApp(String packageName) {
6380        PackageParser.Package pkg = mPackages.get(packageName);
6381        return pkg != null
6382                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6383    }
6384
6385    @Override
6386    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6387        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6388    }
6389
6390    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6391        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6392
6393        // reader
6394        synchronized (mPackages) {
6395            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6396            final int userId = UserHandle.getCallingUserId();
6397            while (i.hasNext()) {
6398                final PackageParser.Package p = i.next();
6399                if (p.applicationInfo == null) continue;
6400
6401                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6402                        && !p.applicationInfo.isDirectBootAware();
6403                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6404                        && p.applicationInfo.isDirectBootAware();
6405
6406                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6407                        && (!mSafeMode || isSystemApp(p))
6408                        && (matchesUnaware || matchesAware)) {
6409                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6410                    if (ps != null) {
6411                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6412                                ps.readUserState(userId), userId);
6413                        if (ai != null) {
6414                            finalList.add(ai);
6415                        }
6416                    }
6417                }
6418            }
6419        }
6420
6421        return finalList;
6422    }
6423
6424    @Override
6425    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6426        if (!sUserManager.exists(userId)) return null;
6427        flags = updateFlagsForComponent(flags, userId, name);
6428        // reader
6429        synchronized (mPackages) {
6430            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6431            PackageSetting ps = provider != null
6432                    ? mSettings.mPackages.get(provider.owner.packageName)
6433                    : null;
6434            return ps != null
6435                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6436                    ? PackageParser.generateProviderInfo(provider, flags,
6437                            ps.readUserState(userId), userId)
6438                    : null;
6439        }
6440    }
6441
6442    /**
6443     * @deprecated
6444     */
6445    @Deprecated
6446    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6447        // reader
6448        synchronized (mPackages) {
6449            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6450                    .entrySet().iterator();
6451            final int userId = UserHandle.getCallingUserId();
6452            while (i.hasNext()) {
6453                Map.Entry<String, PackageParser.Provider> entry = i.next();
6454                PackageParser.Provider p = entry.getValue();
6455                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6456
6457                if (ps != null && p.syncable
6458                        && (!mSafeMode || (p.info.applicationInfo.flags
6459                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6460                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6461                            ps.readUserState(userId), userId);
6462                    if (info != null) {
6463                        outNames.add(entry.getKey());
6464                        outInfo.add(info);
6465                    }
6466                }
6467            }
6468        }
6469    }
6470
6471    @Override
6472    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6473            int uid, int flags) {
6474        final int userId = processName != null ? UserHandle.getUserId(uid)
6475                : UserHandle.getCallingUserId();
6476        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6477        flags = updateFlagsForComponent(flags, userId, processName);
6478
6479        ArrayList<ProviderInfo> finalList = null;
6480        // reader
6481        synchronized (mPackages) {
6482            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6483            while (i.hasNext()) {
6484                final PackageParser.Provider p = i.next();
6485                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6486                if (ps != null && p.info.authority != null
6487                        && (processName == null
6488                                || (p.info.processName.equals(processName)
6489                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6490                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6491                    if (finalList == null) {
6492                        finalList = new ArrayList<ProviderInfo>(3);
6493                    }
6494                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6495                            ps.readUserState(userId), userId);
6496                    if (info != null) {
6497                        finalList.add(info);
6498                    }
6499                }
6500            }
6501        }
6502
6503        if (finalList != null) {
6504            Collections.sort(finalList, mProviderInitOrderSorter);
6505            return new ParceledListSlice<ProviderInfo>(finalList);
6506        }
6507
6508        return ParceledListSlice.emptyList();
6509    }
6510
6511    @Override
6512    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6513        // reader
6514        synchronized (mPackages) {
6515            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6516            return PackageParser.generateInstrumentationInfo(i, flags);
6517        }
6518    }
6519
6520    @Override
6521    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6522            String targetPackage, int flags) {
6523        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6524    }
6525
6526    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6527            int flags) {
6528        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6529
6530        // reader
6531        synchronized (mPackages) {
6532            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6533            while (i.hasNext()) {
6534                final PackageParser.Instrumentation p = i.next();
6535                if (targetPackage == null
6536                        || targetPackage.equals(p.info.targetPackage)) {
6537                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6538                            flags);
6539                    if (ii != null) {
6540                        finalList.add(ii);
6541                    }
6542                }
6543            }
6544        }
6545
6546        return finalList;
6547    }
6548
6549    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6550        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6551        if (overlays == null) {
6552            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6553            return;
6554        }
6555        for (PackageParser.Package opkg : overlays.values()) {
6556            // Not much to do if idmap fails: we already logged the error
6557            // and we certainly don't want to abort installation of pkg simply
6558            // because an overlay didn't fit properly. For these reasons,
6559            // ignore the return value of createIdmapForPackagePairLI.
6560            createIdmapForPackagePairLI(pkg, opkg);
6561        }
6562    }
6563
6564    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6565            PackageParser.Package opkg) {
6566        if (!opkg.mTrustedOverlay) {
6567            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6568                    opkg.baseCodePath + ": overlay not trusted");
6569            return false;
6570        }
6571        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6572        if (overlaySet == null) {
6573            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6574                    opkg.baseCodePath + " but target package has no known overlays");
6575            return false;
6576        }
6577        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6578        // TODO: generate idmap for split APKs
6579        try {
6580            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6581        } catch (InstallerException e) {
6582            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6583                    + opkg.baseCodePath);
6584            return false;
6585        }
6586        PackageParser.Package[] overlayArray =
6587            overlaySet.values().toArray(new PackageParser.Package[0]);
6588        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6589            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6590                return p1.mOverlayPriority - p2.mOverlayPriority;
6591            }
6592        };
6593        Arrays.sort(overlayArray, cmp);
6594
6595        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6596        int i = 0;
6597        for (PackageParser.Package p : overlayArray) {
6598            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6599        }
6600        return true;
6601    }
6602
6603    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6604        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6605        try {
6606            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6607        } finally {
6608            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6609        }
6610    }
6611
6612    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6613        final File[] files = dir.listFiles();
6614        if (ArrayUtils.isEmpty(files)) {
6615            Log.d(TAG, "No files in app dir " + dir);
6616            return;
6617        }
6618
6619        if (DEBUG_PACKAGE_SCANNING) {
6620            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6621                    + " flags=0x" + Integer.toHexString(parseFlags));
6622        }
6623
6624        for (File file : files) {
6625            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6626                    && !PackageInstallerService.isStageName(file.getName());
6627            if (!isPackage) {
6628                // Ignore entries which are not packages
6629                continue;
6630            }
6631            try {
6632                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6633                        scanFlags, currentTime, null);
6634            } catch (PackageManagerException e) {
6635                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6636
6637                // Delete invalid userdata apps
6638                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6639                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6640                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6641                    removeCodePathLI(file);
6642                }
6643            }
6644        }
6645    }
6646
6647    private static File getSettingsProblemFile() {
6648        File dataDir = Environment.getDataDirectory();
6649        File systemDir = new File(dataDir, "system");
6650        File fname = new File(systemDir, "uiderrors.txt");
6651        return fname;
6652    }
6653
6654    static void reportSettingsProblem(int priority, String msg) {
6655        logCriticalInfo(priority, msg);
6656    }
6657
6658    static void logCriticalInfo(int priority, String msg) {
6659        Slog.println(priority, TAG, msg);
6660        EventLogTags.writePmCriticalInfo(msg);
6661        try {
6662            File fname = getSettingsProblemFile();
6663            FileOutputStream out = new FileOutputStream(fname, true);
6664            PrintWriter pw = new FastPrintWriter(out);
6665            SimpleDateFormat formatter = new SimpleDateFormat();
6666            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6667            pw.println(dateString + ": " + msg);
6668            pw.close();
6669            FileUtils.setPermissions(
6670                    fname.toString(),
6671                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6672                    -1, -1);
6673        } catch (java.io.IOException e) {
6674        }
6675    }
6676
6677    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6678        if (srcFile.isDirectory()) {
6679            final File baseFile = new File(pkg.baseCodePath);
6680            long maxModifiedTime = baseFile.lastModified();
6681            if (pkg.splitCodePaths != null) {
6682                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6683                    final File splitFile = new File(pkg.splitCodePaths[i]);
6684                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6685                }
6686            }
6687            return maxModifiedTime;
6688        }
6689        return srcFile.lastModified();
6690    }
6691
6692    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6693            final int policyFlags) throws PackageManagerException {
6694        // When upgrading from pre-N MR1, verify the package time stamp using the package
6695        // directory and not the APK file.
6696        final long lastModifiedTime = mIsPreNMR1Upgrade
6697                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6698        if (ps != null
6699                && ps.codePath.equals(srcFile)
6700                && ps.timeStamp == lastModifiedTime
6701                && !isCompatSignatureUpdateNeeded(pkg)
6702                && !isRecoverSignatureUpdateNeeded(pkg)) {
6703            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6704            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6705            ArraySet<PublicKey> signingKs;
6706            synchronized (mPackages) {
6707                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6708            }
6709            if (ps.signatures.mSignatures != null
6710                    && ps.signatures.mSignatures.length != 0
6711                    && signingKs != null) {
6712                // Optimization: reuse the existing cached certificates
6713                // if the package appears to be unchanged.
6714                pkg.mSignatures = ps.signatures.mSignatures;
6715                pkg.mSigningKeys = signingKs;
6716                return;
6717            }
6718
6719            Slog.w(TAG, "PackageSetting for " + ps.name
6720                    + " is missing signatures.  Collecting certs again to recover them.");
6721        } else {
6722            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6723        }
6724
6725        try {
6726            PackageParser.collectCertificates(pkg, policyFlags);
6727        } catch (PackageParserException e) {
6728            throw PackageManagerException.from(e);
6729        }
6730    }
6731
6732    /**
6733     *  Traces a package scan.
6734     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6735     */
6736    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6737            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6738        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6739        try {
6740            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6741        } finally {
6742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6743        }
6744    }
6745
6746    /**
6747     *  Scans a package and returns the newly parsed package.
6748     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6749     */
6750    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6751            long currentTime, UserHandle user) throws PackageManagerException {
6752        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6753        PackageParser pp = new PackageParser();
6754        pp.setSeparateProcesses(mSeparateProcesses);
6755        pp.setOnlyCoreApps(mOnlyCore);
6756        pp.setDisplayMetrics(mMetrics);
6757
6758        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6759            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6760        }
6761
6762        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6763        final PackageParser.Package pkg;
6764        try {
6765            pkg = pp.parsePackage(scanFile, parseFlags);
6766        } catch (PackageParserException e) {
6767            throw PackageManagerException.from(e);
6768        } finally {
6769            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6770        }
6771
6772        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6773    }
6774
6775    /**
6776     *  Scans a package and returns the newly parsed package.
6777     *  @throws PackageManagerException on a parse error.
6778     */
6779    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6780            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6781            throws PackageManagerException {
6782        // If the package has children and this is the first dive in the function
6783        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6784        // packages (parent and children) would be successfully scanned before the
6785        // actual scan since scanning mutates internal state and we want to atomically
6786        // install the package and its children.
6787        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6788            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6789                scanFlags |= SCAN_CHECK_ONLY;
6790            }
6791        } else {
6792            scanFlags &= ~SCAN_CHECK_ONLY;
6793        }
6794
6795        // Scan the parent
6796        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6797                scanFlags, currentTime, user);
6798
6799        // Scan the children
6800        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6801        for (int i = 0; i < childCount; i++) {
6802            PackageParser.Package childPackage = pkg.childPackages.get(i);
6803            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6804                    currentTime, user);
6805        }
6806
6807
6808        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6809            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6810        }
6811
6812        return scannedPkg;
6813    }
6814
6815    /**
6816     *  Scans a package and returns the newly parsed package.
6817     *  @throws PackageManagerException on a parse error.
6818     */
6819    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6820            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6821            throws PackageManagerException {
6822        PackageSetting ps = null;
6823        PackageSetting updatedPkg;
6824        // reader
6825        synchronized (mPackages) {
6826            // Look to see if we already know about this package.
6827            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6828            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6829                // This package has been renamed to its original name.  Let's
6830                // use that.
6831                ps = mSettings.peekPackageLPr(oldName);
6832            }
6833            // If there was no original package, see one for the real package name.
6834            if (ps == null) {
6835                ps = mSettings.peekPackageLPr(pkg.packageName);
6836            }
6837            // Check to see if this package could be hiding/updating a system
6838            // package.  Must look for it either under the original or real
6839            // package name depending on our state.
6840            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6841            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6842
6843            // If this is a package we don't know about on the system partition, we
6844            // may need to remove disabled child packages on the system partition
6845            // or may need to not add child packages if the parent apk is updated
6846            // on the data partition and no longer defines this child package.
6847            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6848                // If this is a parent package for an updated system app and this system
6849                // app got an OTA update which no longer defines some of the child packages
6850                // we have to prune them from the disabled system packages.
6851                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6852                if (disabledPs != null) {
6853                    final int scannedChildCount = (pkg.childPackages != null)
6854                            ? pkg.childPackages.size() : 0;
6855                    final int disabledChildCount = disabledPs.childPackageNames != null
6856                            ? disabledPs.childPackageNames.size() : 0;
6857                    for (int i = 0; i < disabledChildCount; i++) {
6858                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6859                        boolean disabledPackageAvailable = false;
6860                        for (int j = 0; j < scannedChildCount; j++) {
6861                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6862                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6863                                disabledPackageAvailable = true;
6864                                break;
6865                            }
6866                         }
6867                         if (!disabledPackageAvailable) {
6868                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6869                         }
6870                    }
6871                }
6872            }
6873        }
6874
6875        boolean updatedPkgBetter = false;
6876        // First check if this is a system package that may involve an update
6877        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6878            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6879            // it needs to drop FLAG_PRIVILEGED.
6880            if (locationIsPrivileged(scanFile)) {
6881                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6882            } else {
6883                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6884            }
6885
6886            if (ps != null && !ps.codePath.equals(scanFile)) {
6887                // The path has changed from what was last scanned...  check the
6888                // version of the new path against what we have stored to determine
6889                // what to do.
6890                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6891                if (pkg.mVersionCode <= ps.versionCode) {
6892                    // The system package has been updated and the code path does not match
6893                    // Ignore entry. Skip it.
6894                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6895                            + " ignored: updated version " + ps.versionCode
6896                            + " better than this " + pkg.mVersionCode);
6897                    if (!updatedPkg.codePath.equals(scanFile)) {
6898                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6899                                + ps.name + " changing from " + updatedPkg.codePathString
6900                                + " to " + scanFile);
6901                        updatedPkg.codePath = scanFile;
6902                        updatedPkg.codePathString = scanFile.toString();
6903                        updatedPkg.resourcePath = scanFile;
6904                        updatedPkg.resourcePathString = scanFile.toString();
6905                    }
6906                    updatedPkg.pkg = pkg;
6907                    updatedPkg.versionCode = pkg.mVersionCode;
6908
6909                    // Update the disabled system child packages to point to the package too.
6910                    final int childCount = updatedPkg.childPackageNames != null
6911                            ? updatedPkg.childPackageNames.size() : 0;
6912                    for (int i = 0; i < childCount; i++) {
6913                        String childPackageName = updatedPkg.childPackageNames.get(i);
6914                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6915                                childPackageName);
6916                        if (updatedChildPkg != null) {
6917                            updatedChildPkg.pkg = pkg;
6918                            updatedChildPkg.versionCode = pkg.mVersionCode;
6919                        }
6920                    }
6921
6922                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6923                            + scanFile + " ignored: updated version " + ps.versionCode
6924                            + " better than this " + pkg.mVersionCode);
6925                } else {
6926                    // The current app on the system partition is better than
6927                    // what we have updated to on the data partition; switch
6928                    // back to the system partition version.
6929                    // At this point, its safely assumed that package installation for
6930                    // apps in system partition will go through. If not there won't be a working
6931                    // version of the app
6932                    // writer
6933                    synchronized (mPackages) {
6934                        // Just remove the loaded entries from package lists.
6935                        mPackages.remove(ps.name);
6936                    }
6937
6938                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6939                            + " reverting from " + ps.codePathString
6940                            + ": new version " + pkg.mVersionCode
6941                            + " better than installed " + ps.versionCode);
6942
6943                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6944                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6945                    synchronized (mInstallLock) {
6946                        args.cleanUpResourcesLI();
6947                    }
6948                    synchronized (mPackages) {
6949                        mSettings.enableSystemPackageLPw(ps.name);
6950                    }
6951                    updatedPkgBetter = true;
6952                }
6953            }
6954        }
6955
6956        if (updatedPkg != null) {
6957            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6958            // initially
6959            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6960
6961            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6962            // flag set initially
6963            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6964                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6965            }
6966        }
6967
6968        // Verify certificates against what was last scanned
6969        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6970
6971        /*
6972         * A new system app appeared, but we already had a non-system one of the
6973         * same name installed earlier.
6974         */
6975        boolean shouldHideSystemApp = false;
6976        if (updatedPkg == null && ps != null
6977                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6978            /*
6979             * Check to make sure the signatures match first. If they don't,
6980             * wipe the installed application and its data.
6981             */
6982            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6983                    != PackageManager.SIGNATURE_MATCH) {
6984                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6985                        + " signatures don't match existing userdata copy; removing");
6986                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6987                        "scanPackageInternalLI")) {
6988                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6989                }
6990                ps = null;
6991            } else {
6992                /*
6993                 * If the newly-added system app is an older version than the
6994                 * already installed version, hide it. It will be scanned later
6995                 * and re-added like an update.
6996                 */
6997                if (pkg.mVersionCode <= ps.versionCode) {
6998                    shouldHideSystemApp = true;
6999                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7000                            + " but new version " + pkg.mVersionCode + " better than installed "
7001                            + ps.versionCode + "; hiding system");
7002                } else {
7003                    /*
7004                     * The newly found system app is a newer version that the
7005                     * one previously installed. Simply remove the
7006                     * already-installed application and replace it with our own
7007                     * while keeping the application data.
7008                     */
7009                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7010                            + " reverting from " + ps.codePathString + ": new version "
7011                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7012                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7013                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7014                    synchronized (mInstallLock) {
7015                        args.cleanUpResourcesLI();
7016                    }
7017                }
7018            }
7019        }
7020
7021        // The apk is forward locked (not public) if its code and resources
7022        // are kept in different files. (except for app in either system or
7023        // vendor path).
7024        // TODO grab this value from PackageSettings
7025        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7026            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7027                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7028            }
7029        }
7030
7031        // TODO: extend to support forward-locked splits
7032        String resourcePath = null;
7033        String baseResourcePath = null;
7034        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7035            if (ps != null && ps.resourcePathString != null) {
7036                resourcePath = ps.resourcePathString;
7037                baseResourcePath = ps.resourcePathString;
7038            } else {
7039                // Should not happen at all. Just log an error.
7040                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7041            }
7042        } else {
7043            resourcePath = pkg.codePath;
7044            baseResourcePath = pkg.baseCodePath;
7045        }
7046
7047        // Set application objects path explicitly.
7048        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7049        pkg.setApplicationInfoCodePath(pkg.codePath);
7050        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7051        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7052        pkg.setApplicationInfoResourcePath(resourcePath);
7053        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7054        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7055
7056        // Note that we invoke the following method only if we are about to unpack an application
7057        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7058                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7059
7060        /*
7061         * If the system app should be overridden by a previously installed
7062         * data, hide the system app now and let the /data/app scan pick it up
7063         * again.
7064         */
7065        if (shouldHideSystemApp) {
7066            synchronized (mPackages) {
7067                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7068            }
7069        }
7070
7071        return scannedPkg;
7072    }
7073
7074    private static String fixProcessName(String defProcessName,
7075            String processName, int uid) {
7076        if (processName == null) {
7077            return defProcessName;
7078        }
7079        return processName;
7080    }
7081
7082    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7083            throws PackageManagerException {
7084        if (pkgSetting.signatures.mSignatures != null) {
7085            // Already existing package. Make sure signatures match
7086            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7087                    == PackageManager.SIGNATURE_MATCH;
7088            if (!match) {
7089                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7090                        == PackageManager.SIGNATURE_MATCH;
7091            }
7092            if (!match) {
7093                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7094                        == PackageManager.SIGNATURE_MATCH;
7095            }
7096            if (!match) {
7097                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7098                        + pkg.packageName + " signatures do not match the "
7099                        + "previously installed version; ignoring!");
7100            }
7101        }
7102
7103        // Check for shared user signatures
7104        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7105            // Already existing package. Make sure signatures match
7106            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7107                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7108            if (!match) {
7109                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7110                        == PackageManager.SIGNATURE_MATCH;
7111            }
7112            if (!match) {
7113                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7114                        == PackageManager.SIGNATURE_MATCH;
7115            }
7116            if (!match) {
7117                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7118                        "Package " + pkg.packageName
7119                        + " has no signatures that match those in shared user "
7120                        + pkgSetting.sharedUser.name + "; ignoring!");
7121            }
7122        }
7123    }
7124
7125    /**
7126     * Enforces that only the system UID or root's UID can call a method exposed
7127     * via Binder.
7128     *
7129     * @param message used as message if SecurityException is thrown
7130     * @throws SecurityException if the caller is not system or root
7131     */
7132    private static final void enforceSystemOrRoot(String message) {
7133        final int uid = Binder.getCallingUid();
7134        if (uid != Process.SYSTEM_UID && uid != 0) {
7135            throw new SecurityException(message);
7136        }
7137    }
7138
7139    @Override
7140    public void performFstrimIfNeeded() {
7141        enforceSystemOrRoot("Only the system can request fstrim");
7142
7143        // Before everything else, see whether we need to fstrim.
7144        try {
7145            IMountService ms = PackageHelper.getMountService();
7146            if (ms != null) {
7147                boolean doTrim = false;
7148                final long interval = android.provider.Settings.Global.getLong(
7149                        mContext.getContentResolver(),
7150                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7151                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7152                if (interval > 0) {
7153                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7154                    if (timeSinceLast > interval) {
7155                        doTrim = true;
7156                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7157                                + "; running immediately");
7158                    }
7159                }
7160                if (doTrim) {
7161                    final boolean dexOptDialogShown;
7162                    synchronized (mPackages) {
7163                        dexOptDialogShown = mDexOptDialogShown;
7164                    }
7165                    if (!isFirstBoot() && dexOptDialogShown) {
7166                        try {
7167                            ActivityManagerNative.getDefault().showBootMessage(
7168                                    mContext.getResources().getString(
7169                                            R.string.android_upgrading_fstrim), true);
7170                        } catch (RemoteException e) {
7171                        }
7172                    }
7173                    ms.runMaintenance();
7174                }
7175            } else {
7176                Slog.e(TAG, "Mount service unavailable!");
7177            }
7178        } catch (RemoteException e) {
7179            // Can't happen; MountService is local
7180        }
7181    }
7182
7183    @Override
7184    public void updatePackagesIfNeeded() {
7185        enforceSystemOrRoot("Only the system can request package update");
7186
7187        // We need to re-extract after an OTA.
7188        boolean causeUpgrade = isUpgrade();
7189
7190        // First boot or factory reset.
7191        // Note: we also handle devices that are upgrading to N right now as if it is their
7192        //       first boot, as they do not have profile data.
7193        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7194
7195        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7196        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7197
7198        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7199            return;
7200        }
7201
7202        List<PackageParser.Package> pkgs;
7203        synchronized (mPackages) {
7204            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7205        }
7206
7207        final long startTime = System.nanoTime();
7208        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7209                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7210
7211        final int elapsedTimeSeconds =
7212                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7213
7214        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7215        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7216        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7217        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7218        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7219    }
7220
7221    /**
7222     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7223     * containing statistics about the invocation. The array consists of three elements,
7224     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7225     * and {@code numberOfPackagesFailed}.
7226     */
7227    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7228            String compilerFilter) {
7229
7230        int numberOfPackagesVisited = 0;
7231        int numberOfPackagesOptimized = 0;
7232        int numberOfPackagesSkipped = 0;
7233        int numberOfPackagesFailed = 0;
7234        final int numberOfPackagesToDexopt = pkgs.size();
7235
7236        for (PackageParser.Package pkg : pkgs) {
7237            numberOfPackagesVisited++;
7238
7239            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7240                if (DEBUG_DEXOPT) {
7241                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7242                }
7243                numberOfPackagesSkipped++;
7244                continue;
7245            }
7246
7247            if (DEBUG_DEXOPT) {
7248                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7249                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7250            }
7251
7252            if (showDialog) {
7253                try {
7254                    ActivityManagerNative.getDefault().showBootMessage(
7255                            mContext.getResources().getString(R.string.android_upgrading_apk,
7256                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7257                } catch (RemoteException e) {
7258                }
7259                synchronized (mPackages) {
7260                    mDexOptDialogShown = true;
7261                }
7262            }
7263
7264            // If the OTA updates a system app which was previously preopted to a non-preopted state
7265            // the app might end up being verified at runtime. That's because by default the apps
7266            // are verify-profile but for preopted apps there's no profile.
7267            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7268            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7269            // filter (by default interpret-only).
7270            // Note that at this stage unused apps are already filtered.
7271            if (isSystemApp(pkg) &&
7272                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7273                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7274                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7275            }
7276
7277            // checkProfiles is false to avoid merging profiles during boot which
7278            // might interfere with background compilation (b/28612421).
7279            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7280            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7281            // trade-off worth doing to save boot time work.
7282            int dexOptStatus = performDexOptTraced(pkg.packageName,
7283                    false /* checkProfiles */,
7284                    compilerFilter,
7285                    false /* force */);
7286            switch (dexOptStatus) {
7287                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7288                    numberOfPackagesOptimized++;
7289                    break;
7290                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7291                    numberOfPackagesSkipped++;
7292                    break;
7293                case PackageDexOptimizer.DEX_OPT_FAILED:
7294                    numberOfPackagesFailed++;
7295                    break;
7296                default:
7297                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7298                    break;
7299            }
7300        }
7301
7302        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7303                numberOfPackagesFailed };
7304    }
7305
7306    @Override
7307    public void notifyPackageUse(String packageName, int reason) {
7308        synchronized (mPackages) {
7309            PackageParser.Package p = mPackages.get(packageName);
7310            if (p == null) {
7311                return;
7312            }
7313            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7314        }
7315    }
7316
7317    // TODO: this is not used nor needed. Delete it.
7318    @Override
7319    public boolean performDexOptIfNeeded(String packageName) {
7320        int dexOptStatus = performDexOptTraced(packageName,
7321                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7322        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7323    }
7324
7325    @Override
7326    public boolean performDexOpt(String packageName,
7327            boolean checkProfiles, int compileReason, boolean force) {
7328        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7329                getCompilerFilterForReason(compileReason), force);
7330        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7331    }
7332
7333    @Override
7334    public boolean performDexOptMode(String packageName,
7335            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7336        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7337                targetCompilerFilter, force);
7338        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7339    }
7340
7341    private int performDexOptTraced(String packageName,
7342                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7344        try {
7345            return performDexOptInternal(packageName, checkProfiles,
7346                    targetCompilerFilter, force);
7347        } finally {
7348            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7349        }
7350    }
7351
7352    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7353    // if the package can now be considered up to date for the given filter.
7354    private int performDexOptInternal(String packageName,
7355                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7356        PackageParser.Package p;
7357        synchronized (mPackages) {
7358            p = mPackages.get(packageName);
7359            if (p == null) {
7360                // Package could not be found. Report failure.
7361                return PackageDexOptimizer.DEX_OPT_FAILED;
7362            }
7363            mPackageUsage.maybeWriteAsync(mPackages);
7364            mCompilerStats.maybeWriteAsync();
7365        }
7366        long callingId = Binder.clearCallingIdentity();
7367        try {
7368            synchronized (mInstallLock) {
7369                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7370                        targetCompilerFilter, force);
7371            }
7372        } finally {
7373            Binder.restoreCallingIdentity(callingId);
7374        }
7375    }
7376
7377    public ArraySet<String> getOptimizablePackages() {
7378        ArraySet<String> pkgs = new ArraySet<String>();
7379        synchronized (mPackages) {
7380            for (PackageParser.Package p : mPackages.values()) {
7381                if (PackageDexOptimizer.canOptimizePackage(p)) {
7382                    pkgs.add(p.packageName);
7383                }
7384            }
7385        }
7386        return pkgs;
7387    }
7388
7389    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7390            boolean checkProfiles, String targetCompilerFilter,
7391            boolean force) {
7392        // Select the dex optimizer based on the force parameter.
7393        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7394        //       allocate an object here.
7395        PackageDexOptimizer pdo = force
7396                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7397                : mPackageDexOptimizer;
7398
7399        // Optimize all dependencies first. Note: we ignore the return value and march on
7400        // on errors.
7401        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7402        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7403        if (!deps.isEmpty()) {
7404            for (PackageParser.Package depPackage : deps) {
7405                // TODO: Analyze and investigate if we (should) profile libraries.
7406                // Currently this will do a full compilation of the library by default.
7407                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7408                        false /* checkProfiles */,
7409                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7410                        getOrCreateCompilerPackageStats(depPackage));
7411            }
7412        }
7413        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7414                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7415    }
7416
7417    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7418        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7419            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7420            Set<String> collectedNames = new HashSet<>();
7421            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7422
7423            retValue.remove(p);
7424
7425            return retValue;
7426        } else {
7427            return Collections.emptyList();
7428        }
7429    }
7430
7431    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7432            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7433        if (!collectedNames.contains(p.packageName)) {
7434            collectedNames.add(p.packageName);
7435            collected.add(p);
7436
7437            if (p.usesLibraries != null) {
7438                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7439            }
7440            if (p.usesOptionalLibraries != null) {
7441                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7442                        collectedNames);
7443            }
7444        }
7445    }
7446
7447    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7448            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7449        for (String libName : libs) {
7450            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7451            if (libPkg != null) {
7452                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7453            }
7454        }
7455    }
7456
7457    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7458        synchronized (mPackages) {
7459            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7460            if (lib != null && lib.apk != null) {
7461                return mPackages.get(lib.apk);
7462            }
7463        }
7464        return null;
7465    }
7466
7467    public void shutdown() {
7468        mPackageUsage.writeNow(mPackages);
7469        mCompilerStats.writeNow();
7470    }
7471
7472    @Override
7473    public void dumpProfiles(String packageName) {
7474        PackageParser.Package pkg;
7475        synchronized (mPackages) {
7476            pkg = mPackages.get(packageName);
7477            if (pkg == null) {
7478                throw new IllegalArgumentException("Unknown package: " + packageName);
7479            }
7480        }
7481        /* Only the shell, root, or the app user should be able to dump profiles. */
7482        int callingUid = Binder.getCallingUid();
7483        if (callingUid != Process.SHELL_UID &&
7484            callingUid != Process.ROOT_UID &&
7485            callingUid != pkg.applicationInfo.uid) {
7486            throw new SecurityException("dumpProfiles");
7487        }
7488
7489        synchronized (mInstallLock) {
7490            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7491            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7492            try {
7493                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7494                String gid = Integer.toString(sharedGid);
7495                String codePaths = TextUtils.join(";", allCodePaths);
7496                mInstaller.dumpProfiles(gid, packageName, codePaths);
7497            } catch (InstallerException e) {
7498                Slog.w(TAG, "Failed to dump profiles", e);
7499            }
7500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7501        }
7502    }
7503
7504    @Override
7505    public void forceDexOpt(String packageName) {
7506        enforceSystemOrRoot("forceDexOpt");
7507
7508        PackageParser.Package pkg;
7509        synchronized (mPackages) {
7510            pkg = mPackages.get(packageName);
7511            if (pkg == null) {
7512                throw new IllegalArgumentException("Unknown package: " + packageName);
7513            }
7514        }
7515
7516        synchronized (mInstallLock) {
7517            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7518
7519            // Whoever is calling forceDexOpt wants a fully compiled package.
7520            // Don't use profiles since that may cause compilation to be skipped.
7521            final int res = performDexOptInternalWithDependenciesLI(pkg,
7522                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7523                    true /* force */);
7524
7525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7526            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7527                throw new IllegalStateException("Failed to dexopt: " + res);
7528            }
7529        }
7530    }
7531
7532    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7533        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7534            Slog.w(TAG, "Unable to update from " + oldPkg.name
7535                    + " to " + newPkg.packageName
7536                    + ": old package not in system partition");
7537            return false;
7538        } else if (mPackages.get(oldPkg.name) != null) {
7539            Slog.w(TAG, "Unable to update from " + oldPkg.name
7540                    + " to " + newPkg.packageName
7541                    + ": old package still exists");
7542            return false;
7543        }
7544        return true;
7545    }
7546
7547    void removeCodePathLI(File codePath) {
7548        if (codePath.isDirectory()) {
7549            try {
7550                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7551            } catch (InstallerException e) {
7552                Slog.w(TAG, "Failed to remove code path", e);
7553            }
7554        } else {
7555            codePath.delete();
7556        }
7557    }
7558
7559    private int[] resolveUserIds(int userId) {
7560        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7561    }
7562
7563    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7564        if (pkg == null) {
7565            Slog.wtf(TAG, "Package was null!", new Throwable());
7566            return;
7567        }
7568        clearAppDataLeafLIF(pkg, userId, flags);
7569        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7570        for (int i = 0; i < childCount; i++) {
7571            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7572        }
7573    }
7574
7575    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7576        final PackageSetting ps;
7577        synchronized (mPackages) {
7578            ps = mSettings.mPackages.get(pkg.packageName);
7579        }
7580        for (int realUserId : resolveUserIds(userId)) {
7581            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7582            try {
7583                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7584                        ceDataInode);
7585            } catch (InstallerException e) {
7586                Slog.w(TAG, String.valueOf(e));
7587            }
7588        }
7589    }
7590
7591    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7592        if (pkg == null) {
7593            Slog.wtf(TAG, "Package was null!", new Throwable());
7594            return;
7595        }
7596        destroyAppDataLeafLIF(pkg, userId, flags);
7597        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7598        for (int i = 0; i < childCount; i++) {
7599            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7600        }
7601    }
7602
7603    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7604        final PackageSetting ps;
7605        synchronized (mPackages) {
7606            ps = mSettings.mPackages.get(pkg.packageName);
7607        }
7608        for (int realUserId : resolveUserIds(userId)) {
7609            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7610            try {
7611                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7612                        ceDataInode);
7613            } catch (InstallerException e) {
7614                Slog.w(TAG, String.valueOf(e));
7615            }
7616        }
7617    }
7618
7619    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7620        if (pkg == null) {
7621            Slog.wtf(TAG, "Package was null!", new Throwable());
7622            return;
7623        }
7624        destroyAppProfilesLeafLIF(pkg);
7625        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7627        for (int i = 0; i < childCount; i++) {
7628            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7629            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7630                    true /* removeBaseMarker */);
7631        }
7632    }
7633
7634    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7635            boolean removeBaseMarker) {
7636        if (pkg.isForwardLocked()) {
7637            return;
7638        }
7639
7640        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7641            try {
7642                path = PackageManagerServiceUtils.realpath(new File(path));
7643            } catch (IOException e) {
7644                // TODO: Should we return early here ?
7645                Slog.w(TAG, "Failed to get canonical path", e);
7646                continue;
7647            }
7648
7649            final String useMarker = path.replace('/', '@');
7650            for (int realUserId : resolveUserIds(userId)) {
7651                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7652                if (removeBaseMarker) {
7653                    File foreignUseMark = new File(profileDir, useMarker);
7654                    if (foreignUseMark.exists()) {
7655                        if (!foreignUseMark.delete()) {
7656                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7657                                    + pkg.packageName);
7658                        }
7659                    }
7660                }
7661
7662                File[] markers = profileDir.listFiles();
7663                if (markers != null) {
7664                    final String searchString = "@" + pkg.packageName + "@";
7665                    // We also delete all markers that contain the package name we're
7666                    // uninstalling. These are associated with secondary dex-files belonging
7667                    // to the package. Reconstructing the path of these dex files is messy
7668                    // in general.
7669                    for (File marker : markers) {
7670                        if (marker.getName().indexOf(searchString) > 0) {
7671                            if (!marker.delete()) {
7672                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7673                                    + pkg.packageName);
7674                            }
7675                        }
7676                    }
7677                }
7678            }
7679        }
7680    }
7681
7682    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7683        try {
7684            mInstaller.destroyAppProfiles(pkg.packageName);
7685        } catch (InstallerException e) {
7686            Slog.w(TAG, String.valueOf(e));
7687        }
7688    }
7689
7690    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7691        if (pkg == null) {
7692            Slog.wtf(TAG, "Package was null!", new Throwable());
7693            return;
7694        }
7695        clearAppProfilesLeafLIF(pkg);
7696        // We don't remove the base foreign use marker when clearing profiles because
7697        // we will rename it when the app is updated. Unlike the actual profile contents,
7698        // the foreign use marker is good across installs.
7699        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7700        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7701        for (int i = 0; i < childCount; i++) {
7702            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7703        }
7704    }
7705
7706    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7707        try {
7708            mInstaller.clearAppProfiles(pkg.packageName);
7709        } catch (InstallerException e) {
7710            Slog.w(TAG, String.valueOf(e));
7711        }
7712    }
7713
7714    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7715            long lastUpdateTime) {
7716        // Set parent install/update time
7717        PackageSetting ps = (PackageSetting) pkg.mExtras;
7718        if (ps != null) {
7719            ps.firstInstallTime = firstInstallTime;
7720            ps.lastUpdateTime = lastUpdateTime;
7721        }
7722        // Set children install/update time
7723        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7724        for (int i = 0; i < childCount; i++) {
7725            PackageParser.Package childPkg = pkg.childPackages.get(i);
7726            ps = (PackageSetting) childPkg.mExtras;
7727            if (ps != null) {
7728                ps.firstInstallTime = firstInstallTime;
7729                ps.lastUpdateTime = lastUpdateTime;
7730            }
7731        }
7732    }
7733
7734    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7735            PackageParser.Package changingLib) {
7736        if (file.path != null) {
7737            usesLibraryFiles.add(file.path);
7738            return;
7739        }
7740        PackageParser.Package p = mPackages.get(file.apk);
7741        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7742            // If we are doing this while in the middle of updating a library apk,
7743            // then we need to make sure to use that new apk for determining the
7744            // dependencies here.  (We haven't yet finished committing the new apk
7745            // to the package manager state.)
7746            if (p == null || p.packageName.equals(changingLib.packageName)) {
7747                p = changingLib;
7748            }
7749        }
7750        if (p != null) {
7751            usesLibraryFiles.addAll(p.getAllCodePaths());
7752        }
7753    }
7754
7755    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7756            PackageParser.Package changingLib) throws PackageManagerException {
7757        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7758            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7759            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7760            for (int i=0; i<N; i++) {
7761                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7762                if (file == null) {
7763                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7764                            "Package " + pkg.packageName + " requires unavailable shared library "
7765                            + pkg.usesLibraries.get(i) + "; failing!");
7766                }
7767                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7768            }
7769            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7770            for (int i=0; i<N; i++) {
7771                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7772                if (file == null) {
7773                    Slog.w(TAG, "Package " + pkg.packageName
7774                            + " desires unavailable shared library "
7775                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7776                } else {
7777                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7778                }
7779            }
7780            N = usesLibraryFiles.size();
7781            if (N > 0) {
7782                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7783            } else {
7784                pkg.usesLibraryFiles = null;
7785            }
7786        }
7787    }
7788
7789    private static boolean hasString(List<String> list, List<String> which) {
7790        if (list == null) {
7791            return false;
7792        }
7793        for (int i=list.size()-1; i>=0; i--) {
7794            for (int j=which.size()-1; j>=0; j--) {
7795                if (which.get(j).equals(list.get(i))) {
7796                    return true;
7797                }
7798            }
7799        }
7800        return false;
7801    }
7802
7803    private void updateAllSharedLibrariesLPw() {
7804        for (PackageParser.Package pkg : mPackages.values()) {
7805            try {
7806                updateSharedLibrariesLPw(pkg, null);
7807            } catch (PackageManagerException e) {
7808                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7809            }
7810        }
7811    }
7812
7813    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7814            PackageParser.Package changingPkg) {
7815        ArrayList<PackageParser.Package> res = null;
7816        for (PackageParser.Package pkg : mPackages.values()) {
7817            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7818                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7819                if (res == null) {
7820                    res = new ArrayList<PackageParser.Package>();
7821                }
7822                res.add(pkg);
7823                try {
7824                    updateSharedLibrariesLPw(pkg, changingPkg);
7825                } catch (PackageManagerException e) {
7826                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7827                }
7828            }
7829        }
7830        return res;
7831    }
7832
7833    /**
7834     * Derive the value of the {@code cpuAbiOverride} based on the provided
7835     * value and an optional stored value from the package settings.
7836     */
7837    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7838        String cpuAbiOverride = null;
7839
7840        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7841            cpuAbiOverride = null;
7842        } else if (abiOverride != null) {
7843            cpuAbiOverride = abiOverride;
7844        } else if (settings != null) {
7845            cpuAbiOverride = settings.cpuAbiOverrideString;
7846        }
7847
7848        return cpuAbiOverride;
7849    }
7850
7851    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7852            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7853                    throws PackageManagerException {
7854        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7855        // If the package has children and this is the first dive in the function
7856        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7857        // whether all packages (parent and children) would be successfully scanned
7858        // before the actual scan since scanning mutates internal state and we want
7859        // to atomically install the package and its children.
7860        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7861            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7862                scanFlags |= SCAN_CHECK_ONLY;
7863            }
7864        } else {
7865            scanFlags &= ~SCAN_CHECK_ONLY;
7866        }
7867
7868        final PackageParser.Package scannedPkg;
7869        try {
7870            // Scan the parent
7871            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7872            // Scan the children
7873            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7874            for (int i = 0; i < childCount; i++) {
7875                PackageParser.Package childPkg = pkg.childPackages.get(i);
7876                scanPackageLI(childPkg, policyFlags,
7877                        scanFlags, currentTime, user);
7878            }
7879        } finally {
7880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7881        }
7882
7883        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7884            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7885        }
7886
7887        return scannedPkg;
7888    }
7889
7890    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7891            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7892        boolean success = false;
7893        try {
7894            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7895                    currentTime, user);
7896            success = true;
7897            return res;
7898        } finally {
7899            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7900                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7901                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7902                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7903                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7904            }
7905        }
7906    }
7907
7908    /**
7909     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7910     */
7911    private static boolean apkHasCode(String fileName) {
7912        StrictJarFile jarFile = null;
7913        try {
7914            jarFile = new StrictJarFile(fileName,
7915                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7916            return jarFile.findEntry("classes.dex") != null;
7917        } catch (IOException ignore) {
7918        } finally {
7919            try {
7920                if (jarFile != null) {
7921                    jarFile.close();
7922                }
7923            } catch (IOException ignore) {}
7924        }
7925        return false;
7926    }
7927
7928    /**
7929     * Enforces code policy for the package. This ensures that if an APK has
7930     * declared hasCode="true" in its manifest that the APK actually contains
7931     * code.
7932     *
7933     * @throws PackageManagerException If bytecode could not be found when it should exist
7934     */
7935    private static void enforceCodePolicy(PackageParser.Package pkg)
7936            throws PackageManagerException {
7937        final boolean shouldHaveCode =
7938                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7939        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7940            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7941                    "Package " + pkg.baseCodePath + " code is missing");
7942        }
7943
7944        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7945            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7946                final boolean splitShouldHaveCode =
7947                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7948                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7949                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7950                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7951                }
7952            }
7953        }
7954    }
7955
7956    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7957            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7958            throws PackageManagerException {
7959        final File scanFile = new File(pkg.codePath);
7960        if (pkg.applicationInfo.getCodePath() == null ||
7961                pkg.applicationInfo.getResourcePath() == null) {
7962            // Bail out. The resource and code paths haven't been set.
7963            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7964                    "Code and resource paths haven't been set correctly");
7965        }
7966
7967        // Apply policy
7968        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7969            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7970            if (pkg.applicationInfo.isDirectBootAware()) {
7971                // we're direct boot aware; set for all components
7972                for (PackageParser.Service s : pkg.services) {
7973                    s.info.encryptionAware = s.info.directBootAware = true;
7974                }
7975                for (PackageParser.Provider p : pkg.providers) {
7976                    p.info.encryptionAware = p.info.directBootAware = true;
7977                }
7978                for (PackageParser.Activity a : pkg.activities) {
7979                    a.info.encryptionAware = a.info.directBootAware = true;
7980                }
7981                for (PackageParser.Activity r : pkg.receivers) {
7982                    r.info.encryptionAware = r.info.directBootAware = true;
7983                }
7984            }
7985        } else {
7986            // Only allow system apps to be flagged as core apps.
7987            pkg.coreApp = false;
7988            // clear flags not applicable to regular apps
7989            pkg.applicationInfo.privateFlags &=
7990                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7991            pkg.applicationInfo.privateFlags &=
7992                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7993        }
7994        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7995
7996        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7997            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7998        }
7999
8000        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8001            enforceCodePolicy(pkg);
8002        }
8003
8004        if (mCustomResolverComponentName != null &&
8005                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8006            setUpCustomResolverActivity(pkg);
8007        }
8008
8009        if (pkg.packageName.equals("android")) {
8010            synchronized (mPackages) {
8011                if (mAndroidApplication != null) {
8012                    Slog.w(TAG, "*************************************************");
8013                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8014                    Slog.w(TAG, " file=" + scanFile);
8015                    Slog.w(TAG, "*************************************************");
8016                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8017                            "Core android package being redefined.  Skipping.");
8018                }
8019
8020                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8021                    // Set up information for our fall-back user intent resolution activity.
8022                    mPlatformPackage = pkg;
8023                    pkg.mVersionCode = mSdkVersion;
8024                    mAndroidApplication = pkg.applicationInfo;
8025
8026                    if (!mResolverReplaced) {
8027                        mResolveActivity.applicationInfo = mAndroidApplication;
8028                        mResolveActivity.name = ResolverActivity.class.getName();
8029                        mResolveActivity.packageName = mAndroidApplication.packageName;
8030                        mResolveActivity.processName = "system:ui";
8031                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8032                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8033                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8034                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8035                        mResolveActivity.exported = true;
8036                        mResolveActivity.enabled = true;
8037                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8038                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8039                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8040                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8041                                | ActivityInfo.CONFIG_ORIENTATION
8042                                | ActivityInfo.CONFIG_KEYBOARD
8043                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8044                        mResolveInfo.activityInfo = mResolveActivity;
8045                        mResolveInfo.priority = 0;
8046                        mResolveInfo.preferredOrder = 0;
8047                        mResolveInfo.match = 0;
8048                        mResolveComponentName = new ComponentName(
8049                                mAndroidApplication.packageName, mResolveActivity.name);
8050                    }
8051                }
8052            }
8053        }
8054
8055        if (DEBUG_PACKAGE_SCANNING) {
8056            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8057                Log.d(TAG, "Scanning package " + pkg.packageName);
8058        }
8059
8060        synchronized (mPackages) {
8061            if (mPackages.containsKey(pkg.packageName)
8062                    || mSharedLibraries.containsKey(pkg.packageName)) {
8063                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8064                        "Application package " + pkg.packageName
8065                                + " already installed.  Skipping duplicate.");
8066            }
8067
8068            // If we're only installing presumed-existing packages, require that the
8069            // scanned APK is both already known and at the path previously established
8070            // for it.  Previously unknown packages we pick up normally, but if we have an
8071            // a priori expectation about this package's install presence, enforce it.
8072            // With a singular exception for new system packages. When an OTA contains
8073            // a new system package, we allow the codepath to change from a system location
8074            // to the user-installed location. If we don't allow this change, any newer,
8075            // user-installed version of the application will be ignored.
8076            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8077                if (mExpectingBetter.containsKey(pkg.packageName)) {
8078                    logCriticalInfo(Log.WARN,
8079                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8080                } else {
8081                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8082                    if (known != null) {
8083                        if (DEBUG_PACKAGE_SCANNING) {
8084                            Log.d(TAG, "Examining " + pkg.codePath
8085                                    + " and requiring known paths " + known.codePathString
8086                                    + " & " + known.resourcePathString);
8087                        }
8088                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8089                                || !pkg.applicationInfo.getResourcePath().equals(
8090                                known.resourcePathString)) {
8091                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8092                                    "Application package " + pkg.packageName
8093                                            + " found at " + pkg.applicationInfo.getCodePath()
8094                                            + " but expected at " + known.codePathString
8095                                            + "; ignoring.");
8096                        }
8097                    }
8098                }
8099            }
8100        }
8101
8102        // Initialize package source and resource directories
8103        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8104        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8105
8106        SharedUserSetting suid = null;
8107        PackageSetting pkgSetting = null;
8108
8109        if (!isSystemApp(pkg)) {
8110            // Only system apps can use these features.
8111            pkg.mOriginalPackages = null;
8112            pkg.mRealPackage = null;
8113            pkg.mAdoptPermissions = null;
8114        }
8115
8116        // Getting the package setting may have a side-effect, so if we
8117        // are only checking if scan would succeed, stash a copy of the
8118        // old setting to restore at the end.
8119        PackageSetting nonMutatedPs = null;
8120
8121        // writer
8122        synchronized (mPackages) {
8123            if (pkg.mSharedUserId != null) {
8124                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8125                if (suid == null) {
8126                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8127                            "Creating application package " + pkg.packageName
8128                            + " for shared user failed");
8129                }
8130                if (DEBUG_PACKAGE_SCANNING) {
8131                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8132                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8133                                + "): packages=" + suid.packages);
8134                }
8135            }
8136
8137            // Check if we are renaming from an original package name.
8138            PackageSetting origPackage = null;
8139            String realName = null;
8140            if (pkg.mOriginalPackages != null) {
8141                // This package may need to be renamed to a previously
8142                // installed name.  Let's check on that...
8143                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8144                if (pkg.mOriginalPackages.contains(renamed)) {
8145                    // This package had originally been installed as the
8146                    // original name, and we have already taken care of
8147                    // transitioning to the new one.  Just update the new
8148                    // one to continue using the old name.
8149                    realName = pkg.mRealPackage;
8150                    if (!pkg.packageName.equals(renamed)) {
8151                        // Callers into this function may have already taken
8152                        // care of renaming the package; only do it here if
8153                        // it is not already done.
8154                        pkg.setPackageName(renamed);
8155                    }
8156
8157                } else {
8158                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8159                        if ((origPackage = mSettings.peekPackageLPr(
8160                                pkg.mOriginalPackages.get(i))) != null) {
8161                            // We do have the package already installed under its
8162                            // original name...  should we use it?
8163                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8164                                // New package is not compatible with original.
8165                                origPackage = null;
8166                                continue;
8167                            } else if (origPackage.sharedUser != null) {
8168                                // Make sure uid is compatible between packages.
8169                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8170                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8171                                            + " to " + pkg.packageName + ": old uid "
8172                                            + origPackage.sharedUser.name
8173                                            + " differs from " + pkg.mSharedUserId);
8174                                    origPackage = null;
8175                                    continue;
8176                                }
8177                                // TODO: Add case when shared user id is added [b/28144775]
8178                            } else {
8179                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8180                                        + pkg.packageName + " to old name " + origPackage.name);
8181                            }
8182                            break;
8183                        }
8184                    }
8185                }
8186            }
8187
8188            if (mTransferedPackages.contains(pkg.packageName)) {
8189                Slog.w(TAG, "Package " + pkg.packageName
8190                        + " was transferred to another, but its .apk remains");
8191            }
8192
8193            // See comments in nonMutatedPs declaration
8194            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8195                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8196                if (foundPs != null) {
8197                    nonMutatedPs = new PackageSetting(foundPs);
8198                }
8199            }
8200
8201            // Just create the setting, don't add it yet. For already existing packages
8202            // the PkgSetting exists already and doesn't have to be created.
8203            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8204                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8205                    pkg.applicationInfo.primaryCpuAbi,
8206                    pkg.applicationInfo.secondaryCpuAbi,
8207                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8208                    user, false);
8209            if (pkgSetting == null) {
8210                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8211                        "Creating application package " + pkg.packageName + " failed");
8212            }
8213
8214            if (pkgSetting.origPackage != null) {
8215                // If we are first transitioning from an original package,
8216                // fix up the new package's name now.  We need to do this after
8217                // looking up the package under its new name, so getPackageLP
8218                // can take care of fiddling things correctly.
8219                pkg.setPackageName(origPackage.name);
8220
8221                // File a report about this.
8222                String msg = "New package " + pkgSetting.realName
8223                        + " renamed to replace old package " + pkgSetting.name;
8224                reportSettingsProblem(Log.WARN, msg);
8225
8226                // Make a note of it.
8227                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8228                    mTransferedPackages.add(origPackage.name);
8229                }
8230
8231                // No longer need to retain this.
8232                pkgSetting.origPackage = null;
8233            }
8234
8235            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8236                // Make a note of it.
8237                mTransferedPackages.add(pkg.packageName);
8238            }
8239
8240            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8241                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8242            }
8243
8244            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8245                // Check all shared libraries and map to their actual file path.
8246                // We only do this here for apps not on a system dir, because those
8247                // are the only ones that can fail an install due to this.  We
8248                // will take care of the system apps by updating all of their
8249                // library paths after the scan is done.
8250                updateSharedLibrariesLPw(pkg, null);
8251            }
8252
8253            if (mFoundPolicyFile) {
8254                SELinuxMMAC.assignSeinfoValue(pkg);
8255            }
8256
8257            pkg.applicationInfo.uid = pkgSetting.appId;
8258            pkg.mExtras = pkgSetting;
8259            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8260                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8261                    // We just determined the app is signed correctly, so bring
8262                    // over the latest parsed certs.
8263                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8264                } else {
8265                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8266                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8267                                "Package " + pkg.packageName + " upgrade keys do not match the "
8268                                + "previously installed version");
8269                    } else {
8270                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8271                        String msg = "System package " + pkg.packageName
8272                            + " signature changed; retaining data.";
8273                        reportSettingsProblem(Log.WARN, msg);
8274                    }
8275                }
8276            } else {
8277                try {
8278                    verifySignaturesLP(pkgSetting, pkg);
8279                    // We just determined the app is signed correctly, so bring
8280                    // over the latest parsed certs.
8281                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8282                } catch (PackageManagerException e) {
8283                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8284                        throw e;
8285                    }
8286                    // The signature has changed, but this package is in the system
8287                    // image...  let's recover!
8288                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8289                    // However...  if this package is part of a shared user, but it
8290                    // doesn't match the signature of the shared user, let's fail.
8291                    // What this means is that you can't change the signatures
8292                    // associated with an overall shared user, which doesn't seem all
8293                    // that unreasonable.
8294                    if (pkgSetting.sharedUser != null) {
8295                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8296                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8297                            throw new PackageManagerException(
8298                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8299                                            "Signature mismatch for shared user: "
8300                                            + pkgSetting.sharedUser);
8301                        }
8302                    }
8303                    // File a report about this.
8304                    String msg = "System package " + pkg.packageName
8305                        + " signature changed; retaining data.";
8306                    reportSettingsProblem(Log.WARN, msg);
8307                }
8308            }
8309            // Verify that this new package doesn't have any content providers
8310            // that conflict with existing packages.  Only do this if the
8311            // package isn't already installed, since we don't want to break
8312            // things that are installed.
8313            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8314                final int N = pkg.providers.size();
8315                int i;
8316                for (i=0; i<N; i++) {
8317                    PackageParser.Provider p = pkg.providers.get(i);
8318                    if (p.info.authority != null) {
8319                        String names[] = p.info.authority.split(";");
8320                        for (int j = 0; j < names.length; j++) {
8321                            if (mProvidersByAuthority.containsKey(names[j])) {
8322                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8323                                final String otherPackageName =
8324                                        ((other != null && other.getComponentName() != null) ?
8325                                                other.getComponentName().getPackageName() : "?");
8326                                throw new PackageManagerException(
8327                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8328                                                "Can't install because provider name " + names[j]
8329                                                + " (in package " + pkg.applicationInfo.packageName
8330                                                + ") is already used by " + otherPackageName);
8331                            }
8332                        }
8333                    }
8334                }
8335            }
8336
8337            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8338                // This package wants to adopt ownership of permissions from
8339                // another package.
8340                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8341                    final String origName = pkg.mAdoptPermissions.get(i);
8342                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8343                    if (orig != null) {
8344                        if (verifyPackageUpdateLPr(orig, pkg)) {
8345                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8346                                    + pkg.packageName);
8347                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8348                        }
8349                    }
8350                }
8351            }
8352        }
8353
8354        final String pkgName = pkg.packageName;
8355
8356        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8357        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8358        pkg.applicationInfo.processName = fixProcessName(
8359                pkg.applicationInfo.packageName,
8360                pkg.applicationInfo.processName,
8361                pkg.applicationInfo.uid);
8362
8363        if (pkg != mPlatformPackage) {
8364            // Get all of our default paths setup
8365            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8366        }
8367
8368        final String path = scanFile.getPath();
8369        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8370
8371        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8372            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8373
8374            // Some system apps still use directory structure for native libraries
8375            // in which case we might end up not detecting abi solely based on apk
8376            // structure. Try to detect abi based on directory structure.
8377            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8378                    pkg.applicationInfo.primaryCpuAbi == null) {
8379                setBundledAppAbisAndRoots(pkg, pkgSetting);
8380                setNativeLibraryPaths(pkg);
8381            }
8382
8383        } else {
8384            if ((scanFlags & SCAN_MOVE) != 0) {
8385                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8386                // but we already have this packages package info in the PackageSetting. We just
8387                // use that and derive the native library path based on the new codepath.
8388                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8389                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8390            }
8391
8392            // Set native library paths again. For moves, the path will be updated based on the
8393            // ABIs we've determined above. For non-moves, the path will be updated based on the
8394            // ABIs we determined during compilation, but the path will depend on the final
8395            // package path (after the rename away from the stage path).
8396            setNativeLibraryPaths(pkg);
8397        }
8398
8399        // This is a special case for the "system" package, where the ABI is
8400        // dictated by the zygote configuration (and init.rc). We should keep track
8401        // of this ABI so that we can deal with "normal" applications that run under
8402        // the same UID correctly.
8403        if (mPlatformPackage == pkg) {
8404            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8405                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8406        }
8407
8408        // If there's a mismatch between the abi-override in the package setting
8409        // and the abiOverride specified for the install. Warn about this because we
8410        // would've already compiled the app without taking the package setting into
8411        // account.
8412        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8413            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8414                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8415                        " for package " + pkg.packageName);
8416            }
8417        }
8418
8419        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8420        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8421        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8422
8423        // Copy the derived override back to the parsed package, so that we can
8424        // update the package settings accordingly.
8425        pkg.cpuAbiOverride = cpuAbiOverride;
8426
8427        if (DEBUG_ABI_SELECTION) {
8428            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8429                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8430                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8431        }
8432
8433        // Push the derived path down into PackageSettings so we know what to
8434        // clean up at uninstall time.
8435        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8436
8437        if (DEBUG_ABI_SELECTION) {
8438            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8439                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8440                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8441        }
8442
8443        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8444            // We don't do this here during boot because we can do it all
8445            // at once after scanning all existing packages.
8446            //
8447            // We also do this *before* we perform dexopt on this package, so that
8448            // we can avoid redundant dexopts, and also to make sure we've got the
8449            // code and package path correct.
8450            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8451                    pkg, true /* boot complete */);
8452        }
8453
8454        if (mFactoryTest && pkg.requestedPermissions.contains(
8455                android.Manifest.permission.FACTORY_TEST)) {
8456            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8457        }
8458
8459        if (isSystemApp(pkg)) {
8460            pkgSetting.isOrphaned = true;
8461        }
8462
8463        ArrayList<PackageParser.Package> clientLibPkgs = null;
8464
8465        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8466            if (nonMutatedPs != null) {
8467                synchronized (mPackages) {
8468                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8469                }
8470            }
8471            return pkg;
8472        }
8473
8474        // Only privileged apps and updated privileged apps can add child packages.
8475        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8476            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8477                throw new PackageManagerException("Only privileged apps and updated "
8478                        + "privileged apps can add child packages. Ignoring package "
8479                        + pkg.packageName);
8480            }
8481            final int childCount = pkg.childPackages.size();
8482            for (int i = 0; i < childCount; i++) {
8483                PackageParser.Package childPkg = pkg.childPackages.get(i);
8484                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8485                        childPkg.packageName)) {
8486                    throw new PackageManagerException("Cannot override a child package of "
8487                            + "another disabled system app. Ignoring package " + pkg.packageName);
8488                }
8489            }
8490        }
8491
8492        // writer
8493        synchronized (mPackages) {
8494            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8495                // Only system apps can add new shared libraries.
8496                if (pkg.libraryNames != null) {
8497                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8498                        String name = pkg.libraryNames.get(i);
8499                        boolean allowed = false;
8500                        if (pkg.isUpdatedSystemApp()) {
8501                            // New library entries can only be added through the
8502                            // system image.  This is important to get rid of a lot
8503                            // of nasty edge cases: for example if we allowed a non-
8504                            // system update of the app to add a library, then uninstalling
8505                            // the update would make the library go away, and assumptions
8506                            // we made such as through app install filtering would now
8507                            // have allowed apps on the device which aren't compatible
8508                            // with it.  Better to just have the restriction here, be
8509                            // conservative, and create many fewer cases that can negatively
8510                            // impact the user experience.
8511                            final PackageSetting sysPs = mSettings
8512                                    .getDisabledSystemPkgLPr(pkg.packageName);
8513                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8514                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8515                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8516                                        allowed = true;
8517                                        break;
8518                                    }
8519                                }
8520                            }
8521                        } else {
8522                            allowed = true;
8523                        }
8524                        if (allowed) {
8525                            if (!mSharedLibraries.containsKey(name)) {
8526                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8527                            } else if (!name.equals(pkg.packageName)) {
8528                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8529                                        + name + " already exists; skipping");
8530                            }
8531                        } else {
8532                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8533                                    + name + " that is not declared on system image; skipping");
8534                        }
8535                    }
8536                    if ((scanFlags & SCAN_BOOTING) == 0) {
8537                        // If we are not booting, we need to update any applications
8538                        // that are clients of our shared library.  If we are booting,
8539                        // this will all be done once the scan is complete.
8540                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8541                    }
8542                }
8543            }
8544        }
8545
8546        if ((scanFlags & SCAN_BOOTING) != 0) {
8547            // No apps can run during boot scan, so they don't need to be frozen
8548        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8549            // Caller asked to not kill app, so it's probably not frozen
8550        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8551            // Caller asked us to ignore frozen check for some reason; they
8552            // probably didn't know the package name
8553        } else {
8554            // We're doing major surgery on this package, so it better be frozen
8555            // right now to keep it from launching
8556            checkPackageFrozen(pkgName);
8557        }
8558
8559        // Also need to kill any apps that are dependent on the library.
8560        if (clientLibPkgs != null) {
8561            for (int i=0; i<clientLibPkgs.size(); i++) {
8562                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8563                killApplication(clientPkg.applicationInfo.packageName,
8564                        clientPkg.applicationInfo.uid, "update lib");
8565            }
8566        }
8567
8568        // Make sure we're not adding any bogus keyset info
8569        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8570        ksms.assertScannedPackageValid(pkg);
8571
8572        // writer
8573        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8574
8575        boolean createIdmapFailed = false;
8576        synchronized (mPackages) {
8577            // We don't expect installation to fail beyond this point
8578
8579            if (pkgSetting.pkg != null) {
8580                // Note that |user| might be null during the initial boot scan. If a codePath
8581                // for an app has changed during a boot scan, it's due to an app update that's
8582                // part of the system partition and marker changes must be applied to all users.
8583                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8584                    (user != null) ? user : UserHandle.ALL);
8585            }
8586
8587            // Add the new setting to mSettings
8588            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8589            // Add the new setting to mPackages
8590            mPackages.put(pkg.applicationInfo.packageName, pkg);
8591            // Make sure we don't accidentally delete its data.
8592            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8593            while (iter.hasNext()) {
8594                PackageCleanItem item = iter.next();
8595                if (pkgName.equals(item.packageName)) {
8596                    iter.remove();
8597                }
8598            }
8599
8600            // Take care of first install / last update times.
8601            if (currentTime != 0) {
8602                if (pkgSetting.firstInstallTime == 0) {
8603                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8604                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8605                    pkgSetting.lastUpdateTime = currentTime;
8606                }
8607            } else if (pkgSetting.firstInstallTime == 0) {
8608                // We need *something*.  Take time time stamp of the file.
8609                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8610            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8611                if (scanFileTime != pkgSetting.timeStamp) {
8612                    // A package on the system image has changed; consider this
8613                    // to be an update.
8614                    pkgSetting.lastUpdateTime = scanFileTime;
8615                }
8616            }
8617
8618            // Add the package's KeySets to the global KeySetManagerService
8619            ksms.addScannedPackageLPw(pkg);
8620
8621            int N = pkg.providers.size();
8622            StringBuilder r = null;
8623            int i;
8624            for (i=0; i<N; i++) {
8625                PackageParser.Provider p = pkg.providers.get(i);
8626                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8627                        p.info.processName, pkg.applicationInfo.uid);
8628                mProviders.addProvider(p);
8629                p.syncable = p.info.isSyncable;
8630                if (p.info.authority != null) {
8631                    String names[] = p.info.authority.split(";");
8632                    p.info.authority = null;
8633                    for (int j = 0; j < names.length; j++) {
8634                        if (j == 1 && p.syncable) {
8635                            // We only want the first authority for a provider to possibly be
8636                            // syncable, so if we already added this provider using a different
8637                            // authority clear the syncable flag. We copy the provider before
8638                            // changing it because the mProviders object contains a reference
8639                            // to a provider that we don't want to change.
8640                            // Only do this for the second authority since the resulting provider
8641                            // object can be the same for all future authorities for this provider.
8642                            p = new PackageParser.Provider(p);
8643                            p.syncable = false;
8644                        }
8645                        if (!mProvidersByAuthority.containsKey(names[j])) {
8646                            mProvidersByAuthority.put(names[j], p);
8647                            if (p.info.authority == null) {
8648                                p.info.authority = names[j];
8649                            } else {
8650                                p.info.authority = p.info.authority + ";" + names[j];
8651                            }
8652                            if (DEBUG_PACKAGE_SCANNING) {
8653                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8654                                    Log.d(TAG, "Registered content provider: " + names[j]
8655                                            + ", className = " + p.info.name + ", isSyncable = "
8656                                            + p.info.isSyncable);
8657                            }
8658                        } else {
8659                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8660                            Slog.w(TAG, "Skipping provider name " + names[j] +
8661                                    " (in package " + pkg.applicationInfo.packageName +
8662                                    "): name already used by "
8663                                    + ((other != null && other.getComponentName() != null)
8664                                            ? other.getComponentName().getPackageName() : "?"));
8665                        }
8666                    }
8667                }
8668                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8669                    if (r == null) {
8670                        r = new StringBuilder(256);
8671                    } else {
8672                        r.append(' ');
8673                    }
8674                    r.append(p.info.name);
8675                }
8676            }
8677            if (r != null) {
8678                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8679            }
8680
8681            N = pkg.services.size();
8682            r = null;
8683            for (i=0; i<N; i++) {
8684                PackageParser.Service s = pkg.services.get(i);
8685                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8686                        s.info.processName, pkg.applicationInfo.uid);
8687                mServices.addService(s);
8688                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8689                    if (r == null) {
8690                        r = new StringBuilder(256);
8691                    } else {
8692                        r.append(' ');
8693                    }
8694                    r.append(s.info.name);
8695                }
8696            }
8697            if (r != null) {
8698                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8699            }
8700
8701            N = pkg.receivers.size();
8702            r = null;
8703            for (i=0; i<N; i++) {
8704                PackageParser.Activity a = pkg.receivers.get(i);
8705                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8706                        a.info.processName, pkg.applicationInfo.uid);
8707                mReceivers.addActivity(a, "receiver");
8708                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8709                    if (r == null) {
8710                        r = new StringBuilder(256);
8711                    } else {
8712                        r.append(' ');
8713                    }
8714                    r.append(a.info.name);
8715                }
8716            }
8717            if (r != null) {
8718                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8719            }
8720
8721            N = pkg.activities.size();
8722            r = null;
8723            for (i=0; i<N; i++) {
8724                PackageParser.Activity a = pkg.activities.get(i);
8725                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8726                        a.info.processName, pkg.applicationInfo.uid);
8727                mActivities.addActivity(a, "activity");
8728                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8729                    if (r == null) {
8730                        r = new StringBuilder(256);
8731                    } else {
8732                        r.append(' ');
8733                    }
8734                    r.append(a.info.name);
8735                }
8736            }
8737            if (r != null) {
8738                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8739            }
8740
8741            N = pkg.permissionGroups.size();
8742            r = null;
8743            for (i=0; i<N; i++) {
8744                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8745                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8746                final String curPackageName = cur == null ? null : cur.info.packageName;
8747                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8748                if (cur == null || isPackageUpdate) {
8749                    mPermissionGroups.put(pg.info.name, pg);
8750                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8751                        if (r == null) {
8752                            r = new StringBuilder(256);
8753                        } else {
8754                            r.append(' ');
8755                        }
8756                        if (isPackageUpdate) {
8757                            r.append("UPD:");
8758                        }
8759                        r.append(pg.info.name);
8760                    }
8761                } else {
8762                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8763                            + pg.info.packageName + " ignored: original from "
8764                            + cur.info.packageName);
8765                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8766                        if (r == null) {
8767                            r = new StringBuilder(256);
8768                        } else {
8769                            r.append(' ');
8770                        }
8771                        r.append("DUP:");
8772                        r.append(pg.info.name);
8773                    }
8774                }
8775            }
8776            if (r != null) {
8777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8778            }
8779
8780            N = pkg.permissions.size();
8781            r = null;
8782            for (i=0; i<N; i++) {
8783                PackageParser.Permission p = pkg.permissions.get(i);
8784
8785                // Assume by default that we did not install this permission into the system.
8786                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8787
8788                // Now that permission groups have a special meaning, we ignore permission
8789                // groups for legacy apps to prevent unexpected behavior. In particular,
8790                // permissions for one app being granted to someone just becase they happen
8791                // to be in a group defined by another app (before this had no implications).
8792                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8793                    p.group = mPermissionGroups.get(p.info.group);
8794                    // Warn for a permission in an unknown group.
8795                    if (p.info.group != null && p.group == null) {
8796                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8797                                + p.info.packageName + " in an unknown group " + p.info.group);
8798                    }
8799                }
8800
8801                ArrayMap<String, BasePermission> permissionMap =
8802                        p.tree ? mSettings.mPermissionTrees
8803                                : mSettings.mPermissions;
8804                BasePermission bp = permissionMap.get(p.info.name);
8805
8806                // Allow system apps to redefine non-system permissions
8807                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8808                    final boolean currentOwnerIsSystem = (bp.perm != null
8809                            && isSystemApp(bp.perm.owner));
8810                    if (isSystemApp(p.owner)) {
8811                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8812                            // It's a built-in permission and no owner, take ownership now
8813                            bp.packageSetting = pkgSetting;
8814                            bp.perm = p;
8815                            bp.uid = pkg.applicationInfo.uid;
8816                            bp.sourcePackage = p.info.packageName;
8817                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8818                        } else if (!currentOwnerIsSystem) {
8819                            String msg = "New decl " + p.owner + " of permission  "
8820                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8821                            reportSettingsProblem(Log.WARN, msg);
8822                            bp = null;
8823                        }
8824                    }
8825                }
8826
8827                if (bp == null) {
8828                    bp = new BasePermission(p.info.name, p.info.packageName,
8829                            BasePermission.TYPE_NORMAL);
8830                    permissionMap.put(p.info.name, bp);
8831                }
8832
8833                if (bp.perm == null) {
8834                    if (bp.sourcePackage == null
8835                            || bp.sourcePackage.equals(p.info.packageName)) {
8836                        BasePermission tree = findPermissionTreeLP(p.info.name);
8837                        if (tree == null
8838                                || tree.sourcePackage.equals(p.info.packageName)) {
8839                            bp.packageSetting = pkgSetting;
8840                            bp.perm = p;
8841                            bp.uid = pkg.applicationInfo.uid;
8842                            bp.sourcePackage = p.info.packageName;
8843                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8844                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8845                                if (r == null) {
8846                                    r = new StringBuilder(256);
8847                                } else {
8848                                    r.append(' ');
8849                                }
8850                                r.append(p.info.name);
8851                            }
8852                        } else {
8853                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8854                                    + p.info.packageName + " ignored: base tree "
8855                                    + tree.name + " is from package "
8856                                    + tree.sourcePackage);
8857                        }
8858                    } else {
8859                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8860                                + p.info.packageName + " ignored: original from "
8861                                + bp.sourcePackage);
8862                    }
8863                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8864                    if (r == null) {
8865                        r = new StringBuilder(256);
8866                    } else {
8867                        r.append(' ');
8868                    }
8869                    r.append("DUP:");
8870                    r.append(p.info.name);
8871                }
8872                if (bp.perm == p) {
8873                    bp.protectionLevel = p.info.protectionLevel;
8874                }
8875            }
8876
8877            if (r != null) {
8878                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8879            }
8880
8881            N = pkg.instrumentation.size();
8882            r = null;
8883            for (i=0; i<N; i++) {
8884                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8885                a.info.packageName = pkg.applicationInfo.packageName;
8886                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8887                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8888                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8889                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8890                a.info.dataDir = pkg.applicationInfo.dataDir;
8891                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8892                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8893
8894                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8895                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8896                mInstrumentation.put(a.getComponentName(), a);
8897                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8898                    if (r == null) {
8899                        r = new StringBuilder(256);
8900                    } else {
8901                        r.append(' ');
8902                    }
8903                    r.append(a.info.name);
8904                }
8905            }
8906            if (r != null) {
8907                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8908            }
8909
8910            if (pkg.protectedBroadcasts != null) {
8911                N = pkg.protectedBroadcasts.size();
8912                for (i=0; i<N; i++) {
8913                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8914                }
8915            }
8916
8917            pkgSetting.setTimeStamp(scanFileTime);
8918
8919            // Create idmap files for pairs of (packages, overlay packages).
8920            // Note: "android", ie framework-res.apk, is handled by native layers.
8921            if (pkg.mOverlayTarget != null) {
8922                // This is an overlay package.
8923                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8924                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8925                        mOverlays.put(pkg.mOverlayTarget,
8926                                new ArrayMap<String, PackageParser.Package>());
8927                    }
8928                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8929                    map.put(pkg.packageName, pkg);
8930                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8931                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8932                        createIdmapFailed = true;
8933                    }
8934                }
8935            } else if (mOverlays.containsKey(pkg.packageName) &&
8936                    !pkg.packageName.equals("android")) {
8937                // This is a regular package, with one or more known overlay packages.
8938                createIdmapsForPackageLI(pkg);
8939            }
8940        }
8941
8942        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8943
8944        if (createIdmapFailed) {
8945            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8946                    "scanPackageLI failed to createIdmap");
8947        }
8948        return pkg;
8949    }
8950
8951    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8952            PackageParser.Package update, UserHandle user) {
8953        if (existing.applicationInfo == null || update.applicationInfo == null) {
8954            // This isn't due to an app installation.
8955            return;
8956        }
8957
8958        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8959        final File newCodePath = new File(update.applicationInfo.getCodePath());
8960
8961        // The codePath hasn't changed, so there's nothing for us to do.
8962        if (Objects.equals(oldCodePath, newCodePath)) {
8963            return;
8964        }
8965
8966        File canonicalNewCodePath;
8967        try {
8968            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8969        } catch (IOException e) {
8970            Slog.w(TAG, "Failed to get canonical path.", e);
8971            return;
8972        }
8973
8974        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8975        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8976        // that the last component of the path (i.e, the name) doesn't need canonicalization
8977        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8978        // but may change in the future. Hopefully this function won't exist at that point.
8979        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8980                oldCodePath.getName());
8981
8982        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8983        // with "@".
8984        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8985        if (!oldMarkerPrefix.endsWith("@")) {
8986            oldMarkerPrefix += "@";
8987        }
8988        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8989        if (!newMarkerPrefix.endsWith("@")) {
8990            newMarkerPrefix += "@";
8991        }
8992
8993        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8994        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8995        for (String updatedPath : updatedPaths) {
8996            String updatedPathName = new File(updatedPath).getName();
8997            markerSuffixes.add(updatedPathName.replace('/', '@'));
8998        }
8999
9000        for (int userId : resolveUserIds(user.getIdentifier())) {
9001            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9002
9003            for (String markerSuffix : markerSuffixes) {
9004                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9005                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9006                if (oldForeignUseMark.exists()) {
9007                    try {
9008                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9009                                newForeignUseMark.getAbsolutePath());
9010                    } catch (ErrnoException e) {
9011                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9012                        oldForeignUseMark.delete();
9013                    }
9014                }
9015            }
9016        }
9017    }
9018
9019    /**
9020     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9021     * is derived purely on the basis of the contents of {@code scanFile} and
9022     * {@code cpuAbiOverride}.
9023     *
9024     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9025     */
9026    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9027                                 String cpuAbiOverride, boolean extractLibs)
9028            throws PackageManagerException {
9029        // TODO: We can probably be smarter about this stuff. For installed apps,
9030        // we can calculate this information at install time once and for all. For
9031        // system apps, we can probably assume that this information doesn't change
9032        // after the first boot scan. As things stand, we do lots of unnecessary work.
9033
9034        // Give ourselves some initial paths; we'll come back for another
9035        // pass once we've determined ABI below.
9036        setNativeLibraryPaths(pkg);
9037
9038        // We would never need to extract libs for forward-locked and external packages,
9039        // since the container service will do it for us. We shouldn't attempt to
9040        // extract libs from system app when it was not updated.
9041        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9042                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9043            extractLibs = false;
9044        }
9045
9046        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9047        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9048
9049        NativeLibraryHelper.Handle handle = null;
9050        try {
9051            handle = NativeLibraryHelper.Handle.create(pkg);
9052            // TODO(multiArch): This can be null for apps that didn't go through the
9053            // usual installation process. We can calculate it again, like we
9054            // do during install time.
9055            //
9056            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9057            // unnecessary.
9058            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9059
9060            // Null out the abis so that they can be recalculated.
9061            pkg.applicationInfo.primaryCpuAbi = null;
9062            pkg.applicationInfo.secondaryCpuAbi = null;
9063            if (isMultiArch(pkg.applicationInfo)) {
9064                // Warn if we've set an abiOverride for multi-lib packages..
9065                // By definition, we need to copy both 32 and 64 bit libraries for
9066                // such packages.
9067                if (pkg.cpuAbiOverride != null
9068                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9069                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9070                }
9071
9072                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9073                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9074                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9075                    if (extractLibs) {
9076                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9077                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9078                                useIsaSpecificSubdirs);
9079                    } else {
9080                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9081                    }
9082                }
9083
9084                maybeThrowExceptionForMultiArchCopy(
9085                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9086
9087                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9088                    if (extractLibs) {
9089                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9090                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9091                                useIsaSpecificSubdirs);
9092                    } else {
9093                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9094                    }
9095                }
9096
9097                maybeThrowExceptionForMultiArchCopy(
9098                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9099
9100                if (abi64 >= 0) {
9101                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9102                }
9103
9104                if (abi32 >= 0) {
9105                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9106                    if (abi64 >= 0) {
9107                        if (pkg.use32bitAbi) {
9108                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9109                            pkg.applicationInfo.primaryCpuAbi = abi;
9110                        } else {
9111                            pkg.applicationInfo.secondaryCpuAbi = abi;
9112                        }
9113                    } else {
9114                        pkg.applicationInfo.primaryCpuAbi = abi;
9115                    }
9116                }
9117
9118            } else {
9119                String[] abiList = (cpuAbiOverride != null) ?
9120                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9121
9122                // Enable gross and lame hacks for apps that are built with old
9123                // SDK tools. We must scan their APKs for renderscript bitcode and
9124                // not launch them if it's present. Don't bother checking on devices
9125                // that don't have 64 bit support.
9126                boolean needsRenderScriptOverride = false;
9127                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9128                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9129                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9130                    needsRenderScriptOverride = true;
9131                }
9132
9133                final int copyRet;
9134                if (extractLibs) {
9135                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9136                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9137                } else {
9138                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9139                }
9140
9141                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9142                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9143                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9144                }
9145
9146                if (copyRet >= 0) {
9147                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9148                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9149                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9150                } else if (needsRenderScriptOverride) {
9151                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9152                }
9153            }
9154        } catch (IOException ioe) {
9155            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9156        } finally {
9157            IoUtils.closeQuietly(handle);
9158        }
9159
9160        // Now that we've calculated the ABIs and determined if it's an internal app,
9161        // we will go ahead and populate the nativeLibraryPath.
9162        setNativeLibraryPaths(pkg);
9163    }
9164
9165    /**
9166     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9167     * i.e, so that all packages can be run inside a single process if required.
9168     *
9169     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9170     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9171     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9172     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9173     * updating a package that belongs to a shared user.
9174     *
9175     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9176     * adds unnecessary complexity.
9177     */
9178    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9179            PackageParser.Package scannedPackage, boolean bootComplete) {
9180        String requiredInstructionSet = null;
9181        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9182            requiredInstructionSet = VMRuntime.getInstructionSet(
9183                     scannedPackage.applicationInfo.primaryCpuAbi);
9184        }
9185
9186        PackageSetting requirer = null;
9187        for (PackageSetting ps : packagesForUser) {
9188            // If packagesForUser contains scannedPackage, we skip it. This will happen
9189            // when scannedPackage is an update of an existing package. Without this check,
9190            // we will never be able to change the ABI of any package belonging to a shared
9191            // user, even if it's compatible with other packages.
9192            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9193                if (ps.primaryCpuAbiString == null) {
9194                    continue;
9195                }
9196
9197                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9198                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9199                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9200                    // this but there's not much we can do.
9201                    String errorMessage = "Instruction set mismatch, "
9202                            + ((requirer == null) ? "[caller]" : requirer)
9203                            + " requires " + requiredInstructionSet + " whereas " + ps
9204                            + " requires " + instructionSet;
9205                    Slog.w(TAG, errorMessage);
9206                }
9207
9208                if (requiredInstructionSet == null) {
9209                    requiredInstructionSet = instructionSet;
9210                    requirer = ps;
9211                }
9212            }
9213        }
9214
9215        if (requiredInstructionSet != null) {
9216            String adjustedAbi;
9217            if (requirer != null) {
9218                // requirer != null implies that either scannedPackage was null or that scannedPackage
9219                // did not require an ABI, in which case we have to adjust scannedPackage to match
9220                // the ABI of the set (which is the same as requirer's ABI)
9221                adjustedAbi = requirer.primaryCpuAbiString;
9222                if (scannedPackage != null) {
9223                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9224                }
9225            } else {
9226                // requirer == null implies that we're updating all ABIs in the set to
9227                // match scannedPackage.
9228                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9229            }
9230
9231            for (PackageSetting ps : packagesForUser) {
9232                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9233                    if (ps.primaryCpuAbiString != null) {
9234                        continue;
9235                    }
9236
9237                    ps.primaryCpuAbiString = adjustedAbi;
9238                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9239                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9240                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9241                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9242                                + " (requirer="
9243                                + (requirer == null ? "null" : requirer.pkg.packageName)
9244                                + ", scannedPackage="
9245                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9246                                + ")");
9247                        try {
9248                            mInstaller.rmdex(ps.codePathString,
9249                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9250                        } catch (InstallerException ignored) {
9251                        }
9252                    }
9253                }
9254            }
9255        }
9256    }
9257
9258    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9259        synchronized (mPackages) {
9260            mResolverReplaced = true;
9261            // Set up information for custom user intent resolution activity.
9262            mResolveActivity.applicationInfo = pkg.applicationInfo;
9263            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9264            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9265            mResolveActivity.processName = pkg.applicationInfo.packageName;
9266            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9267            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9268                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9269            mResolveActivity.theme = 0;
9270            mResolveActivity.exported = true;
9271            mResolveActivity.enabled = true;
9272            mResolveInfo.activityInfo = mResolveActivity;
9273            mResolveInfo.priority = 0;
9274            mResolveInfo.preferredOrder = 0;
9275            mResolveInfo.match = 0;
9276            mResolveComponentName = mCustomResolverComponentName;
9277            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9278                    mResolveComponentName);
9279        }
9280    }
9281
9282    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9283        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9284
9285        // Set up information for ephemeral installer activity
9286        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9287        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9288        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9289        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9290        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9291        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9292                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9293        mEphemeralInstallerActivity.theme = 0;
9294        mEphemeralInstallerActivity.exported = true;
9295        mEphemeralInstallerActivity.enabled = true;
9296        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9297        mEphemeralInstallerInfo.priority = 0;
9298        mEphemeralInstallerInfo.preferredOrder = 1;
9299        mEphemeralInstallerInfo.isDefault = true;
9300        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9301                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9302
9303        if (DEBUG_EPHEMERAL) {
9304            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9305        }
9306    }
9307
9308    private static String calculateBundledApkRoot(final String codePathString) {
9309        final File codePath = new File(codePathString);
9310        final File codeRoot;
9311        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9312            codeRoot = Environment.getRootDirectory();
9313        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9314            codeRoot = Environment.getOemDirectory();
9315        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9316            codeRoot = Environment.getVendorDirectory();
9317        } else {
9318            // Unrecognized code path; take its top real segment as the apk root:
9319            // e.g. /something/app/blah.apk => /something
9320            try {
9321                File f = codePath.getCanonicalFile();
9322                File parent = f.getParentFile();    // non-null because codePath is a file
9323                File tmp;
9324                while ((tmp = parent.getParentFile()) != null) {
9325                    f = parent;
9326                    parent = tmp;
9327                }
9328                codeRoot = f;
9329                Slog.w(TAG, "Unrecognized code path "
9330                        + codePath + " - using " + codeRoot);
9331            } catch (IOException e) {
9332                // Can't canonicalize the code path -- shenanigans?
9333                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9334                return Environment.getRootDirectory().getPath();
9335            }
9336        }
9337        return codeRoot.getPath();
9338    }
9339
9340    /**
9341     * Derive and set the location of native libraries for the given package,
9342     * which varies depending on where and how the package was installed.
9343     */
9344    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9345        final ApplicationInfo info = pkg.applicationInfo;
9346        final String codePath = pkg.codePath;
9347        final File codeFile = new File(codePath);
9348        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9349        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9350
9351        info.nativeLibraryRootDir = null;
9352        info.nativeLibraryRootRequiresIsa = false;
9353        info.nativeLibraryDir = null;
9354        info.secondaryNativeLibraryDir = null;
9355
9356        if (isApkFile(codeFile)) {
9357            // Monolithic install
9358            if (bundledApp) {
9359                // If "/system/lib64/apkname" exists, assume that is the per-package
9360                // native library directory to use; otherwise use "/system/lib/apkname".
9361                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9362                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9363                        getPrimaryInstructionSet(info));
9364
9365                // This is a bundled system app so choose the path based on the ABI.
9366                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9367                // is just the default path.
9368                final String apkName = deriveCodePathName(codePath);
9369                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9370                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9371                        apkName).getAbsolutePath();
9372
9373                if (info.secondaryCpuAbi != null) {
9374                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9375                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9376                            secondaryLibDir, apkName).getAbsolutePath();
9377                }
9378            } else if (asecApp) {
9379                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9380                        .getAbsolutePath();
9381            } else {
9382                final String apkName = deriveCodePathName(codePath);
9383                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9384                        .getAbsolutePath();
9385            }
9386
9387            info.nativeLibraryRootRequiresIsa = false;
9388            info.nativeLibraryDir = info.nativeLibraryRootDir;
9389        } else {
9390            // Cluster install
9391            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9392            info.nativeLibraryRootRequiresIsa = true;
9393
9394            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9395                    getPrimaryInstructionSet(info)).getAbsolutePath();
9396
9397            if (info.secondaryCpuAbi != null) {
9398                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9399                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9400            }
9401        }
9402    }
9403
9404    /**
9405     * Calculate the abis and roots for a bundled app. These can uniquely
9406     * be determined from the contents of the system partition, i.e whether
9407     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9408     * of this information, and instead assume that the system was built
9409     * sensibly.
9410     */
9411    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9412                                           PackageSetting pkgSetting) {
9413        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9414
9415        // If "/system/lib64/apkname" exists, assume that is the per-package
9416        // native library directory to use; otherwise use "/system/lib/apkname".
9417        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9418        setBundledAppAbi(pkg, apkRoot, apkName);
9419        // pkgSetting might be null during rescan following uninstall of updates
9420        // to a bundled app, so accommodate that possibility.  The settings in
9421        // that case will be established later from the parsed package.
9422        //
9423        // If the settings aren't null, sync them up with what we've just derived.
9424        // note that apkRoot isn't stored in the package settings.
9425        if (pkgSetting != null) {
9426            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9427            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9428        }
9429    }
9430
9431    /**
9432     * Deduces the ABI of a bundled app and sets the relevant fields on the
9433     * parsed pkg object.
9434     *
9435     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9436     *        under which system libraries are installed.
9437     * @param apkName the name of the installed package.
9438     */
9439    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9440        final File codeFile = new File(pkg.codePath);
9441
9442        final boolean has64BitLibs;
9443        final boolean has32BitLibs;
9444        if (isApkFile(codeFile)) {
9445            // Monolithic install
9446            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9447            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9448        } else {
9449            // Cluster install
9450            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9451            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9452                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9453                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9454                has64BitLibs = (new File(rootDir, isa)).exists();
9455            } else {
9456                has64BitLibs = false;
9457            }
9458            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9459                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9460                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9461                has32BitLibs = (new File(rootDir, isa)).exists();
9462            } else {
9463                has32BitLibs = false;
9464            }
9465        }
9466
9467        if (has64BitLibs && !has32BitLibs) {
9468            // The package has 64 bit libs, but not 32 bit libs. Its primary
9469            // ABI should be 64 bit. We can safely assume here that the bundled
9470            // native libraries correspond to the most preferred ABI in the list.
9471
9472            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9473            pkg.applicationInfo.secondaryCpuAbi = null;
9474        } else if (has32BitLibs && !has64BitLibs) {
9475            // The package has 32 bit libs but not 64 bit libs. Its primary
9476            // ABI should be 32 bit.
9477
9478            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9479            pkg.applicationInfo.secondaryCpuAbi = null;
9480        } else if (has32BitLibs && has64BitLibs) {
9481            // The application has both 64 and 32 bit bundled libraries. We check
9482            // here that the app declares multiArch support, and warn if it doesn't.
9483            //
9484            // We will be lenient here and record both ABIs. The primary will be the
9485            // ABI that's higher on the list, i.e, a device that's configured to prefer
9486            // 64 bit apps will see a 64 bit primary ABI,
9487
9488            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9489                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9490            }
9491
9492            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9493                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9494                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9495            } else {
9496                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9497                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9498            }
9499        } else {
9500            pkg.applicationInfo.primaryCpuAbi = null;
9501            pkg.applicationInfo.secondaryCpuAbi = null;
9502        }
9503    }
9504
9505    private void killApplication(String pkgName, int appId, String reason) {
9506        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9507    }
9508
9509    private void killApplication(String pkgName, int appId, int userId, String reason) {
9510        // Request the ActivityManager to kill the process(only for existing packages)
9511        // so that we do not end up in a confused state while the user is still using the older
9512        // version of the application while the new one gets installed.
9513        final long token = Binder.clearCallingIdentity();
9514        try {
9515            IActivityManager am = ActivityManagerNative.getDefault();
9516            if (am != null) {
9517                try {
9518                    am.killApplication(pkgName, appId, userId, reason);
9519                } catch (RemoteException e) {
9520                }
9521            }
9522        } finally {
9523            Binder.restoreCallingIdentity(token);
9524        }
9525    }
9526
9527    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9528        // Remove the parent package setting
9529        PackageSetting ps = (PackageSetting) pkg.mExtras;
9530        if (ps != null) {
9531            removePackageLI(ps, chatty);
9532        }
9533        // Remove the child package setting
9534        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9535        for (int i = 0; i < childCount; i++) {
9536            PackageParser.Package childPkg = pkg.childPackages.get(i);
9537            ps = (PackageSetting) childPkg.mExtras;
9538            if (ps != null) {
9539                removePackageLI(ps, chatty);
9540            }
9541        }
9542    }
9543
9544    void removePackageLI(PackageSetting ps, boolean chatty) {
9545        if (DEBUG_INSTALL) {
9546            if (chatty)
9547                Log.d(TAG, "Removing package " + ps.name);
9548        }
9549
9550        // writer
9551        synchronized (mPackages) {
9552            mPackages.remove(ps.name);
9553            final PackageParser.Package pkg = ps.pkg;
9554            if (pkg != null) {
9555                cleanPackageDataStructuresLILPw(pkg, chatty);
9556            }
9557        }
9558    }
9559
9560    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9561        if (DEBUG_INSTALL) {
9562            if (chatty)
9563                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9564        }
9565
9566        // writer
9567        synchronized (mPackages) {
9568            // Remove the parent package
9569            mPackages.remove(pkg.applicationInfo.packageName);
9570            cleanPackageDataStructuresLILPw(pkg, chatty);
9571
9572            // Remove the child packages
9573            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9574            for (int i = 0; i < childCount; i++) {
9575                PackageParser.Package childPkg = pkg.childPackages.get(i);
9576                mPackages.remove(childPkg.applicationInfo.packageName);
9577                cleanPackageDataStructuresLILPw(childPkg, chatty);
9578            }
9579        }
9580    }
9581
9582    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9583        int N = pkg.providers.size();
9584        StringBuilder r = null;
9585        int i;
9586        for (i=0; i<N; i++) {
9587            PackageParser.Provider p = pkg.providers.get(i);
9588            mProviders.removeProvider(p);
9589            if (p.info.authority == null) {
9590
9591                /* There was another ContentProvider with this authority when
9592                 * this app was installed so this authority is null,
9593                 * Ignore it as we don't have to unregister the provider.
9594                 */
9595                continue;
9596            }
9597            String names[] = p.info.authority.split(";");
9598            for (int j = 0; j < names.length; j++) {
9599                if (mProvidersByAuthority.get(names[j]) == p) {
9600                    mProvidersByAuthority.remove(names[j]);
9601                    if (DEBUG_REMOVE) {
9602                        if (chatty)
9603                            Log.d(TAG, "Unregistered content provider: " + names[j]
9604                                    + ", className = " + p.info.name + ", isSyncable = "
9605                                    + p.info.isSyncable);
9606                    }
9607                }
9608            }
9609            if (DEBUG_REMOVE && chatty) {
9610                if (r == null) {
9611                    r = new StringBuilder(256);
9612                } else {
9613                    r.append(' ');
9614                }
9615                r.append(p.info.name);
9616            }
9617        }
9618        if (r != null) {
9619            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9620        }
9621
9622        N = pkg.services.size();
9623        r = null;
9624        for (i=0; i<N; i++) {
9625            PackageParser.Service s = pkg.services.get(i);
9626            mServices.removeService(s);
9627            if (chatty) {
9628                if (r == null) {
9629                    r = new StringBuilder(256);
9630                } else {
9631                    r.append(' ');
9632                }
9633                r.append(s.info.name);
9634            }
9635        }
9636        if (r != null) {
9637            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9638        }
9639
9640        N = pkg.receivers.size();
9641        r = null;
9642        for (i=0; i<N; i++) {
9643            PackageParser.Activity a = pkg.receivers.get(i);
9644            mReceivers.removeActivity(a, "receiver");
9645            if (DEBUG_REMOVE && chatty) {
9646                if (r == null) {
9647                    r = new StringBuilder(256);
9648                } else {
9649                    r.append(' ');
9650                }
9651                r.append(a.info.name);
9652            }
9653        }
9654        if (r != null) {
9655            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9656        }
9657
9658        N = pkg.activities.size();
9659        r = null;
9660        for (i=0; i<N; i++) {
9661            PackageParser.Activity a = pkg.activities.get(i);
9662            mActivities.removeActivity(a, "activity");
9663            if (DEBUG_REMOVE && chatty) {
9664                if (r == null) {
9665                    r = new StringBuilder(256);
9666                } else {
9667                    r.append(' ');
9668                }
9669                r.append(a.info.name);
9670            }
9671        }
9672        if (r != null) {
9673            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9674        }
9675
9676        N = pkg.permissions.size();
9677        r = null;
9678        for (i=0; i<N; i++) {
9679            PackageParser.Permission p = pkg.permissions.get(i);
9680            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9681            if (bp == null) {
9682                bp = mSettings.mPermissionTrees.get(p.info.name);
9683            }
9684            if (bp != null && bp.perm == p) {
9685                bp.perm = null;
9686                if (DEBUG_REMOVE && chatty) {
9687                    if (r == null) {
9688                        r = new StringBuilder(256);
9689                    } else {
9690                        r.append(' ');
9691                    }
9692                    r.append(p.info.name);
9693                }
9694            }
9695            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9696                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9697                if (appOpPkgs != null) {
9698                    appOpPkgs.remove(pkg.packageName);
9699                }
9700            }
9701        }
9702        if (r != null) {
9703            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9704        }
9705
9706        N = pkg.requestedPermissions.size();
9707        r = null;
9708        for (i=0; i<N; i++) {
9709            String perm = pkg.requestedPermissions.get(i);
9710            BasePermission bp = mSettings.mPermissions.get(perm);
9711            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9712                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9713                if (appOpPkgs != null) {
9714                    appOpPkgs.remove(pkg.packageName);
9715                    if (appOpPkgs.isEmpty()) {
9716                        mAppOpPermissionPackages.remove(perm);
9717                    }
9718                }
9719            }
9720        }
9721        if (r != null) {
9722            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9723        }
9724
9725        N = pkg.instrumentation.size();
9726        r = null;
9727        for (i=0; i<N; i++) {
9728            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9729            mInstrumentation.remove(a.getComponentName());
9730            if (DEBUG_REMOVE && chatty) {
9731                if (r == null) {
9732                    r = new StringBuilder(256);
9733                } else {
9734                    r.append(' ');
9735                }
9736                r.append(a.info.name);
9737            }
9738        }
9739        if (r != null) {
9740            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9741        }
9742
9743        r = null;
9744        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9745            // Only system apps can hold shared libraries.
9746            if (pkg.libraryNames != null) {
9747                for (i=0; i<pkg.libraryNames.size(); i++) {
9748                    String name = pkg.libraryNames.get(i);
9749                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9750                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9751                        mSharedLibraries.remove(name);
9752                        if (DEBUG_REMOVE && chatty) {
9753                            if (r == null) {
9754                                r = new StringBuilder(256);
9755                            } else {
9756                                r.append(' ');
9757                            }
9758                            r.append(name);
9759                        }
9760                    }
9761                }
9762            }
9763        }
9764        if (r != null) {
9765            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9766        }
9767    }
9768
9769    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9770        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9771            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9772                return true;
9773            }
9774        }
9775        return false;
9776    }
9777
9778    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9779    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9780    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9781
9782    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9783        // Update the parent permissions
9784        updatePermissionsLPw(pkg.packageName, pkg, flags);
9785        // Update the child permissions
9786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9787        for (int i = 0; i < childCount; i++) {
9788            PackageParser.Package childPkg = pkg.childPackages.get(i);
9789            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9790        }
9791    }
9792
9793    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9794            int flags) {
9795        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9796        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9797    }
9798
9799    private void updatePermissionsLPw(String changingPkg,
9800            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9801        // Make sure there are no dangling permission trees.
9802        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9803        while (it.hasNext()) {
9804            final BasePermission bp = it.next();
9805            if (bp.packageSetting == null) {
9806                // We may not yet have parsed the package, so just see if
9807                // we still know about its settings.
9808                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9809            }
9810            if (bp.packageSetting == null) {
9811                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9812                        + " from package " + bp.sourcePackage);
9813                it.remove();
9814            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9815                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9816                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9817                            + " from package " + bp.sourcePackage);
9818                    flags |= UPDATE_PERMISSIONS_ALL;
9819                    it.remove();
9820                }
9821            }
9822        }
9823
9824        // Make sure all dynamic permissions have been assigned to a package,
9825        // and make sure there are no dangling permissions.
9826        it = mSettings.mPermissions.values().iterator();
9827        while (it.hasNext()) {
9828            final BasePermission bp = it.next();
9829            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9830                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9831                        + bp.name + " pkg=" + bp.sourcePackage
9832                        + " info=" + bp.pendingInfo);
9833                if (bp.packageSetting == null && bp.pendingInfo != null) {
9834                    final BasePermission tree = findPermissionTreeLP(bp.name);
9835                    if (tree != null && tree.perm != null) {
9836                        bp.packageSetting = tree.packageSetting;
9837                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9838                                new PermissionInfo(bp.pendingInfo));
9839                        bp.perm.info.packageName = tree.perm.info.packageName;
9840                        bp.perm.info.name = bp.name;
9841                        bp.uid = tree.uid;
9842                    }
9843                }
9844            }
9845            if (bp.packageSetting == null) {
9846                // We may not yet have parsed the package, so just see if
9847                // we still know about its settings.
9848                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9849            }
9850            if (bp.packageSetting == null) {
9851                Slog.w(TAG, "Removing dangling permission: " + bp.name
9852                        + " from package " + bp.sourcePackage);
9853                it.remove();
9854            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9855                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9856                    Slog.i(TAG, "Removing old permission: " + bp.name
9857                            + " from package " + bp.sourcePackage);
9858                    flags |= UPDATE_PERMISSIONS_ALL;
9859                    it.remove();
9860                }
9861            }
9862        }
9863
9864        // Now update the permissions for all packages, in particular
9865        // replace the granted permissions of the system packages.
9866        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9867            for (PackageParser.Package pkg : mPackages.values()) {
9868                if (pkg != pkgInfo) {
9869                    // Only replace for packages on requested volume
9870                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9871                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9872                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9873                    grantPermissionsLPw(pkg, replace, changingPkg);
9874                }
9875            }
9876        }
9877
9878        if (pkgInfo != null) {
9879            // Only replace for packages on requested volume
9880            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9881            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9882                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9883            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9884        }
9885    }
9886
9887    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9888            String packageOfInterest) {
9889        // IMPORTANT: There are two types of permissions: install and runtime.
9890        // Install time permissions are granted when the app is installed to
9891        // all device users and users added in the future. Runtime permissions
9892        // are granted at runtime explicitly to specific users. Normal and signature
9893        // protected permissions are install time permissions. Dangerous permissions
9894        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9895        // otherwise they are runtime permissions. This function does not manage
9896        // runtime permissions except for the case an app targeting Lollipop MR1
9897        // being upgraded to target a newer SDK, in which case dangerous permissions
9898        // are transformed from install time to runtime ones.
9899
9900        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9901        if (ps == null) {
9902            return;
9903        }
9904
9905        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9906
9907        PermissionsState permissionsState = ps.getPermissionsState();
9908        PermissionsState origPermissions = permissionsState;
9909
9910        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9911
9912        boolean runtimePermissionsRevoked = false;
9913        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9914
9915        boolean changedInstallPermission = false;
9916
9917        if (replace) {
9918            ps.installPermissionsFixed = false;
9919            if (!ps.isSharedUser()) {
9920                origPermissions = new PermissionsState(permissionsState);
9921                permissionsState.reset();
9922            } else {
9923                // We need to know only about runtime permission changes since the
9924                // calling code always writes the install permissions state but
9925                // the runtime ones are written only if changed. The only cases of
9926                // changed runtime permissions here are promotion of an install to
9927                // runtime and revocation of a runtime from a shared user.
9928                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9929                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9930                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9931                    runtimePermissionsRevoked = true;
9932                }
9933            }
9934        }
9935
9936        permissionsState.setGlobalGids(mGlobalGids);
9937
9938        final int N = pkg.requestedPermissions.size();
9939        for (int i=0; i<N; i++) {
9940            final String name = pkg.requestedPermissions.get(i);
9941            final BasePermission bp = mSettings.mPermissions.get(name);
9942
9943            if (DEBUG_INSTALL) {
9944                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9945            }
9946
9947            if (bp == null || bp.packageSetting == null) {
9948                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9949                    Slog.w(TAG, "Unknown permission " + name
9950                            + " in package " + pkg.packageName);
9951                }
9952                continue;
9953            }
9954
9955            final String perm = bp.name;
9956            boolean allowedSig = false;
9957            int grant = GRANT_DENIED;
9958
9959            // Keep track of app op permissions.
9960            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9961                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9962                if (pkgs == null) {
9963                    pkgs = new ArraySet<>();
9964                    mAppOpPermissionPackages.put(bp.name, pkgs);
9965                }
9966                pkgs.add(pkg.packageName);
9967            }
9968
9969            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9970            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9971                    >= Build.VERSION_CODES.M;
9972            switch (level) {
9973                case PermissionInfo.PROTECTION_NORMAL: {
9974                    // For all apps normal permissions are install time ones.
9975                    grant = GRANT_INSTALL;
9976                } break;
9977
9978                case PermissionInfo.PROTECTION_DANGEROUS: {
9979                    // If a permission review is required for legacy apps we represent
9980                    // their permissions as always granted runtime ones since we need
9981                    // to keep the review required permission flag per user while an
9982                    // install permission's state is shared across all users.
9983                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9984                        // For legacy apps dangerous permissions are install time ones.
9985                        grant = GRANT_INSTALL;
9986                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9987                        // For legacy apps that became modern, install becomes runtime.
9988                        grant = GRANT_UPGRADE;
9989                    } else if (mPromoteSystemApps
9990                            && isSystemApp(ps)
9991                            && mExistingSystemPackages.contains(ps.name)) {
9992                        // For legacy system apps, install becomes runtime.
9993                        // We cannot check hasInstallPermission() for system apps since those
9994                        // permissions were granted implicitly and not persisted pre-M.
9995                        grant = GRANT_UPGRADE;
9996                    } else {
9997                        // For modern apps keep runtime permissions unchanged.
9998                        grant = GRANT_RUNTIME;
9999                    }
10000                } break;
10001
10002                case PermissionInfo.PROTECTION_SIGNATURE: {
10003                    // For all apps signature permissions are install time ones.
10004                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10005                    if (allowedSig) {
10006                        grant = GRANT_INSTALL;
10007                    }
10008                } break;
10009            }
10010
10011            if (DEBUG_INSTALL) {
10012                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10013            }
10014
10015            if (grant != GRANT_DENIED) {
10016                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10017                    // If this is an existing, non-system package, then
10018                    // we can't add any new permissions to it.
10019                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10020                        // Except...  if this is a permission that was added
10021                        // to the platform (note: need to only do this when
10022                        // updating the platform).
10023                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10024                            grant = GRANT_DENIED;
10025                        }
10026                    }
10027                }
10028
10029                switch (grant) {
10030                    case GRANT_INSTALL: {
10031                        // Revoke this as runtime permission to handle the case of
10032                        // a runtime permission being downgraded to an install one.
10033                        // Also in permission review mode we keep dangerous permissions
10034                        // for legacy apps
10035                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10036                            if (origPermissions.getRuntimePermissionState(
10037                                    bp.name, userId) != null) {
10038                                // Revoke the runtime permission and clear the flags.
10039                                origPermissions.revokeRuntimePermission(bp, userId);
10040                                origPermissions.updatePermissionFlags(bp, userId,
10041                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10042                                // If we revoked a permission permission, we have to write.
10043                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10044                                        changedRuntimePermissionUserIds, userId);
10045                            }
10046                        }
10047                        // Grant an install permission.
10048                        if (permissionsState.grantInstallPermission(bp) !=
10049                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10050                            changedInstallPermission = true;
10051                        }
10052                    } break;
10053
10054                    case GRANT_RUNTIME: {
10055                        // Grant previously granted runtime permissions.
10056                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10057                            PermissionState permissionState = origPermissions
10058                                    .getRuntimePermissionState(bp.name, userId);
10059                            int flags = permissionState != null
10060                                    ? permissionState.getFlags() : 0;
10061                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10062                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10063                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10064                                    // If we cannot put the permission as it was, we have to write.
10065                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10066                                            changedRuntimePermissionUserIds, userId);
10067                                }
10068                                // If the app supports runtime permissions no need for a review.
10069                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10070                                        && appSupportsRuntimePermissions
10071                                        && (flags & PackageManager
10072                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10073                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10074                                    // Since we changed the flags, we have to write.
10075                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10076                                            changedRuntimePermissionUserIds, userId);
10077                                }
10078                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10079                                    && !appSupportsRuntimePermissions) {
10080                                // For legacy apps that need a permission review, every new
10081                                // runtime permission is granted but it is pending a review.
10082                                // We also need to review only platform defined runtime
10083                                // permissions as these are the only ones the platform knows
10084                                // how to disable the API to simulate revocation as legacy
10085                                // apps don't expect to run with revoked permissions.
10086                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10087                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10088                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10089                                        // We changed the flags, hence have to write.
10090                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10091                                                changedRuntimePermissionUserIds, userId);
10092                                    }
10093                                }
10094                                if (permissionsState.grantRuntimePermission(bp, userId)
10095                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10096                                    // We changed the permission, hence have to write.
10097                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10098                                            changedRuntimePermissionUserIds, userId);
10099                                }
10100                            }
10101                            // Propagate the permission flags.
10102                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10103                        }
10104                    } break;
10105
10106                    case GRANT_UPGRADE: {
10107                        // Grant runtime permissions for a previously held install permission.
10108                        PermissionState permissionState = origPermissions
10109                                .getInstallPermissionState(bp.name);
10110                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10111
10112                        if (origPermissions.revokeInstallPermission(bp)
10113                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10114                            // We will be transferring the permission flags, so clear them.
10115                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10116                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10117                            changedInstallPermission = true;
10118                        }
10119
10120                        // If the permission is not to be promoted to runtime we ignore it and
10121                        // also its other flags as they are not applicable to install permissions.
10122                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10123                            for (int userId : currentUserIds) {
10124                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10125                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10126                                    // Transfer the permission flags.
10127                                    permissionsState.updatePermissionFlags(bp, userId,
10128                                            flags, flags);
10129                                    // If we granted the permission, we have to write.
10130                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10131                                            changedRuntimePermissionUserIds, userId);
10132                                }
10133                            }
10134                        }
10135                    } break;
10136
10137                    default: {
10138                        if (packageOfInterest == null
10139                                || packageOfInterest.equals(pkg.packageName)) {
10140                            Slog.w(TAG, "Not granting permission " + perm
10141                                    + " to package " + pkg.packageName
10142                                    + " because it was previously installed without");
10143                        }
10144                    } break;
10145                }
10146            } else {
10147                if (permissionsState.revokeInstallPermission(bp) !=
10148                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10149                    // Also drop the permission flags.
10150                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10151                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10152                    changedInstallPermission = true;
10153                    Slog.i(TAG, "Un-granting permission " + perm
10154                            + " from package " + pkg.packageName
10155                            + " (protectionLevel=" + bp.protectionLevel
10156                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10157                            + ")");
10158                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10159                    // Don't print warning for app op permissions, since it is fine for them
10160                    // not to be granted, there is a UI for the user to decide.
10161                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10162                        Slog.w(TAG, "Not granting permission " + perm
10163                                + " to package " + pkg.packageName
10164                                + " (protectionLevel=" + bp.protectionLevel
10165                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10166                                + ")");
10167                    }
10168                }
10169            }
10170        }
10171
10172        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10173                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10174            // This is the first that we have heard about this package, so the
10175            // permissions we have now selected are fixed until explicitly
10176            // changed.
10177            ps.installPermissionsFixed = true;
10178        }
10179
10180        // Persist the runtime permissions state for users with changes. If permissions
10181        // were revoked because no app in the shared user declares them we have to
10182        // write synchronously to avoid losing runtime permissions state.
10183        for (int userId : changedRuntimePermissionUserIds) {
10184            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10185        }
10186
10187        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10188    }
10189
10190    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10191        boolean allowed = false;
10192        final int NP = PackageParser.NEW_PERMISSIONS.length;
10193        for (int ip=0; ip<NP; ip++) {
10194            final PackageParser.NewPermissionInfo npi
10195                    = PackageParser.NEW_PERMISSIONS[ip];
10196            if (npi.name.equals(perm)
10197                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10198                allowed = true;
10199                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10200                        + pkg.packageName);
10201                break;
10202            }
10203        }
10204        return allowed;
10205    }
10206
10207    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10208            BasePermission bp, PermissionsState origPermissions) {
10209        boolean allowed;
10210        allowed = (compareSignatures(
10211                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10212                        == PackageManager.SIGNATURE_MATCH)
10213                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10214                        == PackageManager.SIGNATURE_MATCH);
10215        if (!allowed && (bp.protectionLevel
10216                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10217            if (isSystemApp(pkg)) {
10218                // For updated system applications, a system permission
10219                // is granted only if it had been defined by the original application.
10220                if (pkg.isUpdatedSystemApp()) {
10221                    final PackageSetting sysPs = mSettings
10222                            .getDisabledSystemPkgLPr(pkg.packageName);
10223                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10224                        // If the original was granted this permission, we take
10225                        // that grant decision as read and propagate it to the
10226                        // update.
10227                        if (sysPs.isPrivileged()) {
10228                            allowed = true;
10229                        }
10230                    } else {
10231                        // The system apk may have been updated with an older
10232                        // version of the one on the data partition, but which
10233                        // granted a new system permission that it didn't have
10234                        // before.  In this case we do want to allow the app to
10235                        // now get the new permission if the ancestral apk is
10236                        // privileged to get it.
10237                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10238                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10239                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10240                                    allowed = true;
10241                                    break;
10242                                }
10243                            }
10244                        }
10245                        // Also if a privileged parent package on the system image or any of
10246                        // its children requested a privileged permission, the updated child
10247                        // packages can also get the permission.
10248                        if (pkg.parentPackage != null) {
10249                            final PackageSetting disabledSysParentPs = mSettings
10250                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10251                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10252                                    && disabledSysParentPs.isPrivileged()) {
10253                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10254                                    allowed = true;
10255                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10256                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10257                                    for (int i = 0; i < count; i++) {
10258                                        PackageParser.Package disabledSysChildPkg =
10259                                                disabledSysParentPs.pkg.childPackages.get(i);
10260                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10261                                                perm)) {
10262                                            allowed = true;
10263                                            break;
10264                                        }
10265                                    }
10266                                }
10267                            }
10268                        }
10269                    }
10270                } else {
10271                    allowed = isPrivilegedApp(pkg);
10272                }
10273            }
10274        }
10275        if (!allowed) {
10276            if (!allowed && (bp.protectionLevel
10277                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10278                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10279                // If this was a previously normal/dangerous permission that got moved
10280                // to a system permission as part of the runtime permission redesign, then
10281                // we still want to blindly grant it to old apps.
10282                allowed = true;
10283            }
10284            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10285                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10286                // If this permission is to be granted to the system installer and
10287                // this app is an installer, then it gets the permission.
10288                allowed = true;
10289            }
10290            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10291                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10292                // If this permission is to be granted to the system verifier and
10293                // this app is a verifier, then it gets the permission.
10294                allowed = true;
10295            }
10296            if (!allowed && (bp.protectionLevel
10297                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10298                    && isSystemApp(pkg)) {
10299                // Any pre-installed system app is allowed to get this permission.
10300                allowed = true;
10301            }
10302            if (!allowed && (bp.protectionLevel
10303                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10304                // For development permissions, a development permission
10305                // is granted only if it was already granted.
10306                allowed = origPermissions.hasInstallPermission(perm);
10307            }
10308            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10309                    && pkg.packageName.equals(mSetupWizardPackage)) {
10310                // If this permission is to be granted to the system setup wizard and
10311                // this app is a setup wizard, then it gets the permission.
10312                allowed = true;
10313            }
10314        }
10315        return allowed;
10316    }
10317
10318    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10319        final int permCount = pkg.requestedPermissions.size();
10320        for (int j = 0; j < permCount; j++) {
10321            String requestedPermission = pkg.requestedPermissions.get(j);
10322            if (permission.equals(requestedPermission)) {
10323                return true;
10324            }
10325        }
10326        return false;
10327    }
10328
10329    final class ActivityIntentResolver
10330            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10331        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10332                boolean defaultOnly, int userId) {
10333            if (!sUserManager.exists(userId)) return null;
10334            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10335            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10336        }
10337
10338        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10339                int userId) {
10340            if (!sUserManager.exists(userId)) return null;
10341            mFlags = flags;
10342            return super.queryIntent(intent, resolvedType,
10343                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10344        }
10345
10346        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10347                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10348            if (!sUserManager.exists(userId)) return null;
10349            if (packageActivities == null) {
10350                return null;
10351            }
10352            mFlags = flags;
10353            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10354            final int N = packageActivities.size();
10355            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10356                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10357
10358            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10359            for (int i = 0; i < N; ++i) {
10360                intentFilters = packageActivities.get(i).intents;
10361                if (intentFilters != null && intentFilters.size() > 0) {
10362                    PackageParser.ActivityIntentInfo[] array =
10363                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10364                    intentFilters.toArray(array);
10365                    listCut.add(array);
10366                }
10367            }
10368            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10369        }
10370
10371        /**
10372         * Finds a privileged activity that matches the specified activity names.
10373         */
10374        private PackageParser.Activity findMatchingActivity(
10375                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10376            for (PackageParser.Activity sysActivity : activityList) {
10377                if (sysActivity.info.name.equals(activityInfo.name)) {
10378                    return sysActivity;
10379                }
10380                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10381                    return sysActivity;
10382                }
10383                if (sysActivity.info.targetActivity != null) {
10384                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10385                        return sysActivity;
10386                    }
10387                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10388                        return sysActivity;
10389                    }
10390                }
10391            }
10392            return null;
10393        }
10394
10395        public class IterGenerator<E> {
10396            public Iterator<E> generate(ActivityIntentInfo info) {
10397                return null;
10398            }
10399        }
10400
10401        public class ActionIterGenerator extends IterGenerator<String> {
10402            @Override
10403            public Iterator<String> generate(ActivityIntentInfo info) {
10404                return info.actionsIterator();
10405            }
10406        }
10407
10408        public class CategoriesIterGenerator extends IterGenerator<String> {
10409            @Override
10410            public Iterator<String> generate(ActivityIntentInfo info) {
10411                return info.categoriesIterator();
10412            }
10413        }
10414
10415        public class SchemesIterGenerator extends IterGenerator<String> {
10416            @Override
10417            public Iterator<String> generate(ActivityIntentInfo info) {
10418                return info.schemesIterator();
10419            }
10420        }
10421
10422        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10423            @Override
10424            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10425                return info.authoritiesIterator();
10426            }
10427        }
10428
10429        /**
10430         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10431         * MODIFIED. Do not pass in a list that should not be changed.
10432         */
10433        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10434                IterGenerator<T> generator, Iterator<T> searchIterator) {
10435            // loop through the set of actions; every one must be found in the intent filter
10436            while (searchIterator.hasNext()) {
10437                // we must have at least one filter in the list to consider a match
10438                if (intentList.size() == 0) {
10439                    break;
10440                }
10441
10442                final T searchAction = searchIterator.next();
10443
10444                // loop through the set of intent filters
10445                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10446                while (intentIter.hasNext()) {
10447                    final ActivityIntentInfo intentInfo = intentIter.next();
10448                    boolean selectionFound = false;
10449
10450                    // loop through the intent filter's selection criteria; at least one
10451                    // of them must match the searched criteria
10452                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10453                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10454                        final T intentSelection = intentSelectionIter.next();
10455                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10456                            selectionFound = true;
10457                            break;
10458                        }
10459                    }
10460
10461                    // the selection criteria wasn't found in this filter's set; this filter
10462                    // is not a potential match
10463                    if (!selectionFound) {
10464                        intentIter.remove();
10465                    }
10466                }
10467            }
10468        }
10469
10470        private boolean isProtectedAction(ActivityIntentInfo filter) {
10471            final Iterator<String> actionsIter = filter.actionsIterator();
10472            while (actionsIter != null && actionsIter.hasNext()) {
10473                final String filterAction = actionsIter.next();
10474                if (PROTECTED_ACTIONS.contains(filterAction)) {
10475                    return true;
10476                }
10477            }
10478            return false;
10479        }
10480
10481        /**
10482         * Adjusts the priority of the given intent filter according to policy.
10483         * <p>
10484         * <ul>
10485         * <li>The priority for non privileged applications is capped to '0'</li>
10486         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10487         * <li>The priority for unbundled updates to privileged applications is capped to the
10488         *      priority defined on the system partition</li>
10489         * </ul>
10490         * <p>
10491         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10492         * allowed to obtain any priority on any action.
10493         */
10494        private void adjustPriority(
10495                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10496            // nothing to do; priority is fine as-is
10497            if (intent.getPriority() <= 0) {
10498                return;
10499            }
10500
10501            final ActivityInfo activityInfo = intent.activity.info;
10502            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10503
10504            final boolean privilegedApp =
10505                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10506            if (!privilegedApp) {
10507                // non-privileged applications can never define a priority >0
10508                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10509                        + " package: " + applicationInfo.packageName
10510                        + " activity: " + intent.activity.className
10511                        + " origPrio: " + intent.getPriority());
10512                intent.setPriority(0);
10513                return;
10514            }
10515
10516            if (systemActivities == null) {
10517                // the system package is not disabled; we're parsing the system partition
10518                if (isProtectedAction(intent)) {
10519                    if (mDeferProtectedFilters) {
10520                        // We can't deal with these just yet. No component should ever obtain a
10521                        // >0 priority for a protected actions, with ONE exception -- the setup
10522                        // wizard. The setup wizard, however, cannot be known until we're able to
10523                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10524                        // until all intent filters have been processed. Chicken, meet egg.
10525                        // Let the filter temporarily have a high priority and rectify the
10526                        // priorities after all system packages have been scanned.
10527                        mProtectedFilters.add(intent);
10528                        if (DEBUG_FILTERS) {
10529                            Slog.i(TAG, "Protected action; save for later;"
10530                                    + " package: " + applicationInfo.packageName
10531                                    + " activity: " + intent.activity.className
10532                                    + " origPrio: " + intent.getPriority());
10533                        }
10534                        return;
10535                    } else {
10536                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10537                            Slog.i(TAG, "No setup wizard;"
10538                                + " All protected intents capped to priority 0");
10539                        }
10540                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10541                            if (DEBUG_FILTERS) {
10542                                Slog.i(TAG, "Found setup wizard;"
10543                                    + " allow priority " + intent.getPriority() + ";"
10544                                    + " package: " + intent.activity.info.packageName
10545                                    + " activity: " + intent.activity.className
10546                                    + " priority: " + intent.getPriority());
10547                            }
10548                            // setup wizard gets whatever it wants
10549                            return;
10550                        }
10551                        Slog.w(TAG, "Protected action; cap priority to 0;"
10552                                + " package: " + intent.activity.info.packageName
10553                                + " activity: " + intent.activity.className
10554                                + " origPrio: " + intent.getPriority());
10555                        intent.setPriority(0);
10556                        return;
10557                    }
10558                }
10559                // privileged apps on the system image get whatever priority they request
10560                return;
10561            }
10562
10563            // privileged app unbundled update ... try to find the same activity
10564            final PackageParser.Activity foundActivity =
10565                    findMatchingActivity(systemActivities, activityInfo);
10566            if (foundActivity == null) {
10567                // this is a new activity; it cannot obtain >0 priority
10568                if (DEBUG_FILTERS) {
10569                    Slog.i(TAG, "New activity; cap priority to 0;"
10570                            + " package: " + applicationInfo.packageName
10571                            + " activity: " + intent.activity.className
10572                            + " origPrio: " + intent.getPriority());
10573                }
10574                intent.setPriority(0);
10575                return;
10576            }
10577
10578            // found activity, now check for filter equivalence
10579
10580            // a shallow copy is enough; we modify the list, not its contents
10581            final List<ActivityIntentInfo> intentListCopy =
10582                    new ArrayList<>(foundActivity.intents);
10583            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10584
10585            // find matching action subsets
10586            final Iterator<String> actionsIterator = intent.actionsIterator();
10587            if (actionsIterator != null) {
10588                getIntentListSubset(
10589                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10590                if (intentListCopy.size() == 0) {
10591                    // no more intents to match; we're not equivalent
10592                    if (DEBUG_FILTERS) {
10593                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10594                                + " package: " + applicationInfo.packageName
10595                                + " activity: " + intent.activity.className
10596                                + " origPrio: " + intent.getPriority());
10597                    }
10598                    intent.setPriority(0);
10599                    return;
10600                }
10601            }
10602
10603            // find matching category subsets
10604            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10605            if (categoriesIterator != null) {
10606                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10607                        categoriesIterator);
10608                if (intentListCopy.size() == 0) {
10609                    // no more intents to match; we're not equivalent
10610                    if (DEBUG_FILTERS) {
10611                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10612                                + " package: " + applicationInfo.packageName
10613                                + " activity: " + intent.activity.className
10614                                + " origPrio: " + intent.getPriority());
10615                    }
10616                    intent.setPriority(0);
10617                    return;
10618                }
10619            }
10620
10621            // find matching schemes subsets
10622            final Iterator<String> schemesIterator = intent.schemesIterator();
10623            if (schemesIterator != null) {
10624                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10625                        schemesIterator);
10626                if (intentListCopy.size() == 0) {
10627                    // no more intents to match; we're not equivalent
10628                    if (DEBUG_FILTERS) {
10629                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10630                                + " package: " + applicationInfo.packageName
10631                                + " activity: " + intent.activity.className
10632                                + " origPrio: " + intent.getPriority());
10633                    }
10634                    intent.setPriority(0);
10635                    return;
10636                }
10637            }
10638
10639            // find matching authorities subsets
10640            final Iterator<IntentFilter.AuthorityEntry>
10641                    authoritiesIterator = intent.authoritiesIterator();
10642            if (authoritiesIterator != null) {
10643                getIntentListSubset(intentListCopy,
10644                        new AuthoritiesIterGenerator(),
10645                        authoritiesIterator);
10646                if (intentListCopy.size() == 0) {
10647                    // no more intents to match; we're not equivalent
10648                    if (DEBUG_FILTERS) {
10649                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10650                                + " package: " + applicationInfo.packageName
10651                                + " activity: " + intent.activity.className
10652                                + " origPrio: " + intent.getPriority());
10653                    }
10654                    intent.setPriority(0);
10655                    return;
10656                }
10657            }
10658
10659            // we found matching filter(s); app gets the max priority of all intents
10660            int cappedPriority = 0;
10661            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10662                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10663            }
10664            if (intent.getPriority() > cappedPriority) {
10665                if (DEBUG_FILTERS) {
10666                    Slog.i(TAG, "Found matching filter(s);"
10667                            + " cap priority to " + cappedPriority + ";"
10668                            + " package: " + applicationInfo.packageName
10669                            + " activity: " + intent.activity.className
10670                            + " origPrio: " + intent.getPriority());
10671                }
10672                intent.setPriority(cappedPriority);
10673                return;
10674            }
10675            // all this for nothing; the requested priority was <= what was on the system
10676        }
10677
10678        public final void addActivity(PackageParser.Activity a, String type) {
10679            mActivities.put(a.getComponentName(), a);
10680            if (DEBUG_SHOW_INFO)
10681                Log.v(
10682                TAG, "  " + type + " " +
10683                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10684            if (DEBUG_SHOW_INFO)
10685                Log.v(TAG, "    Class=" + a.info.name);
10686            final int NI = a.intents.size();
10687            for (int j=0; j<NI; j++) {
10688                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10689                if ("activity".equals(type)) {
10690                    final PackageSetting ps =
10691                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10692                    final List<PackageParser.Activity> systemActivities =
10693                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10694                    adjustPriority(systemActivities, intent);
10695                }
10696                if (DEBUG_SHOW_INFO) {
10697                    Log.v(TAG, "    IntentFilter:");
10698                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10699                }
10700                if (!intent.debugCheck()) {
10701                    Log.w(TAG, "==> For Activity " + a.info.name);
10702                }
10703                addFilter(intent);
10704            }
10705        }
10706
10707        public final void removeActivity(PackageParser.Activity a, String type) {
10708            mActivities.remove(a.getComponentName());
10709            if (DEBUG_SHOW_INFO) {
10710                Log.v(TAG, "  " + type + " "
10711                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10712                                : a.info.name) + ":");
10713                Log.v(TAG, "    Class=" + a.info.name);
10714            }
10715            final int NI = a.intents.size();
10716            for (int j=0; j<NI; j++) {
10717                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10718                if (DEBUG_SHOW_INFO) {
10719                    Log.v(TAG, "    IntentFilter:");
10720                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10721                }
10722                removeFilter(intent);
10723            }
10724        }
10725
10726        @Override
10727        protected boolean allowFilterResult(
10728                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10729            ActivityInfo filterAi = filter.activity.info;
10730            for (int i=dest.size()-1; i>=0; i--) {
10731                ActivityInfo destAi = dest.get(i).activityInfo;
10732                if (destAi.name == filterAi.name
10733                        && destAi.packageName == filterAi.packageName) {
10734                    return false;
10735                }
10736            }
10737            return true;
10738        }
10739
10740        @Override
10741        protected ActivityIntentInfo[] newArray(int size) {
10742            return new ActivityIntentInfo[size];
10743        }
10744
10745        @Override
10746        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10747            if (!sUserManager.exists(userId)) return true;
10748            PackageParser.Package p = filter.activity.owner;
10749            if (p != null) {
10750                PackageSetting ps = (PackageSetting)p.mExtras;
10751                if (ps != null) {
10752                    // System apps are never considered stopped for purposes of
10753                    // filtering, because there may be no way for the user to
10754                    // actually re-launch them.
10755                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10756                            && ps.getStopped(userId);
10757                }
10758            }
10759            return false;
10760        }
10761
10762        @Override
10763        protected boolean isPackageForFilter(String packageName,
10764                PackageParser.ActivityIntentInfo info) {
10765            return packageName.equals(info.activity.owner.packageName);
10766        }
10767
10768        @Override
10769        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10770                int match, int userId) {
10771            if (!sUserManager.exists(userId)) return null;
10772            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10773                return null;
10774            }
10775            final PackageParser.Activity activity = info.activity;
10776            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10777            if (ps == null) {
10778                return null;
10779            }
10780            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10781                    ps.readUserState(userId), userId);
10782            if (ai == null) {
10783                return null;
10784            }
10785            final ResolveInfo res = new ResolveInfo();
10786            res.activityInfo = ai;
10787            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10788                res.filter = info;
10789            }
10790            if (info != null) {
10791                res.handleAllWebDataURI = info.handleAllWebDataURI();
10792            }
10793            res.priority = info.getPriority();
10794            res.preferredOrder = activity.owner.mPreferredOrder;
10795            //System.out.println("Result: " + res.activityInfo.className +
10796            //                   " = " + res.priority);
10797            res.match = match;
10798            res.isDefault = info.hasDefault;
10799            res.labelRes = info.labelRes;
10800            res.nonLocalizedLabel = info.nonLocalizedLabel;
10801            if (userNeedsBadging(userId)) {
10802                res.noResourceId = true;
10803            } else {
10804                res.icon = info.icon;
10805            }
10806            res.iconResourceId = info.icon;
10807            res.system = res.activityInfo.applicationInfo.isSystemApp();
10808            return res;
10809        }
10810
10811        @Override
10812        protected void sortResults(List<ResolveInfo> results) {
10813            Collections.sort(results, mResolvePrioritySorter);
10814        }
10815
10816        @Override
10817        protected void dumpFilter(PrintWriter out, String prefix,
10818                PackageParser.ActivityIntentInfo filter) {
10819            out.print(prefix); out.print(
10820                    Integer.toHexString(System.identityHashCode(filter.activity)));
10821                    out.print(' ');
10822                    filter.activity.printComponentShortName(out);
10823                    out.print(" filter ");
10824                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10825        }
10826
10827        @Override
10828        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10829            return filter.activity;
10830        }
10831
10832        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10833            PackageParser.Activity activity = (PackageParser.Activity)label;
10834            out.print(prefix); out.print(
10835                    Integer.toHexString(System.identityHashCode(activity)));
10836                    out.print(' ');
10837                    activity.printComponentShortName(out);
10838            if (count > 1) {
10839                out.print(" ("); out.print(count); out.print(" filters)");
10840            }
10841            out.println();
10842        }
10843
10844        // Keys are String (activity class name), values are Activity.
10845        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10846                = new ArrayMap<ComponentName, PackageParser.Activity>();
10847        private int mFlags;
10848    }
10849
10850    private final class ServiceIntentResolver
10851            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10852        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10853                boolean defaultOnly, int userId) {
10854            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10855            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10856        }
10857
10858        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10859                int userId) {
10860            if (!sUserManager.exists(userId)) return null;
10861            mFlags = flags;
10862            return super.queryIntent(intent, resolvedType,
10863                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10864        }
10865
10866        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10867                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10868            if (!sUserManager.exists(userId)) return null;
10869            if (packageServices == null) {
10870                return null;
10871            }
10872            mFlags = flags;
10873            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10874            final int N = packageServices.size();
10875            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10876                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10877
10878            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10879            for (int i = 0; i < N; ++i) {
10880                intentFilters = packageServices.get(i).intents;
10881                if (intentFilters != null && intentFilters.size() > 0) {
10882                    PackageParser.ServiceIntentInfo[] array =
10883                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10884                    intentFilters.toArray(array);
10885                    listCut.add(array);
10886                }
10887            }
10888            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10889        }
10890
10891        public final void addService(PackageParser.Service s) {
10892            mServices.put(s.getComponentName(), s);
10893            if (DEBUG_SHOW_INFO) {
10894                Log.v(TAG, "  "
10895                        + (s.info.nonLocalizedLabel != null
10896                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10897                Log.v(TAG, "    Class=" + s.info.name);
10898            }
10899            final int NI = s.intents.size();
10900            int j;
10901            for (j=0; j<NI; j++) {
10902                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10903                if (DEBUG_SHOW_INFO) {
10904                    Log.v(TAG, "    IntentFilter:");
10905                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10906                }
10907                if (!intent.debugCheck()) {
10908                    Log.w(TAG, "==> For Service " + s.info.name);
10909                }
10910                addFilter(intent);
10911            }
10912        }
10913
10914        public final void removeService(PackageParser.Service s) {
10915            mServices.remove(s.getComponentName());
10916            if (DEBUG_SHOW_INFO) {
10917                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10918                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10919                Log.v(TAG, "    Class=" + s.info.name);
10920            }
10921            final int NI = s.intents.size();
10922            int j;
10923            for (j=0; j<NI; j++) {
10924                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10925                if (DEBUG_SHOW_INFO) {
10926                    Log.v(TAG, "    IntentFilter:");
10927                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10928                }
10929                removeFilter(intent);
10930            }
10931        }
10932
10933        @Override
10934        protected boolean allowFilterResult(
10935                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10936            ServiceInfo filterSi = filter.service.info;
10937            for (int i=dest.size()-1; i>=0; i--) {
10938                ServiceInfo destAi = dest.get(i).serviceInfo;
10939                if (destAi.name == filterSi.name
10940                        && destAi.packageName == filterSi.packageName) {
10941                    return false;
10942                }
10943            }
10944            return true;
10945        }
10946
10947        @Override
10948        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10949            return new PackageParser.ServiceIntentInfo[size];
10950        }
10951
10952        @Override
10953        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10954            if (!sUserManager.exists(userId)) return true;
10955            PackageParser.Package p = filter.service.owner;
10956            if (p != null) {
10957                PackageSetting ps = (PackageSetting)p.mExtras;
10958                if (ps != null) {
10959                    // System apps are never considered stopped for purposes of
10960                    // filtering, because there may be no way for the user to
10961                    // actually re-launch them.
10962                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10963                            && ps.getStopped(userId);
10964                }
10965            }
10966            return false;
10967        }
10968
10969        @Override
10970        protected boolean isPackageForFilter(String packageName,
10971                PackageParser.ServiceIntentInfo info) {
10972            return packageName.equals(info.service.owner.packageName);
10973        }
10974
10975        @Override
10976        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10977                int match, int userId) {
10978            if (!sUserManager.exists(userId)) return null;
10979            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10980            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10981                return null;
10982            }
10983            final PackageParser.Service service = info.service;
10984            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10985            if (ps == null) {
10986                return null;
10987            }
10988            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10989                    ps.readUserState(userId), userId);
10990            if (si == null) {
10991                return null;
10992            }
10993            final ResolveInfo res = new ResolveInfo();
10994            res.serviceInfo = si;
10995            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10996                res.filter = filter;
10997            }
10998            res.priority = info.getPriority();
10999            res.preferredOrder = service.owner.mPreferredOrder;
11000            res.match = match;
11001            res.isDefault = info.hasDefault;
11002            res.labelRes = info.labelRes;
11003            res.nonLocalizedLabel = info.nonLocalizedLabel;
11004            res.icon = info.icon;
11005            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11006            return res;
11007        }
11008
11009        @Override
11010        protected void sortResults(List<ResolveInfo> results) {
11011            Collections.sort(results, mResolvePrioritySorter);
11012        }
11013
11014        @Override
11015        protected void dumpFilter(PrintWriter out, String prefix,
11016                PackageParser.ServiceIntentInfo filter) {
11017            out.print(prefix); out.print(
11018                    Integer.toHexString(System.identityHashCode(filter.service)));
11019                    out.print(' ');
11020                    filter.service.printComponentShortName(out);
11021                    out.print(" filter ");
11022                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11023        }
11024
11025        @Override
11026        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11027            return filter.service;
11028        }
11029
11030        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11031            PackageParser.Service service = (PackageParser.Service)label;
11032            out.print(prefix); out.print(
11033                    Integer.toHexString(System.identityHashCode(service)));
11034                    out.print(' ');
11035                    service.printComponentShortName(out);
11036            if (count > 1) {
11037                out.print(" ("); out.print(count); out.print(" filters)");
11038            }
11039            out.println();
11040        }
11041
11042//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11043//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11044//            final List<ResolveInfo> retList = Lists.newArrayList();
11045//            while (i.hasNext()) {
11046//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11047//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11048//                    retList.add(resolveInfo);
11049//                }
11050//            }
11051//            return retList;
11052//        }
11053
11054        // Keys are String (activity class name), values are Activity.
11055        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11056                = new ArrayMap<ComponentName, PackageParser.Service>();
11057        private int mFlags;
11058    };
11059
11060    private final class ProviderIntentResolver
11061            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11062        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11063                boolean defaultOnly, int userId) {
11064            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11065            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11066        }
11067
11068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11069                int userId) {
11070            if (!sUserManager.exists(userId))
11071                return null;
11072            mFlags = flags;
11073            return super.queryIntent(intent, resolvedType,
11074                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11075        }
11076
11077        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11078                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11079            if (!sUserManager.exists(userId))
11080                return null;
11081            if (packageProviders == null) {
11082                return null;
11083            }
11084            mFlags = flags;
11085            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11086            final int N = packageProviders.size();
11087            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11088                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11089
11090            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11091            for (int i = 0; i < N; ++i) {
11092                intentFilters = packageProviders.get(i).intents;
11093                if (intentFilters != null && intentFilters.size() > 0) {
11094                    PackageParser.ProviderIntentInfo[] array =
11095                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11096                    intentFilters.toArray(array);
11097                    listCut.add(array);
11098                }
11099            }
11100            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11101        }
11102
11103        public final void addProvider(PackageParser.Provider p) {
11104            if (mProviders.containsKey(p.getComponentName())) {
11105                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11106                return;
11107            }
11108
11109            mProviders.put(p.getComponentName(), p);
11110            if (DEBUG_SHOW_INFO) {
11111                Log.v(TAG, "  "
11112                        + (p.info.nonLocalizedLabel != null
11113                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11114                Log.v(TAG, "    Class=" + p.info.name);
11115            }
11116            final int NI = p.intents.size();
11117            int j;
11118            for (j = 0; j < NI; j++) {
11119                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11120                if (DEBUG_SHOW_INFO) {
11121                    Log.v(TAG, "    IntentFilter:");
11122                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11123                }
11124                if (!intent.debugCheck()) {
11125                    Log.w(TAG, "==> For Provider " + p.info.name);
11126                }
11127                addFilter(intent);
11128            }
11129        }
11130
11131        public final void removeProvider(PackageParser.Provider p) {
11132            mProviders.remove(p.getComponentName());
11133            if (DEBUG_SHOW_INFO) {
11134                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11135                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11136                Log.v(TAG, "    Class=" + p.info.name);
11137            }
11138            final int NI = p.intents.size();
11139            int j;
11140            for (j = 0; j < NI; j++) {
11141                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11142                if (DEBUG_SHOW_INFO) {
11143                    Log.v(TAG, "    IntentFilter:");
11144                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11145                }
11146                removeFilter(intent);
11147            }
11148        }
11149
11150        @Override
11151        protected boolean allowFilterResult(
11152                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11153            ProviderInfo filterPi = filter.provider.info;
11154            for (int i = dest.size() - 1; i >= 0; i--) {
11155                ProviderInfo destPi = dest.get(i).providerInfo;
11156                if (destPi.name == filterPi.name
11157                        && destPi.packageName == filterPi.packageName) {
11158                    return false;
11159                }
11160            }
11161            return true;
11162        }
11163
11164        @Override
11165        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11166            return new PackageParser.ProviderIntentInfo[size];
11167        }
11168
11169        @Override
11170        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11171            if (!sUserManager.exists(userId))
11172                return true;
11173            PackageParser.Package p = filter.provider.owner;
11174            if (p != null) {
11175                PackageSetting ps = (PackageSetting) p.mExtras;
11176                if (ps != null) {
11177                    // System apps are never considered stopped for purposes of
11178                    // filtering, because there may be no way for the user to
11179                    // actually re-launch them.
11180                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11181                            && ps.getStopped(userId);
11182                }
11183            }
11184            return false;
11185        }
11186
11187        @Override
11188        protected boolean isPackageForFilter(String packageName,
11189                PackageParser.ProviderIntentInfo info) {
11190            return packageName.equals(info.provider.owner.packageName);
11191        }
11192
11193        @Override
11194        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11195                int match, int userId) {
11196            if (!sUserManager.exists(userId))
11197                return null;
11198            final PackageParser.ProviderIntentInfo info = filter;
11199            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11200                return null;
11201            }
11202            final PackageParser.Provider provider = info.provider;
11203            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11204            if (ps == null) {
11205                return null;
11206            }
11207            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11208                    ps.readUserState(userId), userId);
11209            if (pi == null) {
11210                return null;
11211            }
11212            final ResolveInfo res = new ResolveInfo();
11213            res.providerInfo = pi;
11214            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11215                res.filter = filter;
11216            }
11217            res.priority = info.getPriority();
11218            res.preferredOrder = provider.owner.mPreferredOrder;
11219            res.match = match;
11220            res.isDefault = info.hasDefault;
11221            res.labelRes = info.labelRes;
11222            res.nonLocalizedLabel = info.nonLocalizedLabel;
11223            res.icon = info.icon;
11224            res.system = res.providerInfo.applicationInfo.isSystemApp();
11225            return res;
11226        }
11227
11228        @Override
11229        protected void sortResults(List<ResolveInfo> results) {
11230            Collections.sort(results, mResolvePrioritySorter);
11231        }
11232
11233        @Override
11234        protected void dumpFilter(PrintWriter out, String prefix,
11235                PackageParser.ProviderIntentInfo filter) {
11236            out.print(prefix);
11237            out.print(
11238                    Integer.toHexString(System.identityHashCode(filter.provider)));
11239            out.print(' ');
11240            filter.provider.printComponentShortName(out);
11241            out.print(" filter ");
11242            out.println(Integer.toHexString(System.identityHashCode(filter)));
11243        }
11244
11245        @Override
11246        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11247            return filter.provider;
11248        }
11249
11250        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11251            PackageParser.Provider provider = (PackageParser.Provider)label;
11252            out.print(prefix); out.print(
11253                    Integer.toHexString(System.identityHashCode(provider)));
11254                    out.print(' ');
11255                    provider.printComponentShortName(out);
11256            if (count > 1) {
11257                out.print(" ("); out.print(count); out.print(" filters)");
11258            }
11259            out.println();
11260        }
11261
11262        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11263                = new ArrayMap<ComponentName, PackageParser.Provider>();
11264        private int mFlags;
11265    }
11266
11267    private static final class EphemeralIntentResolver
11268            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11269        /**
11270         * The result that has the highest defined order. Ordering applies on a
11271         * per-package basis. Mapping is from package name to Pair of order and
11272         * EphemeralResolveInfo.
11273         * <p>
11274         * NOTE: This is implemented as a field variable for convenience and efficiency.
11275         * By having a field variable, we're able to track filter ordering as soon as
11276         * a non-zero order is defined. Otherwise, multiple loops across the result set
11277         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11278         * this needs to be contained entirely within {@link #filterResults()}.
11279         */
11280        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11281
11282        @Override
11283        protected EphemeralResolveIntentInfo[] newArray(int size) {
11284            return new EphemeralResolveIntentInfo[size];
11285        }
11286
11287        @Override
11288        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11289            return true;
11290        }
11291
11292        @Override
11293        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11294                int userId) {
11295            if (!sUserManager.exists(userId)) {
11296                return null;
11297            }
11298            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11299            final Integer order = info.getOrder();
11300            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11301                    mOrderResult.get(packageName);
11302            // ordering is enabled and this item's order isn't high enough
11303            if (lastOrderResult != null && lastOrderResult.first >= order) {
11304                return null;
11305            }
11306            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11307            if (order > 0) {
11308                // non-zero order, enable ordering
11309                mOrderResult.put(packageName, new Pair<>(order, res));
11310            }
11311            return res;
11312        }
11313
11314        @Override
11315        protected void filterResults(List<EphemeralResolveInfo> results) {
11316            // only do work if ordering is enabled [most of the time it won't be]
11317            if (mOrderResult.size() == 0) {
11318                return;
11319            }
11320            int resultSize = results.size();
11321            for (int i = 0; i < resultSize; i++) {
11322                final EphemeralResolveInfo info = results.get(i);
11323                final String packageName = info.getPackageName();
11324                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11325                if (savedInfo == null) {
11326                    // package doesn't having ordering
11327                    continue;
11328                }
11329                if (savedInfo.second == info) {
11330                    // circled back to the highest ordered item; remove from order list
11331                    mOrderResult.remove(savedInfo);
11332                    if (mOrderResult.size() == 0) {
11333                        // no more ordered items
11334                        break;
11335                    }
11336                    continue;
11337                }
11338                // item has a worse order, remove it from the result list
11339                results.remove(i);
11340                resultSize--;
11341                i--;
11342            }
11343        }
11344    }
11345
11346    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11347            new Comparator<ResolveInfo>() {
11348        public int compare(ResolveInfo r1, ResolveInfo r2) {
11349            int v1 = r1.priority;
11350            int v2 = r2.priority;
11351            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11352            if (v1 != v2) {
11353                return (v1 > v2) ? -1 : 1;
11354            }
11355            v1 = r1.preferredOrder;
11356            v2 = r2.preferredOrder;
11357            if (v1 != v2) {
11358                return (v1 > v2) ? -1 : 1;
11359            }
11360            if (r1.isDefault != r2.isDefault) {
11361                return r1.isDefault ? -1 : 1;
11362            }
11363            v1 = r1.match;
11364            v2 = r2.match;
11365            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11366            if (v1 != v2) {
11367                return (v1 > v2) ? -1 : 1;
11368            }
11369            if (r1.system != r2.system) {
11370                return r1.system ? -1 : 1;
11371            }
11372            if (r1.activityInfo != null) {
11373                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11374            }
11375            if (r1.serviceInfo != null) {
11376                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11377            }
11378            if (r1.providerInfo != null) {
11379                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11380            }
11381            return 0;
11382        }
11383    };
11384
11385    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11386            new Comparator<ProviderInfo>() {
11387        public int compare(ProviderInfo p1, ProviderInfo p2) {
11388            final int v1 = p1.initOrder;
11389            final int v2 = p2.initOrder;
11390            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11391        }
11392    };
11393
11394    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11395            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11396            final int[] userIds) {
11397        mHandler.post(new Runnable() {
11398            @Override
11399            public void run() {
11400                try {
11401                    final IActivityManager am = ActivityManagerNative.getDefault();
11402                    if (am == null) return;
11403                    final int[] resolvedUserIds;
11404                    if (userIds == null) {
11405                        resolvedUserIds = am.getRunningUserIds();
11406                    } else {
11407                        resolvedUserIds = userIds;
11408                    }
11409                    for (int id : resolvedUserIds) {
11410                        final Intent intent = new Intent(action,
11411                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11412                        if (extras != null) {
11413                            intent.putExtras(extras);
11414                        }
11415                        if (targetPkg != null) {
11416                            intent.setPackage(targetPkg);
11417                        }
11418                        // Modify the UID when posting to other users
11419                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11420                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11421                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11422                            intent.putExtra(Intent.EXTRA_UID, uid);
11423                        }
11424                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11425                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11426                        if (DEBUG_BROADCASTS) {
11427                            RuntimeException here = new RuntimeException("here");
11428                            here.fillInStackTrace();
11429                            Slog.d(TAG, "Sending to user " + id + ": "
11430                                    + intent.toShortString(false, true, false, false)
11431                                    + " " + intent.getExtras(), here);
11432                        }
11433                        am.broadcastIntent(null, intent, null, finishedReceiver,
11434                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11435                                null, finishedReceiver != null, false, id);
11436                    }
11437                } catch (RemoteException ex) {
11438                }
11439            }
11440        });
11441    }
11442
11443    /**
11444     * Check if the external storage media is available. This is true if there
11445     * is a mounted external storage medium or if the external storage is
11446     * emulated.
11447     */
11448    private boolean isExternalMediaAvailable() {
11449        return mMediaMounted || Environment.isExternalStorageEmulated();
11450    }
11451
11452    @Override
11453    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11454        // writer
11455        synchronized (mPackages) {
11456            if (!isExternalMediaAvailable()) {
11457                // If the external storage is no longer mounted at this point,
11458                // the caller may not have been able to delete all of this
11459                // packages files and can not delete any more.  Bail.
11460                return null;
11461            }
11462            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11463            if (lastPackage != null) {
11464                pkgs.remove(lastPackage);
11465            }
11466            if (pkgs.size() > 0) {
11467                return pkgs.get(0);
11468            }
11469        }
11470        return null;
11471    }
11472
11473    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11474        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11475                userId, andCode ? 1 : 0, packageName);
11476        if (mSystemReady) {
11477            msg.sendToTarget();
11478        } else {
11479            if (mPostSystemReadyMessages == null) {
11480                mPostSystemReadyMessages = new ArrayList<>();
11481            }
11482            mPostSystemReadyMessages.add(msg);
11483        }
11484    }
11485
11486    void startCleaningPackages() {
11487        // reader
11488        if (!isExternalMediaAvailable()) {
11489            return;
11490        }
11491        synchronized (mPackages) {
11492            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11493                return;
11494            }
11495        }
11496        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11497        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11498        IActivityManager am = ActivityManagerNative.getDefault();
11499        if (am != null) {
11500            try {
11501                am.startService(null, intent, null, mContext.getOpPackageName(),
11502                        UserHandle.USER_SYSTEM);
11503            } catch (RemoteException e) {
11504            }
11505        }
11506    }
11507
11508    @Override
11509    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11510            int installFlags, String installerPackageName, int userId) {
11511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11512
11513        final int callingUid = Binder.getCallingUid();
11514        enforceCrossUserPermission(callingUid, userId,
11515                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11516
11517        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11518            try {
11519                if (observer != null) {
11520                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11521                }
11522            } catch (RemoteException re) {
11523            }
11524            return;
11525        }
11526
11527        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11528            installFlags |= PackageManager.INSTALL_FROM_ADB;
11529
11530        } else {
11531            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11532            // about installerPackageName.
11533
11534            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11535            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11536        }
11537
11538        UserHandle user;
11539        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11540            user = UserHandle.ALL;
11541        } else {
11542            user = new UserHandle(userId);
11543        }
11544
11545        // Only system components can circumvent runtime permissions when installing.
11546        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11547                && mContext.checkCallingOrSelfPermission(Manifest.permission
11548                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11549            throw new SecurityException("You need the "
11550                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11551                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11552        }
11553
11554        final File originFile = new File(originPath);
11555        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11556
11557        final Message msg = mHandler.obtainMessage(INIT_COPY);
11558        final VerificationInfo verificationInfo = new VerificationInfo(
11559                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11560        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11561                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11562                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11563                null /*certificates*/);
11564        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11565        msg.obj = params;
11566
11567        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11568                System.identityHashCode(msg.obj));
11569        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11570                System.identityHashCode(msg.obj));
11571
11572        mHandler.sendMessage(msg);
11573    }
11574
11575    void installStage(String packageName, File stagedDir, String stagedCid,
11576            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11577            String installerPackageName, int installerUid, UserHandle user,
11578            Certificate[][] certificates) {
11579        if (DEBUG_EPHEMERAL) {
11580            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11581                Slog.d(TAG, "Ephemeral install of " + packageName);
11582            }
11583        }
11584        final VerificationInfo verificationInfo = new VerificationInfo(
11585                sessionParams.originatingUri, sessionParams.referrerUri,
11586                sessionParams.originatingUid, installerUid);
11587
11588        final OriginInfo origin;
11589        if (stagedDir != null) {
11590            origin = OriginInfo.fromStagedFile(stagedDir);
11591        } else {
11592            origin = OriginInfo.fromStagedContainer(stagedCid);
11593        }
11594
11595        final Message msg = mHandler.obtainMessage(INIT_COPY);
11596        final InstallParams params = new InstallParams(origin, null, observer,
11597                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11598                verificationInfo, user, sessionParams.abiOverride,
11599                sessionParams.grantedRuntimePermissions, certificates);
11600        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11601        msg.obj = params;
11602
11603        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11604                System.identityHashCode(msg.obj));
11605        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11606                System.identityHashCode(msg.obj));
11607
11608        mHandler.sendMessage(msg);
11609    }
11610
11611    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11612            int userId) {
11613        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11614        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11615    }
11616
11617    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11618            int appId, int userId) {
11619        Bundle extras = new Bundle(1);
11620        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11621
11622        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11623                packageName, extras, 0, null, null, new int[] {userId});
11624        try {
11625            IActivityManager am = ActivityManagerNative.getDefault();
11626            if (isSystem && am.isUserRunning(userId, 0)) {
11627                // The just-installed/enabled app is bundled on the system, so presumed
11628                // to be able to run automatically without needing an explicit launch.
11629                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11630                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11631                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11632                        .setPackage(packageName);
11633                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11634                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11635            }
11636        } catch (RemoteException e) {
11637            // shouldn't happen
11638            Slog.w(TAG, "Unable to bootstrap installed package", e);
11639        }
11640    }
11641
11642    @Override
11643    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11644            int userId) {
11645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11646        PackageSetting pkgSetting;
11647        final int uid = Binder.getCallingUid();
11648        enforceCrossUserPermission(uid, userId,
11649                true /* requireFullPermission */, true /* checkShell */,
11650                "setApplicationHiddenSetting for user " + userId);
11651
11652        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11653            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11654            return false;
11655        }
11656
11657        long callingId = Binder.clearCallingIdentity();
11658        try {
11659            boolean sendAdded = false;
11660            boolean sendRemoved = false;
11661            // writer
11662            synchronized (mPackages) {
11663                pkgSetting = mSettings.mPackages.get(packageName);
11664                if (pkgSetting == null) {
11665                    return false;
11666                }
11667                // Do not allow "android" is being disabled
11668                if ("android".equals(packageName)) {
11669                    Slog.w(TAG, "Cannot hide package: android");
11670                    return false;
11671                }
11672                // Only allow protected packages to hide themselves.
11673                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11674                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11675                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11676                    return false;
11677                }
11678
11679                if (pkgSetting.getHidden(userId) != hidden) {
11680                    pkgSetting.setHidden(hidden, userId);
11681                    mSettings.writePackageRestrictionsLPr(userId);
11682                    if (hidden) {
11683                        sendRemoved = true;
11684                    } else {
11685                        sendAdded = true;
11686                    }
11687                }
11688            }
11689            if (sendAdded) {
11690                sendPackageAddedForUser(packageName, pkgSetting, userId);
11691                return true;
11692            }
11693            if (sendRemoved) {
11694                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11695                        "hiding pkg");
11696                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11697                return true;
11698            }
11699        } finally {
11700            Binder.restoreCallingIdentity(callingId);
11701        }
11702        return false;
11703    }
11704
11705    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11706            int userId) {
11707        final PackageRemovedInfo info = new PackageRemovedInfo();
11708        info.removedPackage = packageName;
11709        info.removedUsers = new int[] {userId};
11710        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11711        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11712    }
11713
11714    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11715        if (pkgList.length > 0) {
11716            Bundle extras = new Bundle(1);
11717            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11718
11719            sendPackageBroadcast(
11720                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11721                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11722                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11723                    new int[] {userId});
11724        }
11725    }
11726
11727    /**
11728     * Returns true if application is not found or there was an error. Otherwise it returns
11729     * the hidden state of the package for the given user.
11730     */
11731    @Override
11732    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11733        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11734        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11735                true /* requireFullPermission */, false /* checkShell */,
11736                "getApplicationHidden for user " + userId);
11737        PackageSetting pkgSetting;
11738        long callingId = Binder.clearCallingIdentity();
11739        try {
11740            // writer
11741            synchronized (mPackages) {
11742                pkgSetting = mSettings.mPackages.get(packageName);
11743                if (pkgSetting == null) {
11744                    return true;
11745                }
11746                return pkgSetting.getHidden(userId);
11747            }
11748        } finally {
11749            Binder.restoreCallingIdentity(callingId);
11750        }
11751    }
11752
11753    /**
11754     * @hide
11755     */
11756    @Override
11757    public int installExistingPackageAsUser(String packageName, int userId) {
11758        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11759                null);
11760        PackageSetting pkgSetting;
11761        final int uid = Binder.getCallingUid();
11762        enforceCrossUserPermission(uid, userId,
11763                true /* requireFullPermission */, true /* checkShell */,
11764                "installExistingPackage for user " + userId);
11765        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11766            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11767        }
11768
11769        long callingId = Binder.clearCallingIdentity();
11770        try {
11771            boolean installed = false;
11772
11773            // writer
11774            synchronized (mPackages) {
11775                pkgSetting = mSettings.mPackages.get(packageName);
11776                if (pkgSetting == null) {
11777                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11778                }
11779                if (!pkgSetting.getInstalled(userId)) {
11780                    pkgSetting.setInstalled(true, userId);
11781                    pkgSetting.setHidden(false, userId);
11782                    mSettings.writePackageRestrictionsLPr(userId);
11783                    installed = true;
11784                }
11785            }
11786
11787            if (installed) {
11788                if (pkgSetting.pkg != null) {
11789                    synchronized (mInstallLock) {
11790                        // We don't need to freeze for a brand new install
11791                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11792                    }
11793                }
11794                sendPackageAddedForUser(packageName, pkgSetting, userId);
11795            }
11796        } finally {
11797            Binder.restoreCallingIdentity(callingId);
11798        }
11799
11800        return PackageManager.INSTALL_SUCCEEDED;
11801    }
11802
11803    boolean isUserRestricted(int userId, String restrictionKey) {
11804        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11805        if (restrictions.getBoolean(restrictionKey, false)) {
11806            Log.w(TAG, "User is restricted: " + restrictionKey);
11807            return true;
11808        }
11809        return false;
11810    }
11811
11812    @Override
11813    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11814            int userId) {
11815        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11816        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11817                true /* requireFullPermission */, true /* checkShell */,
11818                "setPackagesSuspended for user " + userId);
11819
11820        if (ArrayUtils.isEmpty(packageNames)) {
11821            return packageNames;
11822        }
11823
11824        // List of package names for whom the suspended state has changed.
11825        List<String> changedPackages = new ArrayList<>(packageNames.length);
11826        // List of package names for whom the suspended state is not set as requested in this
11827        // method.
11828        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11829        long callingId = Binder.clearCallingIdentity();
11830        try {
11831            for (int i = 0; i < packageNames.length; i++) {
11832                String packageName = packageNames[i];
11833                boolean changed = false;
11834                final int appId;
11835                synchronized (mPackages) {
11836                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11837                    if (pkgSetting == null) {
11838                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11839                                + "\". Skipping suspending/un-suspending.");
11840                        unactionedPackages.add(packageName);
11841                        continue;
11842                    }
11843                    appId = pkgSetting.appId;
11844                    if (pkgSetting.getSuspended(userId) != suspended) {
11845                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11846                            unactionedPackages.add(packageName);
11847                            continue;
11848                        }
11849                        pkgSetting.setSuspended(suspended, userId);
11850                        mSettings.writePackageRestrictionsLPr(userId);
11851                        changed = true;
11852                        changedPackages.add(packageName);
11853                    }
11854                }
11855
11856                if (changed && suspended) {
11857                    killApplication(packageName, UserHandle.getUid(userId, appId),
11858                            "suspending package");
11859                }
11860            }
11861        } finally {
11862            Binder.restoreCallingIdentity(callingId);
11863        }
11864
11865        if (!changedPackages.isEmpty()) {
11866            sendPackagesSuspendedForUser(changedPackages.toArray(
11867                    new String[changedPackages.size()]), userId, suspended);
11868        }
11869
11870        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11871    }
11872
11873    @Override
11874    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11875        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11876                true /* requireFullPermission */, false /* checkShell */,
11877                "isPackageSuspendedForUser for user " + userId);
11878        synchronized (mPackages) {
11879            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11880            if (pkgSetting == null) {
11881                throw new IllegalArgumentException("Unknown target package: " + packageName);
11882            }
11883            return pkgSetting.getSuspended(userId);
11884        }
11885    }
11886
11887    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11888        if (isPackageDeviceAdmin(packageName, userId)) {
11889            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11890                    + "\": has an active device admin");
11891            return false;
11892        }
11893
11894        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11895        if (packageName.equals(activeLauncherPackageName)) {
11896            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11897                    + "\": contains the active launcher");
11898            return false;
11899        }
11900
11901        if (packageName.equals(mRequiredInstallerPackage)) {
11902            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11903                    + "\": required for package installation");
11904            return false;
11905        }
11906
11907        if (packageName.equals(mRequiredUninstallerPackage)) {
11908            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11909                    + "\": required for package uninstallation");
11910            return false;
11911        }
11912
11913        if (packageName.equals(mRequiredVerifierPackage)) {
11914            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11915                    + "\": required for package verification");
11916            return false;
11917        }
11918
11919        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11920            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11921                    + "\": is the default dialer");
11922            return false;
11923        }
11924
11925        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11926            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11927                    + "\": protected package");
11928            return false;
11929        }
11930
11931        return true;
11932    }
11933
11934    private String getActiveLauncherPackageName(int userId) {
11935        Intent intent = new Intent(Intent.ACTION_MAIN);
11936        intent.addCategory(Intent.CATEGORY_HOME);
11937        ResolveInfo resolveInfo = resolveIntent(
11938                intent,
11939                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11940                PackageManager.MATCH_DEFAULT_ONLY,
11941                userId);
11942
11943        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11944    }
11945
11946    private String getDefaultDialerPackageName(int userId) {
11947        synchronized (mPackages) {
11948            return mSettings.getDefaultDialerPackageNameLPw(userId);
11949        }
11950    }
11951
11952    @Override
11953    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11954        mContext.enforceCallingOrSelfPermission(
11955                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11956                "Only package verification agents can verify applications");
11957
11958        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11959        final PackageVerificationResponse response = new PackageVerificationResponse(
11960                verificationCode, Binder.getCallingUid());
11961        msg.arg1 = id;
11962        msg.obj = response;
11963        mHandler.sendMessage(msg);
11964    }
11965
11966    @Override
11967    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11968            long millisecondsToDelay) {
11969        mContext.enforceCallingOrSelfPermission(
11970                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11971                "Only package verification agents can extend verification timeouts");
11972
11973        final PackageVerificationState state = mPendingVerification.get(id);
11974        final PackageVerificationResponse response = new PackageVerificationResponse(
11975                verificationCodeAtTimeout, Binder.getCallingUid());
11976
11977        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11978            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11979        }
11980        if (millisecondsToDelay < 0) {
11981            millisecondsToDelay = 0;
11982        }
11983        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11984                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11985            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11986        }
11987
11988        if ((state != null) && !state.timeoutExtended()) {
11989            state.extendTimeout();
11990
11991            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11992            msg.arg1 = id;
11993            msg.obj = response;
11994            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11995        }
11996    }
11997
11998    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11999            int verificationCode, UserHandle user) {
12000        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12001        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12002        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12003        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12004        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12005
12006        mContext.sendBroadcastAsUser(intent, user,
12007                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12008    }
12009
12010    private ComponentName matchComponentForVerifier(String packageName,
12011            List<ResolveInfo> receivers) {
12012        ActivityInfo targetReceiver = null;
12013
12014        final int NR = receivers.size();
12015        for (int i = 0; i < NR; i++) {
12016            final ResolveInfo info = receivers.get(i);
12017            if (info.activityInfo == null) {
12018                continue;
12019            }
12020
12021            if (packageName.equals(info.activityInfo.packageName)) {
12022                targetReceiver = info.activityInfo;
12023                break;
12024            }
12025        }
12026
12027        if (targetReceiver == null) {
12028            return null;
12029        }
12030
12031        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12032    }
12033
12034    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12035            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12036        if (pkgInfo.verifiers.length == 0) {
12037            return null;
12038        }
12039
12040        final int N = pkgInfo.verifiers.length;
12041        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12042        for (int i = 0; i < N; i++) {
12043            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12044
12045            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12046                    receivers);
12047            if (comp == null) {
12048                continue;
12049            }
12050
12051            final int verifierUid = getUidForVerifier(verifierInfo);
12052            if (verifierUid == -1) {
12053                continue;
12054            }
12055
12056            if (DEBUG_VERIFY) {
12057                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12058                        + " with the correct signature");
12059            }
12060            sufficientVerifiers.add(comp);
12061            verificationState.addSufficientVerifier(verifierUid);
12062        }
12063
12064        return sufficientVerifiers;
12065    }
12066
12067    private int getUidForVerifier(VerifierInfo verifierInfo) {
12068        synchronized (mPackages) {
12069            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12070            if (pkg == null) {
12071                return -1;
12072            } else if (pkg.mSignatures.length != 1) {
12073                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12074                        + " has more than one signature; ignoring");
12075                return -1;
12076            }
12077
12078            /*
12079             * If the public key of the package's signature does not match
12080             * our expected public key, then this is a different package and
12081             * we should skip.
12082             */
12083
12084            final byte[] expectedPublicKey;
12085            try {
12086                final Signature verifierSig = pkg.mSignatures[0];
12087                final PublicKey publicKey = verifierSig.getPublicKey();
12088                expectedPublicKey = publicKey.getEncoded();
12089            } catch (CertificateException e) {
12090                return -1;
12091            }
12092
12093            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12094
12095            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12096                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12097                        + " does not have the expected public key; ignoring");
12098                return -1;
12099            }
12100
12101            return pkg.applicationInfo.uid;
12102        }
12103    }
12104
12105    @Override
12106    public void finishPackageInstall(int token, boolean didLaunch) {
12107        enforceSystemOrRoot("Only the system is allowed to finish installs");
12108
12109        if (DEBUG_INSTALL) {
12110            Slog.v(TAG, "BM finishing package install for " + token);
12111        }
12112        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12113
12114        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12115        mHandler.sendMessage(msg);
12116    }
12117
12118    /**
12119     * Get the verification agent timeout.
12120     *
12121     * @return verification timeout in milliseconds
12122     */
12123    private long getVerificationTimeout() {
12124        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12125                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12126                DEFAULT_VERIFICATION_TIMEOUT);
12127    }
12128
12129    /**
12130     * Get the default verification agent response code.
12131     *
12132     * @return default verification response code
12133     */
12134    private int getDefaultVerificationResponse() {
12135        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12136                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12137                DEFAULT_VERIFICATION_RESPONSE);
12138    }
12139
12140    /**
12141     * Check whether or not package verification has been enabled.
12142     *
12143     * @return true if verification should be performed
12144     */
12145    private boolean isVerificationEnabled(int userId, int installFlags) {
12146        if (!DEFAULT_VERIFY_ENABLE) {
12147            return false;
12148        }
12149        // Ephemeral apps don't get the full verification treatment
12150        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12151            if (DEBUG_EPHEMERAL) {
12152                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12153            }
12154            return false;
12155        }
12156
12157        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12158
12159        // Check if installing from ADB
12160        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12161            // Do not run verification in a test harness environment
12162            if (ActivityManager.isRunningInTestHarness()) {
12163                return false;
12164            }
12165            if (ensureVerifyAppsEnabled) {
12166                return true;
12167            }
12168            // Check if the developer does not want package verification for ADB installs
12169            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12170                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12171                return false;
12172            }
12173        }
12174
12175        if (ensureVerifyAppsEnabled) {
12176            return true;
12177        }
12178
12179        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12180                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12181    }
12182
12183    @Override
12184    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12185            throws RemoteException {
12186        mContext.enforceCallingOrSelfPermission(
12187                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12188                "Only intentfilter verification agents can verify applications");
12189
12190        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12191        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12192                Binder.getCallingUid(), verificationCode, failedDomains);
12193        msg.arg1 = id;
12194        msg.obj = response;
12195        mHandler.sendMessage(msg);
12196    }
12197
12198    @Override
12199    public int getIntentVerificationStatus(String packageName, int userId) {
12200        synchronized (mPackages) {
12201            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12202        }
12203    }
12204
12205    @Override
12206    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12207        mContext.enforceCallingOrSelfPermission(
12208                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12209
12210        boolean result = false;
12211        synchronized (mPackages) {
12212            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12213        }
12214        if (result) {
12215            scheduleWritePackageRestrictionsLocked(userId);
12216        }
12217        return result;
12218    }
12219
12220    @Override
12221    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12222            String packageName) {
12223        synchronized (mPackages) {
12224            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12225        }
12226    }
12227
12228    @Override
12229    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12230        if (TextUtils.isEmpty(packageName)) {
12231            return ParceledListSlice.emptyList();
12232        }
12233        synchronized (mPackages) {
12234            PackageParser.Package pkg = mPackages.get(packageName);
12235            if (pkg == null || pkg.activities == null) {
12236                return ParceledListSlice.emptyList();
12237            }
12238            final int count = pkg.activities.size();
12239            ArrayList<IntentFilter> result = new ArrayList<>();
12240            for (int n=0; n<count; n++) {
12241                PackageParser.Activity activity = pkg.activities.get(n);
12242                if (activity.intents != null && activity.intents.size() > 0) {
12243                    result.addAll(activity.intents);
12244                }
12245            }
12246            return new ParceledListSlice<>(result);
12247        }
12248    }
12249
12250    @Override
12251    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12252        mContext.enforceCallingOrSelfPermission(
12253                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12254
12255        synchronized (mPackages) {
12256            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12257            if (packageName != null) {
12258                result |= updateIntentVerificationStatus(packageName,
12259                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12260                        userId);
12261                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12262                        packageName, userId);
12263            }
12264            return result;
12265        }
12266    }
12267
12268    @Override
12269    public String getDefaultBrowserPackageName(int userId) {
12270        synchronized (mPackages) {
12271            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12272        }
12273    }
12274
12275    /**
12276     * Get the "allow unknown sources" setting.
12277     *
12278     * @return the current "allow unknown sources" setting
12279     */
12280    private int getUnknownSourcesSettings() {
12281        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12282                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12283                -1);
12284    }
12285
12286    @Override
12287    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12288        final int uid = Binder.getCallingUid();
12289        // writer
12290        synchronized (mPackages) {
12291            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12292            if (targetPackageSetting == null) {
12293                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12294            }
12295
12296            PackageSetting installerPackageSetting;
12297            if (installerPackageName != null) {
12298                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12299                if (installerPackageSetting == null) {
12300                    throw new IllegalArgumentException("Unknown installer package: "
12301                            + installerPackageName);
12302                }
12303            } else {
12304                installerPackageSetting = null;
12305            }
12306
12307            Signature[] callerSignature;
12308            Object obj = mSettings.getUserIdLPr(uid);
12309            if (obj != null) {
12310                if (obj instanceof SharedUserSetting) {
12311                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12312                } else if (obj instanceof PackageSetting) {
12313                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12314                } else {
12315                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12316                }
12317            } else {
12318                throw new SecurityException("Unknown calling UID: " + uid);
12319            }
12320
12321            // Verify: can't set installerPackageName to a package that is
12322            // not signed with the same cert as the caller.
12323            if (installerPackageSetting != null) {
12324                if (compareSignatures(callerSignature,
12325                        installerPackageSetting.signatures.mSignatures)
12326                        != PackageManager.SIGNATURE_MATCH) {
12327                    throw new SecurityException(
12328                            "Caller does not have same cert as new installer package "
12329                            + installerPackageName);
12330                }
12331            }
12332
12333            // Verify: if target already has an installer package, it must
12334            // be signed with the same cert as the caller.
12335            if (targetPackageSetting.installerPackageName != null) {
12336                PackageSetting setting = mSettings.mPackages.get(
12337                        targetPackageSetting.installerPackageName);
12338                // If the currently set package isn't valid, then it's always
12339                // okay to change it.
12340                if (setting != null) {
12341                    if (compareSignatures(callerSignature,
12342                            setting.signatures.mSignatures)
12343                            != PackageManager.SIGNATURE_MATCH) {
12344                        throw new SecurityException(
12345                                "Caller does not have same cert as old installer package "
12346                                + targetPackageSetting.installerPackageName);
12347                    }
12348                }
12349            }
12350
12351            // Okay!
12352            targetPackageSetting.installerPackageName = installerPackageName;
12353            if (installerPackageName != null) {
12354                mSettings.mInstallerPackages.add(installerPackageName);
12355            }
12356            scheduleWriteSettingsLocked();
12357        }
12358    }
12359
12360    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12361        // Queue up an async operation since the package installation may take a little while.
12362        mHandler.post(new Runnable() {
12363            public void run() {
12364                mHandler.removeCallbacks(this);
12365                 // Result object to be returned
12366                PackageInstalledInfo res = new PackageInstalledInfo();
12367                res.setReturnCode(currentStatus);
12368                res.uid = -1;
12369                res.pkg = null;
12370                res.removedInfo = null;
12371                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12372                    args.doPreInstall(res.returnCode);
12373                    synchronized (mInstallLock) {
12374                        installPackageTracedLI(args, res);
12375                    }
12376                    args.doPostInstall(res.returnCode, res.uid);
12377                }
12378
12379                // A restore should be performed at this point if (a) the install
12380                // succeeded, (b) the operation is not an update, and (c) the new
12381                // package has not opted out of backup participation.
12382                final boolean update = res.removedInfo != null
12383                        && res.removedInfo.removedPackage != null;
12384                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12385                boolean doRestore = !update
12386                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12387
12388                // Set up the post-install work request bookkeeping.  This will be used
12389                // and cleaned up by the post-install event handling regardless of whether
12390                // there's a restore pass performed.  Token values are >= 1.
12391                int token;
12392                if (mNextInstallToken < 0) mNextInstallToken = 1;
12393                token = mNextInstallToken++;
12394
12395                PostInstallData data = new PostInstallData(args, res);
12396                mRunningInstalls.put(token, data);
12397                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12398
12399                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12400                    // Pass responsibility to the Backup Manager.  It will perform a
12401                    // restore if appropriate, then pass responsibility back to the
12402                    // Package Manager to run the post-install observer callbacks
12403                    // and broadcasts.
12404                    IBackupManager bm = IBackupManager.Stub.asInterface(
12405                            ServiceManager.getService(Context.BACKUP_SERVICE));
12406                    if (bm != null) {
12407                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12408                                + " to BM for possible restore");
12409                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12410                        try {
12411                            // TODO: http://b/22388012
12412                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12413                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12414                            } else {
12415                                doRestore = false;
12416                            }
12417                        } catch (RemoteException e) {
12418                            // can't happen; the backup manager is local
12419                        } catch (Exception e) {
12420                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12421                            doRestore = false;
12422                        }
12423                    } else {
12424                        Slog.e(TAG, "Backup Manager not found!");
12425                        doRestore = false;
12426                    }
12427                }
12428
12429                if (!doRestore) {
12430                    // No restore possible, or the Backup Manager was mysteriously not
12431                    // available -- just fire the post-install work request directly.
12432                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12433
12434                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12435
12436                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12437                    mHandler.sendMessage(msg);
12438                }
12439            }
12440        });
12441    }
12442
12443    /**
12444     * Callback from PackageSettings whenever an app is first transitioned out of the
12445     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12446     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12447     * here whether the app is the target of an ongoing install, and only send the
12448     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12449     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12450     * handling.
12451     */
12452    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12453        // Serialize this with the rest of the install-process message chain.  In the
12454        // restore-at-install case, this Runnable will necessarily run before the
12455        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12456        // are coherent.  In the non-restore case, the app has already completed install
12457        // and been launched through some other means, so it is not in a problematic
12458        // state for observers to see the FIRST_LAUNCH signal.
12459        mHandler.post(new Runnable() {
12460            @Override
12461            public void run() {
12462                for (int i = 0; i < mRunningInstalls.size(); i++) {
12463                    final PostInstallData data = mRunningInstalls.valueAt(i);
12464                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12465                        continue;
12466                    }
12467                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12468                        // right package; but is it for the right user?
12469                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12470                            if (userId == data.res.newUsers[uIndex]) {
12471                                if (DEBUG_BACKUP) {
12472                                    Slog.i(TAG, "Package " + pkgName
12473                                            + " being restored so deferring FIRST_LAUNCH");
12474                                }
12475                                return;
12476                            }
12477                        }
12478                    }
12479                }
12480                // didn't find it, so not being restored
12481                if (DEBUG_BACKUP) {
12482                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12483                }
12484                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12485            }
12486        });
12487    }
12488
12489    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12490        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12491                installerPkg, null, userIds);
12492    }
12493
12494    private abstract class HandlerParams {
12495        private static final int MAX_RETRIES = 4;
12496
12497        /**
12498         * Number of times startCopy() has been attempted and had a non-fatal
12499         * error.
12500         */
12501        private int mRetries = 0;
12502
12503        /** User handle for the user requesting the information or installation. */
12504        private final UserHandle mUser;
12505        String traceMethod;
12506        int traceCookie;
12507
12508        HandlerParams(UserHandle user) {
12509            mUser = user;
12510        }
12511
12512        UserHandle getUser() {
12513            return mUser;
12514        }
12515
12516        HandlerParams setTraceMethod(String traceMethod) {
12517            this.traceMethod = traceMethod;
12518            return this;
12519        }
12520
12521        HandlerParams setTraceCookie(int traceCookie) {
12522            this.traceCookie = traceCookie;
12523            return this;
12524        }
12525
12526        final boolean startCopy() {
12527            boolean res;
12528            try {
12529                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12530
12531                if (++mRetries > MAX_RETRIES) {
12532                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12533                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12534                    handleServiceError();
12535                    return false;
12536                } else {
12537                    handleStartCopy();
12538                    res = true;
12539                }
12540            } catch (RemoteException e) {
12541                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12542                mHandler.sendEmptyMessage(MCS_RECONNECT);
12543                res = false;
12544            }
12545            handleReturnCode();
12546            return res;
12547        }
12548
12549        final void serviceError() {
12550            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12551            handleServiceError();
12552            handleReturnCode();
12553        }
12554
12555        abstract void handleStartCopy() throws RemoteException;
12556        abstract void handleServiceError();
12557        abstract void handleReturnCode();
12558    }
12559
12560    class MeasureParams extends HandlerParams {
12561        private final PackageStats mStats;
12562        private boolean mSuccess;
12563
12564        private final IPackageStatsObserver mObserver;
12565
12566        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12567            super(new UserHandle(stats.userHandle));
12568            mObserver = observer;
12569            mStats = stats;
12570        }
12571
12572        @Override
12573        public String toString() {
12574            return "MeasureParams{"
12575                + Integer.toHexString(System.identityHashCode(this))
12576                + " " + mStats.packageName + "}";
12577        }
12578
12579        @Override
12580        void handleStartCopy() throws RemoteException {
12581            synchronized (mInstallLock) {
12582                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12583            }
12584
12585            if (mSuccess) {
12586                boolean mounted = false;
12587                try {
12588                    final String status = Environment.getExternalStorageState();
12589                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12590                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12591                } catch (Exception e) {
12592                }
12593
12594                if (mounted) {
12595                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12596
12597                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12598                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12599
12600                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12601                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12602
12603                    // Always subtract cache size, since it's a subdirectory
12604                    mStats.externalDataSize -= mStats.externalCacheSize;
12605
12606                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12607                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12608
12609                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12610                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12611                }
12612            }
12613        }
12614
12615        @Override
12616        void handleReturnCode() {
12617            if (mObserver != null) {
12618                try {
12619                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12620                } catch (RemoteException e) {
12621                    Slog.i(TAG, "Observer no longer exists.");
12622                }
12623            }
12624        }
12625
12626        @Override
12627        void handleServiceError() {
12628            Slog.e(TAG, "Could not measure application " + mStats.packageName
12629                            + " external storage");
12630        }
12631    }
12632
12633    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12634            throws RemoteException {
12635        long result = 0;
12636        for (File path : paths) {
12637            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12638        }
12639        return result;
12640    }
12641
12642    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12643        for (File path : paths) {
12644            try {
12645                mcs.clearDirectory(path.getAbsolutePath());
12646            } catch (RemoteException e) {
12647            }
12648        }
12649    }
12650
12651    static class OriginInfo {
12652        /**
12653         * Location where install is coming from, before it has been
12654         * copied/renamed into place. This could be a single monolithic APK
12655         * file, or a cluster directory. This location may be untrusted.
12656         */
12657        final File file;
12658        final String cid;
12659
12660        /**
12661         * Flag indicating that {@link #file} or {@link #cid} has already been
12662         * staged, meaning downstream users don't need to defensively copy the
12663         * contents.
12664         */
12665        final boolean staged;
12666
12667        /**
12668         * Flag indicating that {@link #file} or {@link #cid} is an already
12669         * installed app that is being moved.
12670         */
12671        final boolean existing;
12672
12673        final String resolvedPath;
12674        final File resolvedFile;
12675
12676        static OriginInfo fromNothing() {
12677            return new OriginInfo(null, null, false, false);
12678        }
12679
12680        static OriginInfo fromUntrustedFile(File file) {
12681            return new OriginInfo(file, null, false, false);
12682        }
12683
12684        static OriginInfo fromExistingFile(File file) {
12685            return new OriginInfo(file, null, false, true);
12686        }
12687
12688        static OriginInfo fromStagedFile(File file) {
12689            return new OriginInfo(file, null, true, false);
12690        }
12691
12692        static OriginInfo fromStagedContainer(String cid) {
12693            return new OriginInfo(null, cid, true, false);
12694        }
12695
12696        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12697            this.file = file;
12698            this.cid = cid;
12699            this.staged = staged;
12700            this.existing = existing;
12701
12702            if (cid != null) {
12703                resolvedPath = PackageHelper.getSdDir(cid);
12704                resolvedFile = new File(resolvedPath);
12705            } else if (file != null) {
12706                resolvedPath = file.getAbsolutePath();
12707                resolvedFile = file;
12708            } else {
12709                resolvedPath = null;
12710                resolvedFile = null;
12711            }
12712        }
12713    }
12714
12715    static class MoveInfo {
12716        final int moveId;
12717        final String fromUuid;
12718        final String toUuid;
12719        final String packageName;
12720        final String dataAppName;
12721        final int appId;
12722        final String seinfo;
12723        final int targetSdkVersion;
12724
12725        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12726                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12727            this.moveId = moveId;
12728            this.fromUuid = fromUuid;
12729            this.toUuid = toUuid;
12730            this.packageName = packageName;
12731            this.dataAppName = dataAppName;
12732            this.appId = appId;
12733            this.seinfo = seinfo;
12734            this.targetSdkVersion = targetSdkVersion;
12735        }
12736    }
12737
12738    static class VerificationInfo {
12739        /** A constant used to indicate that a uid value is not present. */
12740        public static final int NO_UID = -1;
12741
12742        /** URI referencing where the package was downloaded from. */
12743        final Uri originatingUri;
12744
12745        /** HTTP referrer URI associated with the originatingURI. */
12746        final Uri referrer;
12747
12748        /** UID of the application that the install request originated from. */
12749        final int originatingUid;
12750
12751        /** UID of application requesting the install */
12752        final int installerUid;
12753
12754        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12755            this.originatingUri = originatingUri;
12756            this.referrer = referrer;
12757            this.originatingUid = originatingUid;
12758            this.installerUid = installerUid;
12759        }
12760    }
12761
12762    class InstallParams extends HandlerParams {
12763        final OriginInfo origin;
12764        final MoveInfo move;
12765        final IPackageInstallObserver2 observer;
12766        int installFlags;
12767        final String installerPackageName;
12768        final String volumeUuid;
12769        private InstallArgs mArgs;
12770        private int mRet;
12771        final String packageAbiOverride;
12772        final String[] grantedRuntimePermissions;
12773        final VerificationInfo verificationInfo;
12774        final Certificate[][] certificates;
12775
12776        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12777                int installFlags, String installerPackageName, String volumeUuid,
12778                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12779                String[] grantedPermissions, Certificate[][] certificates) {
12780            super(user);
12781            this.origin = origin;
12782            this.move = move;
12783            this.observer = observer;
12784            this.installFlags = installFlags;
12785            this.installerPackageName = installerPackageName;
12786            this.volumeUuid = volumeUuid;
12787            this.verificationInfo = verificationInfo;
12788            this.packageAbiOverride = packageAbiOverride;
12789            this.grantedRuntimePermissions = grantedPermissions;
12790            this.certificates = certificates;
12791        }
12792
12793        @Override
12794        public String toString() {
12795            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12796                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12797        }
12798
12799        private int installLocationPolicy(PackageInfoLite pkgLite) {
12800            String packageName = pkgLite.packageName;
12801            int installLocation = pkgLite.installLocation;
12802            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12803            // reader
12804            synchronized (mPackages) {
12805                // Currently installed package which the new package is attempting to replace or
12806                // null if no such package is installed.
12807                PackageParser.Package installedPkg = mPackages.get(packageName);
12808                // Package which currently owns the data which the new package will own if installed.
12809                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12810                // will be null whereas dataOwnerPkg will contain information about the package
12811                // which was uninstalled while keeping its data.
12812                PackageParser.Package dataOwnerPkg = installedPkg;
12813                if (dataOwnerPkg  == null) {
12814                    PackageSetting ps = mSettings.mPackages.get(packageName);
12815                    if (ps != null) {
12816                        dataOwnerPkg = ps.pkg;
12817                    }
12818                }
12819
12820                if (dataOwnerPkg != null) {
12821                    // If installed, the package will get access to data left on the device by its
12822                    // predecessor. As a security measure, this is permited only if this is not a
12823                    // version downgrade or if the predecessor package is marked as debuggable and
12824                    // a downgrade is explicitly requested.
12825                    //
12826                    // On debuggable platform builds, downgrades are permitted even for
12827                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12828                    // not offer security guarantees and thus it's OK to disable some security
12829                    // mechanisms to make debugging/testing easier on those builds. However, even on
12830                    // debuggable builds downgrades of packages are permitted only if requested via
12831                    // installFlags. This is because we aim to keep the behavior of debuggable
12832                    // platform builds as close as possible to the behavior of non-debuggable
12833                    // platform builds.
12834                    final boolean downgradeRequested =
12835                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12836                    final boolean packageDebuggable =
12837                                (dataOwnerPkg.applicationInfo.flags
12838                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12839                    final boolean downgradePermitted =
12840                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12841                    if (!downgradePermitted) {
12842                        try {
12843                            checkDowngrade(dataOwnerPkg, pkgLite);
12844                        } catch (PackageManagerException e) {
12845                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12846                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12847                        }
12848                    }
12849                }
12850
12851                if (installedPkg != null) {
12852                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12853                        // Check for updated system application.
12854                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12855                            if (onSd) {
12856                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12857                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12858                            }
12859                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12860                        } else {
12861                            if (onSd) {
12862                                // Install flag overrides everything.
12863                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12864                            }
12865                            // If current upgrade specifies particular preference
12866                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12867                                // Application explicitly specified internal.
12868                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12869                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12870                                // App explictly prefers external. Let policy decide
12871                            } else {
12872                                // Prefer previous location
12873                                if (isExternal(installedPkg)) {
12874                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12875                                }
12876                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12877                            }
12878                        }
12879                    } else {
12880                        // Invalid install. Return error code
12881                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12882                    }
12883                }
12884            }
12885            // All the special cases have been taken care of.
12886            // Return result based on recommended install location.
12887            if (onSd) {
12888                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12889            }
12890            return pkgLite.recommendedInstallLocation;
12891        }
12892
12893        /*
12894         * Invoke remote method to get package information and install
12895         * location values. Override install location based on default
12896         * policy if needed and then create install arguments based
12897         * on the install location.
12898         */
12899        public void handleStartCopy() throws RemoteException {
12900            int ret = PackageManager.INSTALL_SUCCEEDED;
12901
12902            // If we're already staged, we've firmly committed to an install location
12903            if (origin.staged) {
12904                if (origin.file != null) {
12905                    installFlags |= PackageManager.INSTALL_INTERNAL;
12906                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12907                } else if (origin.cid != null) {
12908                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12909                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12910                } else {
12911                    throw new IllegalStateException("Invalid stage location");
12912                }
12913            }
12914
12915            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12916            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12917            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12918            PackageInfoLite pkgLite = null;
12919
12920            if (onInt && onSd) {
12921                // Check if both bits are set.
12922                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12923                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12924            } else if (onSd && ephemeral) {
12925                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12926                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12927            } else {
12928                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12929                        packageAbiOverride);
12930
12931                if (DEBUG_EPHEMERAL && ephemeral) {
12932                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12933                }
12934
12935                /*
12936                 * If we have too little free space, try to free cache
12937                 * before giving up.
12938                 */
12939                if (!origin.staged && pkgLite.recommendedInstallLocation
12940                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12941                    // TODO: focus freeing disk space on the target device
12942                    final StorageManager storage = StorageManager.from(mContext);
12943                    final long lowThreshold = storage.getStorageLowBytes(
12944                            Environment.getDataDirectory());
12945
12946                    final long sizeBytes = mContainerService.calculateInstalledSize(
12947                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12948
12949                    try {
12950                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12951                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12952                                installFlags, packageAbiOverride);
12953                    } catch (InstallerException e) {
12954                        Slog.w(TAG, "Failed to free cache", e);
12955                    }
12956
12957                    /*
12958                     * The cache free must have deleted the file we
12959                     * downloaded to install.
12960                     *
12961                     * TODO: fix the "freeCache" call to not delete
12962                     *       the file we care about.
12963                     */
12964                    if (pkgLite.recommendedInstallLocation
12965                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12966                        pkgLite.recommendedInstallLocation
12967                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12968                    }
12969                }
12970            }
12971
12972            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12973                int loc = pkgLite.recommendedInstallLocation;
12974                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12975                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12976                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12977                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12978                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12979                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12980                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12981                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12982                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12983                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12984                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12985                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12986                } else {
12987                    // Override with defaults if needed.
12988                    loc = installLocationPolicy(pkgLite);
12989                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12990                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12991                    } else if (!onSd && !onInt) {
12992                        // Override install location with flags
12993                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12994                            // Set the flag to install on external media.
12995                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12996                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12997                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12998                            if (DEBUG_EPHEMERAL) {
12999                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13000                            }
13001                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13002                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13003                                    |PackageManager.INSTALL_INTERNAL);
13004                        } else {
13005                            // Make sure the flag for installing on external
13006                            // media is unset
13007                            installFlags |= PackageManager.INSTALL_INTERNAL;
13008                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13009                        }
13010                    }
13011                }
13012            }
13013
13014            final InstallArgs args = createInstallArgs(this);
13015            mArgs = args;
13016
13017            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13018                // TODO: http://b/22976637
13019                // Apps installed for "all" users use the device owner to verify the app
13020                UserHandle verifierUser = getUser();
13021                if (verifierUser == UserHandle.ALL) {
13022                    verifierUser = UserHandle.SYSTEM;
13023                }
13024
13025                /*
13026                 * Determine if we have any installed package verifiers. If we
13027                 * do, then we'll defer to them to verify the packages.
13028                 */
13029                final int requiredUid = mRequiredVerifierPackage == null ? -1
13030                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13031                                verifierUser.getIdentifier());
13032                if (!origin.existing && requiredUid != -1
13033                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13034                    final Intent verification = new Intent(
13035                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13036                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13037                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13038                            PACKAGE_MIME_TYPE);
13039                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13040
13041                    // Query all live verifiers based on current user state
13042                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13043                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13044
13045                    if (DEBUG_VERIFY) {
13046                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13047                                + verification.toString() + " with " + pkgLite.verifiers.length
13048                                + " optional verifiers");
13049                    }
13050
13051                    final int verificationId = mPendingVerificationToken++;
13052
13053                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13054
13055                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13056                            installerPackageName);
13057
13058                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13059                            installFlags);
13060
13061                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13062                            pkgLite.packageName);
13063
13064                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13065                            pkgLite.versionCode);
13066
13067                    if (verificationInfo != null) {
13068                        if (verificationInfo.originatingUri != null) {
13069                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13070                                    verificationInfo.originatingUri);
13071                        }
13072                        if (verificationInfo.referrer != null) {
13073                            verification.putExtra(Intent.EXTRA_REFERRER,
13074                                    verificationInfo.referrer);
13075                        }
13076                        if (verificationInfo.originatingUid >= 0) {
13077                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13078                                    verificationInfo.originatingUid);
13079                        }
13080                        if (verificationInfo.installerUid >= 0) {
13081                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13082                                    verificationInfo.installerUid);
13083                        }
13084                    }
13085
13086                    final PackageVerificationState verificationState = new PackageVerificationState(
13087                            requiredUid, args);
13088
13089                    mPendingVerification.append(verificationId, verificationState);
13090
13091                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13092                            receivers, verificationState);
13093
13094                    /*
13095                     * If any sufficient verifiers were listed in the package
13096                     * manifest, attempt to ask them.
13097                     */
13098                    if (sufficientVerifiers != null) {
13099                        final int N = sufficientVerifiers.size();
13100                        if (N == 0) {
13101                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13102                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13103                        } else {
13104                            for (int i = 0; i < N; i++) {
13105                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13106
13107                                final Intent sufficientIntent = new Intent(verification);
13108                                sufficientIntent.setComponent(verifierComponent);
13109                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13110                            }
13111                        }
13112                    }
13113
13114                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13115                            mRequiredVerifierPackage, receivers);
13116                    if (ret == PackageManager.INSTALL_SUCCEEDED
13117                            && mRequiredVerifierPackage != null) {
13118                        Trace.asyncTraceBegin(
13119                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13120                        /*
13121                         * Send the intent to the required verification agent,
13122                         * but only start the verification timeout after the
13123                         * target BroadcastReceivers have run.
13124                         */
13125                        verification.setComponent(requiredVerifierComponent);
13126                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13127                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13128                                new BroadcastReceiver() {
13129                                    @Override
13130                                    public void onReceive(Context context, Intent intent) {
13131                                        final Message msg = mHandler
13132                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13133                                        msg.arg1 = verificationId;
13134                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13135                                    }
13136                                }, null, 0, null, null);
13137
13138                        /*
13139                         * We don't want the copy to proceed until verification
13140                         * succeeds, so null out this field.
13141                         */
13142                        mArgs = null;
13143                    }
13144                } else {
13145                    /*
13146                     * No package verification is enabled, so immediately start
13147                     * the remote call to initiate copy using temporary file.
13148                     */
13149                    ret = args.copyApk(mContainerService, true);
13150                }
13151            }
13152
13153            mRet = ret;
13154        }
13155
13156        @Override
13157        void handleReturnCode() {
13158            // If mArgs is null, then MCS couldn't be reached. When it
13159            // reconnects, it will try again to install. At that point, this
13160            // will succeed.
13161            if (mArgs != null) {
13162                processPendingInstall(mArgs, mRet);
13163            }
13164        }
13165
13166        @Override
13167        void handleServiceError() {
13168            mArgs = createInstallArgs(this);
13169            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13170        }
13171
13172        public boolean isForwardLocked() {
13173            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13174        }
13175    }
13176
13177    /**
13178     * Used during creation of InstallArgs
13179     *
13180     * @param installFlags package installation flags
13181     * @return true if should be installed on external storage
13182     */
13183    private static boolean installOnExternalAsec(int installFlags) {
13184        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13185            return false;
13186        }
13187        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13188            return true;
13189        }
13190        return false;
13191    }
13192
13193    /**
13194     * Used during creation of InstallArgs
13195     *
13196     * @param installFlags package installation flags
13197     * @return true if should be installed as forward locked
13198     */
13199    private static boolean installForwardLocked(int installFlags) {
13200        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13201    }
13202
13203    private InstallArgs createInstallArgs(InstallParams params) {
13204        if (params.move != null) {
13205            return new MoveInstallArgs(params);
13206        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13207            return new AsecInstallArgs(params);
13208        } else {
13209            return new FileInstallArgs(params);
13210        }
13211    }
13212
13213    /**
13214     * Create args that describe an existing installed package. Typically used
13215     * when cleaning up old installs, or used as a move source.
13216     */
13217    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13218            String resourcePath, String[] instructionSets) {
13219        final boolean isInAsec;
13220        if (installOnExternalAsec(installFlags)) {
13221            /* Apps on SD card are always in ASEC containers. */
13222            isInAsec = true;
13223        } else if (installForwardLocked(installFlags)
13224                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13225            /*
13226             * Forward-locked apps are only in ASEC containers if they're the
13227             * new style
13228             */
13229            isInAsec = true;
13230        } else {
13231            isInAsec = false;
13232        }
13233
13234        if (isInAsec) {
13235            return new AsecInstallArgs(codePath, instructionSets,
13236                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13237        } else {
13238            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13239        }
13240    }
13241
13242    static abstract class InstallArgs {
13243        /** @see InstallParams#origin */
13244        final OriginInfo origin;
13245        /** @see InstallParams#move */
13246        final MoveInfo move;
13247
13248        final IPackageInstallObserver2 observer;
13249        // Always refers to PackageManager flags only
13250        final int installFlags;
13251        final String installerPackageName;
13252        final String volumeUuid;
13253        final UserHandle user;
13254        final String abiOverride;
13255        final String[] installGrantPermissions;
13256        /** If non-null, drop an async trace when the install completes */
13257        final String traceMethod;
13258        final int traceCookie;
13259        final Certificate[][] certificates;
13260
13261        // The list of instruction sets supported by this app. This is currently
13262        // only used during the rmdex() phase to clean up resources. We can get rid of this
13263        // if we move dex files under the common app path.
13264        /* nullable */ String[] instructionSets;
13265
13266        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13267                int installFlags, String installerPackageName, String volumeUuid,
13268                UserHandle user, String[] instructionSets,
13269                String abiOverride, String[] installGrantPermissions,
13270                String traceMethod, int traceCookie, Certificate[][] certificates) {
13271            this.origin = origin;
13272            this.move = move;
13273            this.installFlags = installFlags;
13274            this.observer = observer;
13275            this.installerPackageName = installerPackageName;
13276            this.volumeUuid = volumeUuid;
13277            this.user = user;
13278            this.instructionSets = instructionSets;
13279            this.abiOverride = abiOverride;
13280            this.installGrantPermissions = installGrantPermissions;
13281            this.traceMethod = traceMethod;
13282            this.traceCookie = traceCookie;
13283            this.certificates = certificates;
13284        }
13285
13286        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13287        abstract int doPreInstall(int status);
13288
13289        /**
13290         * Rename package into final resting place. All paths on the given
13291         * scanned package should be updated to reflect the rename.
13292         */
13293        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13294        abstract int doPostInstall(int status, int uid);
13295
13296        /** @see PackageSettingBase#codePathString */
13297        abstract String getCodePath();
13298        /** @see PackageSettingBase#resourcePathString */
13299        abstract String getResourcePath();
13300
13301        // Need installer lock especially for dex file removal.
13302        abstract void cleanUpResourcesLI();
13303        abstract boolean doPostDeleteLI(boolean delete);
13304
13305        /**
13306         * Called before the source arguments are copied. This is used mostly
13307         * for MoveParams when it needs to read the source file to put it in the
13308         * destination.
13309         */
13310        int doPreCopy() {
13311            return PackageManager.INSTALL_SUCCEEDED;
13312        }
13313
13314        /**
13315         * Called after the source arguments are copied. This is used mostly for
13316         * MoveParams when it needs to read the source file to put it in the
13317         * destination.
13318         */
13319        int doPostCopy(int uid) {
13320            return PackageManager.INSTALL_SUCCEEDED;
13321        }
13322
13323        protected boolean isFwdLocked() {
13324            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13325        }
13326
13327        protected boolean isExternalAsec() {
13328            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13329        }
13330
13331        protected boolean isEphemeral() {
13332            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13333        }
13334
13335        UserHandle getUser() {
13336            return user;
13337        }
13338    }
13339
13340    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13341        if (!allCodePaths.isEmpty()) {
13342            if (instructionSets == null) {
13343                throw new IllegalStateException("instructionSet == null");
13344            }
13345            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13346            for (String codePath : allCodePaths) {
13347                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13348                    try {
13349                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13350                    } catch (InstallerException ignored) {
13351                    }
13352                }
13353            }
13354        }
13355    }
13356
13357    /**
13358     * Logic to handle installation of non-ASEC applications, including copying
13359     * and renaming logic.
13360     */
13361    class FileInstallArgs extends InstallArgs {
13362        private File codeFile;
13363        private File resourceFile;
13364
13365        // Example topology:
13366        // /data/app/com.example/base.apk
13367        // /data/app/com.example/split_foo.apk
13368        // /data/app/com.example/lib/arm/libfoo.so
13369        // /data/app/com.example/lib/arm64/libfoo.so
13370        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13371
13372        /** New install */
13373        FileInstallArgs(InstallParams params) {
13374            super(params.origin, params.move, params.observer, params.installFlags,
13375                    params.installerPackageName, params.volumeUuid,
13376                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13377                    params.grantedRuntimePermissions,
13378                    params.traceMethod, params.traceCookie, params.certificates);
13379            if (isFwdLocked()) {
13380                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13381            }
13382        }
13383
13384        /** Existing install */
13385        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13386            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13387                    null, null, null, 0, null /*certificates*/);
13388            this.codeFile = (codePath != null) ? new File(codePath) : null;
13389            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13390        }
13391
13392        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13393            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13394            try {
13395                return doCopyApk(imcs, temp);
13396            } finally {
13397                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13398            }
13399        }
13400
13401        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13402            if (origin.staged) {
13403                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13404                codeFile = origin.file;
13405                resourceFile = origin.file;
13406                return PackageManager.INSTALL_SUCCEEDED;
13407            }
13408
13409            try {
13410                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13411                final File tempDir =
13412                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13413                codeFile = tempDir;
13414                resourceFile = tempDir;
13415            } catch (IOException e) {
13416                Slog.w(TAG, "Failed to create copy file: " + e);
13417                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13418            }
13419
13420            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13421                @Override
13422                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13423                    if (!FileUtils.isValidExtFilename(name)) {
13424                        throw new IllegalArgumentException("Invalid filename: " + name);
13425                    }
13426                    try {
13427                        final File file = new File(codeFile, name);
13428                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13429                                O_RDWR | O_CREAT, 0644);
13430                        Os.chmod(file.getAbsolutePath(), 0644);
13431                        return new ParcelFileDescriptor(fd);
13432                    } catch (ErrnoException e) {
13433                        throw new RemoteException("Failed to open: " + e.getMessage());
13434                    }
13435                }
13436            };
13437
13438            int ret = PackageManager.INSTALL_SUCCEEDED;
13439            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13440            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13441                Slog.e(TAG, "Failed to copy package");
13442                return ret;
13443            }
13444
13445            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13446            NativeLibraryHelper.Handle handle = null;
13447            try {
13448                handle = NativeLibraryHelper.Handle.create(codeFile);
13449                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13450                        abiOverride);
13451            } catch (IOException e) {
13452                Slog.e(TAG, "Copying native libraries failed", e);
13453                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13454            } finally {
13455                IoUtils.closeQuietly(handle);
13456            }
13457
13458            return ret;
13459        }
13460
13461        int doPreInstall(int status) {
13462            if (status != PackageManager.INSTALL_SUCCEEDED) {
13463                cleanUp();
13464            }
13465            return status;
13466        }
13467
13468        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13469            if (status != PackageManager.INSTALL_SUCCEEDED) {
13470                cleanUp();
13471                return false;
13472            }
13473
13474            final File targetDir = codeFile.getParentFile();
13475            final File beforeCodeFile = codeFile;
13476            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13477
13478            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13479            try {
13480                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13481            } catch (ErrnoException e) {
13482                Slog.w(TAG, "Failed to rename", e);
13483                return false;
13484            }
13485
13486            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13487                Slog.w(TAG, "Failed to restorecon");
13488                return false;
13489            }
13490
13491            // Reflect the rename internally
13492            codeFile = afterCodeFile;
13493            resourceFile = afterCodeFile;
13494
13495            // Reflect the rename in scanned details
13496            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13497            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13498                    afterCodeFile, pkg.baseCodePath));
13499            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13500                    afterCodeFile, pkg.splitCodePaths));
13501
13502            // Reflect the rename in app info
13503            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13504            pkg.setApplicationInfoCodePath(pkg.codePath);
13505            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13506            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13507            pkg.setApplicationInfoResourcePath(pkg.codePath);
13508            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13509            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13510
13511            return true;
13512        }
13513
13514        int doPostInstall(int status, int uid) {
13515            if (status != PackageManager.INSTALL_SUCCEEDED) {
13516                cleanUp();
13517            }
13518            return status;
13519        }
13520
13521        @Override
13522        String getCodePath() {
13523            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13524        }
13525
13526        @Override
13527        String getResourcePath() {
13528            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13529        }
13530
13531        private boolean cleanUp() {
13532            if (codeFile == null || !codeFile.exists()) {
13533                return false;
13534            }
13535
13536            removeCodePathLI(codeFile);
13537
13538            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13539                resourceFile.delete();
13540            }
13541
13542            return true;
13543        }
13544
13545        void cleanUpResourcesLI() {
13546            // Try enumerating all code paths before deleting
13547            List<String> allCodePaths = Collections.EMPTY_LIST;
13548            if (codeFile != null && codeFile.exists()) {
13549                try {
13550                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13551                    allCodePaths = pkg.getAllCodePaths();
13552                } catch (PackageParserException e) {
13553                    // Ignored; we tried our best
13554                }
13555            }
13556
13557            cleanUp();
13558            removeDexFiles(allCodePaths, instructionSets);
13559        }
13560
13561        boolean doPostDeleteLI(boolean delete) {
13562            // XXX err, shouldn't we respect the delete flag?
13563            cleanUpResourcesLI();
13564            return true;
13565        }
13566    }
13567
13568    private boolean isAsecExternal(String cid) {
13569        final String asecPath = PackageHelper.getSdFilesystem(cid);
13570        return !asecPath.startsWith(mAsecInternalPath);
13571    }
13572
13573    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13574            PackageManagerException {
13575        if (copyRet < 0) {
13576            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13577                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13578                throw new PackageManagerException(copyRet, message);
13579            }
13580        }
13581    }
13582
13583    /**
13584     * Extract the MountService "container ID" from the full code path of an
13585     * .apk.
13586     */
13587    static String cidFromCodePath(String fullCodePath) {
13588        int eidx = fullCodePath.lastIndexOf("/");
13589        String subStr1 = fullCodePath.substring(0, eidx);
13590        int sidx = subStr1.lastIndexOf("/");
13591        return subStr1.substring(sidx+1, eidx);
13592    }
13593
13594    /**
13595     * Logic to handle installation of ASEC applications, including copying and
13596     * renaming logic.
13597     */
13598    class AsecInstallArgs extends InstallArgs {
13599        static final String RES_FILE_NAME = "pkg.apk";
13600        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13601
13602        String cid;
13603        String packagePath;
13604        String resourcePath;
13605
13606        /** New install */
13607        AsecInstallArgs(InstallParams params) {
13608            super(params.origin, params.move, params.observer, params.installFlags,
13609                    params.installerPackageName, params.volumeUuid,
13610                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13611                    params.grantedRuntimePermissions,
13612                    params.traceMethod, params.traceCookie, params.certificates);
13613        }
13614
13615        /** Existing install */
13616        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13617                        boolean isExternal, boolean isForwardLocked) {
13618            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13619              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13620                    instructionSets, null, null, null, 0, null /*certificates*/);
13621            // Hackily pretend we're still looking at a full code path
13622            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13623                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13624            }
13625
13626            // Extract cid from fullCodePath
13627            int eidx = fullCodePath.lastIndexOf("/");
13628            String subStr1 = fullCodePath.substring(0, eidx);
13629            int sidx = subStr1.lastIndexOf("/");
13630            cid = subStr1.substring(sidx+1, eidx);
13631            setMountPath(subStr1);
13632        }
13633
13634        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13635            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13636              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13637                    instructionSets, null, null, null, 0, null /*certificates*/);
13638            this.cid = cid;
13639            setMountPath(PackageHelper.getSdDir(cid));
13640        }
13641
13642        void createCopyFile() {
13643            cid = mInstallerService.allocateExternalStageCidLegacy();
13644        }
13645
13646        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13647            if (origin.staged && origin.cid != null) {
13648                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13649                cid = origin.cid;
13650                setMountPath(PackageHelper.getSdDir(cid));
13651                return PackageManager.INSTALL_SUCCEEDED;
13652            }
13653
13654            if (temp) {
13655                createCopyFile();
13656            } else {
13657                /*
13658                 * Pre-emptively destroy the container since it's destroyed if
13659                 * copying fails due to it existing anyway.
13660                 */
13661                PackageHelper.destroySdDir(cid);
13662            }
13663
13664            final String newMountPath = imcs.copyPackageToContainer(
13665                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13666                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13667
13668            if (newMountPath != null) {
13669                setMountPath(newMountPath);
13670                return PackageManager.INSTALL_SUCCEEDED;
13671            } else {
13672                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13673            }
13674        }
13675
13676        @Override
13677        String getCodePath() {
13678            return packagePath;
13679        }
13680
13681        @Override
13682        String getResourcePath() {
13683            return resourcePath;
13684        }
13685
13686        int doPreInstall(int status) {
13687            if (status != PackageManager.INSTALL_SUCCEEDED) {
13688                // Destroy container
13689                PackageHelper.destroySdDir(cid);
13690            } else {
13691                boolean mounted = PackageHelper.isContainerMounted(cid);
13692                if (!mounted) {
13693                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13694                            Process.SYSTEM_UID);
13695                    if (newMountPath != null) {
13696                        setMountPath(newMountPath);
13697                    } else {
13698                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13699                    }
13700                }
13701            }
13702            return status;
13703        }
13704
13705        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13706            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13707            String newMountPath = null;
13708            if (PackageHelper.isContainerMounted(cid)) {
13709                // Unmount the container
13710                if (!PackageHelper.unMountSdDir(cid)) {
13711                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13712                    return false;
13713                }
13714            }
13715            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13716                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13717                        " which might be stale. Will try to clean up.");
13718                // Clean up the stale container and proceed to recreate.
13719                if (!PackageHelper.destroySdDir(newCacheId)) {
13720                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13721                    return false;
13722                }
13723                // Successfully cleaned up stale container. Try to rename again.
13724                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13725                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13726                            + " inspite of cleaning it up.");
13727                    return false;
13728                }
13729            }
13730            if (!PackageHelper.isContainerMounted(newCacheId)) {
13731                Slog.w(TAG, "Mounting container " + newCacheId);
13732                newMountPath = PackageHelper.mountSdDir(newCacheId,
13733                        getEncryptKey(), Process.SYSTEM_UID);
13734            } else {
13735                newMountPath = PackageHelper.getSdDir(newCacheId);
13736            }
13737            if (newMountPath == null) {
13738                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13739                return false;
13740            }
13741            Log.i(TAG, "Succesfully renamed " + cid +
13742                    " to " + newCacheId +
13743                    " at new path: " + newMountPath);
13744            cid = newCacheId;
13745
13746            final File beforeCodeFile = new File(packagePath);
13747            setMountPath(newMountPath);
13748            final File afterCodeFile = new File(packagePath);
13749
13750            // Reflect the rename in scanned details
13751            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13752            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13753                    afterCodeFile, pkg.baseCodePath));
13754            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13755                    afterCodeFile, pkg.splitCodePaths));
13756
13757            // Reflect the rename in app info
13758            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13759            pkg.setApplicationInfoCodePath(pkg.codePath);
13760            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13761            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13762            pkg.setApplicationInfoResourcePath(pkg.codePath);
13763            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13764            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13765
13766            return true;
13767        }
13768
13769        private void setMountPath(String mountPath) {
13770            final File mountFile = new File(mountPath);
13771
13772            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13773            if (monolithicFile.exists()) {
13774                packagePath = monolithicFile.getAbsolutePath();
13775                if (isFwdLocked()) {
13776                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13777                } else {
13778                    resourcePath = packagePath;
13779                }
13780            } else {
13781                packagePath = mountFile.getAbsolutePath();
13782                resourcePath = packagePath;
13783            }
13784        }
13785
13786        int doPostInstall(int status, int uid) {
13787            if (status != PackageManager.INSTALL_SUCCEEDED) {
13788                cleanUp();
13789            } else {
13790                final int groupOwner;
13791                final String protectedFile;
13792                if (isFwdLocked()) {
13793                    groupOwner = UserHandle.getSharedAppGid(uid);
13794                    protectedFile = RES_FILE_NAME;
13795                } else {
13796                    groupOwner = -1;
13797                    protectedFile = null;
13798                }
13799
13800                if (uid < Process.FIRST_APPLICATION_UID
13801                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13802                    Slog.e(TAG, "Failed to finalize " + cid);
13803                    PackageHelper.destroySdDir(cid);
13804                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13805                }
13806
13807                boolean mounted = PackageHelper.isContainerMounted(cid);
13808                if (!mounted) {
13809                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13810                }
13811            }
13812            return status;
13813        }
13814
13815        private void cleanUp() {
13816            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13817
13818            // Destroy secure container
13819            PackageHelper.destroySdDir(cid);
13820        }
13821
13822        private List<String> getAllCodePaths() {
13823            final File codeFile = new File(getCodePath());
13824            if (codeFile != null && codeFile.exists()) {
13825                try {
13826                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13827                    return pkg.getAllCodePaths();
13828                } catch (PackageParserException e) {
13829                    // Ignored; we tried our best
13830                }
13831            }
13832            return Collections.EMPTY_LIST;
13833        }
13834
13835        void cleanUpResourcesLI() {
13836            // Enumerate all code paths before deleting
13837            cleanUpResourcesLI(getAllCodePaths());
13838        }
13839
13840        private void cleanUpResourcesLI(List<String> allCodePaths) {
13841            cleanUp();
13842            removeDexFiles(allCodePaths, instructionSets);
13843        }
13844
13845        String getPackageName() {
13846            return getAsecPackageName(cid);
13847        }
13848
13849        boolean doPostDeleteLI(boolean delete) {
13850            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13851            final List<String> allCodePaths = getAllCodePaths();
13852            boolean mounted = PackageHelper.isContainerMounted(cid);
13853            if (mounted) {
13854                // Unmount first
13855                if (PackageHelper.unMountSdDir(cid)) {
13856                    mounted = false;
13857                }
13858            }
13859            if (!mounted && delete) {
13860                cleanUpResourcesLI(allCodePaths);
13861            }
13862            return !mounted;
13863        }
13864
13865        @Override
13866        int doPreCopy() {
13867            if (isFwdLocked()) {
13868                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13869                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13870                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13871                }
13872            }
13873
13874            return PackageManager.INSTALL_SUCCEEDED;
13875        }
13876
13877        @Override
13878        int doPostCopy(int uid) {
13879            if (isFwdLocked()) {
13880                if (uid < Process.FIRST_APPLICATION_UID
13881                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13882                                RES_FILE_NAME)) {
13883                    Slog.e(TAG, "Failed to finalize " + cid);
13884                    PackageHelper.destroySdDir(cid);
13885                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13886                }
13887            }
13888
13889            return PackageManager.INSTALL_SUCCEEDED;
13890        }
13891    }
13892
13893    /**
13894     * Logic to handle movement of existing installed applications.
13895     */
13896    class MoveInstallArgs extends InstallArgs {
13897        private File codeFile;
13898        private File resourceFile;
13899
13900        /** New install */
13901        MoveInstallArgs(InstallParams params) {
13902            super(params.origin, params.move, params.observer, params.installFlags,
13903                    params.installerPackageName, params.volumeUuid,
13904                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13905                    params.grantedRuntimePermissions,
13906                    params.traceMethod, params.traceCookie, params.certificates);
13907        }
13908
13909        int copyApk(IMediaContainerService imcs, boolean temp) {
13910            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13911                    + move.fromUuid + " to " + move.toUuid);
13912            synchronized (mInstaller) {
13913                try {
13914                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13915                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13916                } catch (InstallerException e) {
13917                    Slog.w(TAG, "Failed to move app", e);
13918                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13919                }
13920            }
13921
13922            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13923            resourceFile = codeFile;
13924            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13925
13926            return PackageManager.INSTALL_SUCCEEDED;
13927        }
13928
13929        int doPreInstall(int status) {
13930            if (status != PackageManager.INSTALL_SUCCEEDED) {
13931                cleanUp(move.toUuid);
13932            }
13933            return status;
13934        }
13935
13936        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13937            if (status != PackageManager.INSTALL_SUCCEEDED) {
13938                cleanUp(move.toUuid);
13939                return false;
13940            }
13941
13942            // Reflect the move in app info
13943            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13944            pkg.setApplicationInfoCodePath(pkg.codePath);
13945            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13946            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13947            pkg.setApplicationInfoResourcePath(pkg.codePath);
13948            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13949            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13950
13951            return true;
13952        }
13953
13954        int doPostInstall(int status, int uid) {
13955            if (status == PackageManager.INSTALL_SUCCEEDED) {
13956                cleanUp(move.fromUuid);
13957            } else {
13958                cleanUp(move.toUuid);
13959            }
13960            return status;
13961        }
13962
13963        @Override
13964        String getCodePath() {
13965            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13966        }
13967
13968        @Override
13969        String getResourcePath() {
13970            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13971        }
13972
13973        private boolean cleanUp(String volumeUuid) {
13974            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13975                    move.dataAppName);
13976            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13977            final int[] userIds = sUserManager.getUserIds();
13978            synchronized (mInstallLock) {
13979                // Clean up both app data and code
13980                // All package moves are frozen until finished
13981                for (int userId : userIds) {
13982                    try {
13983                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13984                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13985                    } catch (InstallerException e) {
13986                        Slog.w(TAG, String.valueOf(e));
13987                    }
13988                }
13989                removeCodePathLI(codeFile);
13990            }
13991            return true;
13992        }
13993
13994        void cleanUpResourcesLI() {
13995            throw new UnsupportedOperationException();
13996        }
13997
13998        boolean doPostDeleteLI(boolean delete) {
13999            throw new UnsupportedOperationException();
14000        }
14001    }
14002
14003    static String getAsecPackageName(String packageCid) {
14004        int idx = packageCid.lastIndexOf("-");
14005        if (idx == -1) {
14006            return packageCid;
14007        }
14008        return packageCid.substring(0, idx);
14009    }
14010
14011    // Utility method used to create code paths based on package name and available index.
14012    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14013        String idxStr = "";
14014        int idx = 1;
14015        // Fall back to default value of idx=1 if prefix is not
14016        // part of oldCodePath
14017        if (oldCodePath != null) {
14018            String subStr = oldCodePath;
14019            // Drop the suffix right away
14020            if (suffix != null && subStr.endsWith(suffix)) {
14021                subStr = subStr.substring(0, subStr.length() - suffix.length());
14022            }
14023            // If oldCodePath already contains prefix find out the
14024            // ending index to either increment or decrement.
14025            int sidx = subStr.lastIndexOf(prefix);
14026            if (sidx != -1) {
14027                subStr = subStr.substring(sidx + prefix.length());
14028                if (subStr != null) {
14029                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14030                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14031                    }
14032                    try {
14033                        idx = Integer.parseInt(subStr);
14034                        if (idx <= 1) {
14035                            idx++;
14036                        } else {
14037                            idx--;
14038                        }
14039                    } catch(NumberFormatException e) {
14040                    }
14041                }
14042            }
14043        }
14044        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14045        return prefix + idxStr;
14046    }
14047
14048    private File getNextCodePath(File targetDir, String packageName) {
14049        int suffix = 1;
14050        File result;
14051        do {
14052            result = new File(targetDir, packageName + "-" + suffix);
14053            suffix++;
14054        } while (result.exists());
14055        return result;
14056    }
14057
14058    // Utility method that returns the relative package path with respect
14059    // to the installation directory. Like say for /data/data/com.test-1.apk
14060    // string com.test-1 is returned.
14061    static String deriveCodePathName(String codePath) {
14062        if (codePath == null) {
14063            return null;
14064        }
14065        final File codeFile = new File(codePath);
14066        final String name = codeFile.getName();
14067        if (codeFile.isDirectory()) {
14068            return name;
14069        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14070            final int lastDot = name.lastIndexOf('.');
14071            return name.substring(0, lastDot);
14072        } else {
14073            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14074            return null;
14075        }
14076    }
14077
14078    static class PackageInstalledInfo {
14079        String name;
14080        int uid;
14081        // The set of users that originally had this package installed.
14082        int[] origUsers;
14083        // The set of users that now have this package installed.
14084        int[] newUsers;
14085        PackageParser.Package pkg;
14086        int returnCode;
14087        String returnMsg;
14088        PackageRemovedInfo removedInfo;
14089        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14090
14091        public void setError(int code, String msg) {
14092            setReturnCode(code);
14093            setReturnMessage(msg);
14094            Slog.w(TAG, msg);
14095        }
14096
14097        public void setError(String msg, PackageParserException e) {
14098            setReturnCode(e.error);
14099            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14100            Slog.w(TAG, msg, e);
14101        }
14102
14103        public void setError(String msg, PackageManagerException e) {
14104            returnCode = e.error;
14105            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14106            Slog.w(TAG, msg, e);
14107        }
14108
14109        public void setReturnCode(int returnCode) {
14110            this.returnCode = returnCode;
14111            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14112            for (int i = 0; i < childCount; i++) {
14113                addedChildPackages.valueAt(i).returnCode = returnCode;
14114            }
14115        }
14116
14117        private void setReturnMessage(String returnMsg) {
14118            this.returnMsg = returnMsg;
14119            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14120            for (int i = 0; i < childCount; i++) {
14121                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14122            }
14123        }
14124
14125        // In some error cases we want to convey more info back to the observer
14126        String origPackage;
14127        String origPermission;
14128    }
14129
14130    /*
14131     * Install a non-existing package.
14132     */
14133    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14134            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14135            PackageInstalledInfo res) {
14136        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14137
14138        // Remember this for later, in case we need to rollback this install
14139        String pkgName = pkg.packageName;
14140
14141        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14142
14143        synchronized(mPackages) {
14144            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14145                // A package with the same name is already installed, though
14146                // it has been renamed to an older name.  The package we
14147                // are trying to install should be installed as an update to
14148                // the existing one, but that has not been requested, so bail.
14149                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14150                        + " without first uninstalling package running as "
14151                        + mSettings.mRenamedPackages.get(pkgName));
14152                return;
14153            }
14154            if (mPackages.containsKey(pkgName)) {
14155                // Don't allow installation over an existing package with the same name.
14156                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14157                        + " without first uninstalling.");
14158                return;
14159            }
14160        }
14161
14162        try {
14163            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14164                    System.currentTimeMillis(), user);
14165
14166            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14167
14168            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14169                prepareAppDataAfterInstallLIF(newPackage);
14170
14171            } else {
14172                // Remove package from internal structures, but keep around any
14173                // data that might have already existed
14174                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14175                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14176            }
14177        } catch (PackageManagerException e) {
14178            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14179        }
14180
14181        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14182    }
14183
14184    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14185        // Can't rotate keys during boot or if sharedUser.
14186        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14187                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14188            return false;
14189        }
14190        // app is using upgradeKeySets; make sure all are valid
14191        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14192        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14193        for (int i = 0; i < upgradeKeySets.length; i++) {
14194            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14195                Slog.wtf(TAG, "Package "
14196                         + (oldPs.name != null ? oldPs.name : "<null>")
14197                         + " contains upgrade-key-set reference to unknown key-set: "
14198                         + upgradeKeySets[i]
14199                         + " reverting to signatures check.");
14200                return false;
14201            }
14202        }
14203        return true;
14204    }
14205
14206    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14207        // Upgrade keysets are being used.  Determine if new package has a superset of the
14208        // required keys.
14209        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14210        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14211        for (int i = 0; i < upgradeKeySets.length; i++) {
14212            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14213            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14214                return true;
14215            }
14216        }
14217        return false;
14218    }
14219
14220    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14221        try (DigestInputStream digestStream =
14222                new DigestInputStream(new FileInputStream(file), digest)) {
14223            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14224        }
14225    }
14226
14227    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14228            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14229        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14230
14231        final PackageParser.Package oldPackage;
14232        final String pkgName = pkg.packageName;
14233        final int[] allUsers;
14234        final int[] installedUsers;
14235
14236        synchronized(mPackages) {
14237            oldPackage = mPackages.get(pkgName);
14238            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14239
14240            // don't allow upgrade to target a release SDK from a pre-release SDK
14241            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14242                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14243            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14244                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14245            if (oldTargetsPreRelease
14246                    && !newTargetsPreRelease
14247                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14248                Slog.w(TAG, "Can't install package targeting released sdk");
14249                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14250                return;
14251            }
14252
14253            // don't allow an upgrade from full to ephemeral
14254            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14255            if (isEphemeral && !oldIsEphemeral) {
14256                // can't downgrade from full to ephemeral
14257                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14258                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14259                return;
14260            }
14261
14262            // verify signatures are valid
14263            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14264            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14265                if (!checkUpgradeKeySetLP(ps, pkg)) {
14266                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14267                            "New package not signed by keys specified by upgrade-keysets: "
14268                                    + pkgName);
14269                    return;
14270                }
14271            } else {
14272                // default to original signature matching
14273                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14274                        != PackageManager.SIGNATURE_MATCH) {
14275                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14276                            "New package has a different signature: " + pkgName);
14277                    return;
14278                }
14279            }
14280
14281            // don't allow a system upgrade unless the upgrade hash matches
14282            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14283                byte[] digestBytes = null;
14284                try {
14285                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14286                    updateDigest(digest, new File(pkg.baseCodePath));
14287                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14288                        for (String path : pkg.splitCodePaths) {
14289                            updateDigest(digest, new File(path));
14290                        }
14291                    }
14292                    digestBytes = digest.digest();
14293                } catch (NoSuchAlgorithmException | IOException e) {
14294                    res.setError(INSTALL_FAILED_INVALID_APK,
14295                            "Could not compute hash: " + pkgName);
14296                    return;
14297                }
14298                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14299                    res.setError(INSTALL_FAILED_INVALID_APK,
14300                            "New package fails restrict-update check: " + pkgName);
14301                    return;
14302                }
14303                // retain upgrade restriction
14304                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14305            }
14306
14307            // Check for shared user id changes
14308            String invalidPackageName =
14309                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14310            if (invalidPackageName != null) {
14311                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14312                        "Package " + invalidPackageName + " tried to change user "
14313                                + oldPackage.mSharedUserId);
14314                return;
14315            }
14316
14317            // In case of rollback, remember per-user/profile install state
14318            allUsers = sUserManager.getUserIds();
14319            installedUsers = ps.queryInstalledUsers(allUsers, true);
14320        }
14321
14322        // Update what is removed
14323        res.removedInfo = new PackageRemovedInfo();
14324        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14325        res.removedInfo.removedPackage = oldPackage.packageName;
14326        res.removedInfo.isUpdate = true;
14327        res.removedInfo.origUsers = installedUsers;
14328        final int childCount = (oldPackage.childPackages != null)
14329                ? oldPackage.childPackages.size() : 0;
14330        for (int i = 0; i < childCount; i++) {
14331            boolean childPackageUpdated = false;
14332            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14333            if (res.addedChildPackages != null) {
14334                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14335                if (childRes != null) {
14336                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14337                    childRes.removedInfo.removedPackage = childPkg.packageName;
14338                    childRes.removedInfo.isUpdate = true;
14339                    childPackageUpdated = true;
14340                }
14341            }
14342            if (!childPackageUpdated) {
14343                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14344                childRemovedRes.removedPackage = childPkg.packageName;
14345                childRemovedRes.isUpdate = false;
14346                childRemovedRes.dataRemoved = true;
14347                synchronized (mPackages) {
14348                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14349                    if (childPs != null) {
14350                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14351                    }
14352                }
14353                if (res.removedInfo.removedChildPackages == null) {
14354                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14355                }
14356                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14357            }
14358        }
14359
14360        boolean sysPkg = (isSystemApp(oldPackage));
14361        if (sysPkg) {
14362            // Set the system/privileged flags as needed
14363            final boolean privileged =
14364                    (oldPackage.applicationInfo.privateFlags
14365                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14366            final int systemPolicyFlags = policyFlags
14367                    | PackageParser.PARSE_IS_SYSTEM
14368                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14369
14370            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14371                    user, allUsers, installerPackageName, res);
14372        } else {
14373            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14374                    user, allUsers, installerPackageName, res);
14375        }
14376    }
14377
14378    public List<String> getPreviousCodePaths(String packageName) {
14379        final PackageSetting ps = mSettings.mPackages.get(packageName);
14380        final List<String> result = new ArrayList<String>();
14381        if (ps != null && ps.oldCodePaths != null) {
14382            result.addAll(ps.oldCodePaths);
14383        }
14384        return result;
14385    }
14386
14387    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14388            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14389            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14390        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14391                + deletedPackage);
14392
14393        String pkgName = deletedPackage.packageName;
14394        boolean deletedPkg = true;
14395        boolean addedPkg = false;
14396        boolean updatedSettings = false;
14397        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14398        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14399                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14400
14401        final long origUpdateTime = (pkg.mExtras != null)
14402                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14403
14404        // First delete the existing package while retaining the data directory
14405        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14406                res.removedInfo, true, pkg)) {
14407            // If the existing package wasn't successfully deleted
14408            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14409            deletedPkg = false;
14410        } else {
14411            // Successfully deleted the old package; proceed with replace.
14412
14413            // If deleted package lived in a container, give users a chance to
14414            // relinquish resources before killing.
14415            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14416                if (DEBUG_INSTALL) {
14417                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14418                }
14419                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14420                final ArrayList<String> pkgList = new ArrayList<String>(1);
14421                pkgList.add(deletedPackage.applicationInfo.packageName);
14422                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14423            }
14424
14425            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14426                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14427            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14428
14429            try {
14430                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14431                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14432                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14433
14434                // Update the in-memory copy of the previous code paths.
14435                PackageSetting ps = mSettings.mPackages.get(pkgName);
14436                if (!killApp) {
14437                    if (ps.oldCodePaths == null) {
14438                        ps.oldCodePaths = new ArraySet<>();
14439                    }
14440                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14441                    if (deletedPackage.splitCodePaths != null) {
14442                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14443                    }
14444                } else {
14445                    ps.oldCodePaths = null;
14446                }
14447                if (ps.childPackageNames != null) {
14448                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14449                        final String childPkgName = ps.childPackageNames.get(i);
14450                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14451                        childPs.oldCodePaths = ps.oldCodePaths;
14452                    }
14453                }
14454                prepareAppDataAfterInstallLIF(newPackage);
14455                addedPkg = true;
14456            } catch (PackageManagerException e) {
14457                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14458            }
14459        }
14460
14461        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14462            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14463
14464            // Revert all internal state mutations and added folders for the failed install
14465            if (addedPkg) {
14466                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14467                        res.removedInfo, true, null);
14468            }
14469
14470            // Restore the old package
14471            if (deletedPkg) {
14472                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14473                File restoreFile = new File(deletedPackage.codePath);
14474                // Parse old package
14475                boolean oldExternal = isExternal(deletedPackage);
14476                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14477                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14478                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14479                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14480                try {
14481                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14482                            null);
14483                } catch (PackageManagerException e) {
14484                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14485                            + e.getMessage());
14486                    return;
14487                }
14488
14489                synchronized (mPackages) {
14490                    // Ensure the installer package name up to date
14491                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14492
14493                    // Update permissions for restored package
14494                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14495
14496                    mSettings.writeLPr();
14497                }
14498
14499                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14500            }
14501        } else {
14502            synchronized (mPackages) {
14503                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14504                if (ps != null) {
14505                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14506                    if (res.removedInfo.removedChildPackages != null) {
14507                        final int childCount = res.removedInfo.removedChildPackages.size();
14508                        // Iterate in reverse as we may modify the collection
14509                        for (int i = childCount - 1; i >= 0; i--) {
14510                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14511                            if (res.addedChildPackages.containsKey(childPackageName)) {
14512                                res.removedInfo.removedChildPackages.removeAt(i);
14513                            } else {
14514                                PackageRemovedInfo childInfo = res.removedInfo
14515                                        .removedChildPackages.valueAt(i);
14516                                childInfo.removedForAllUsers = mPackages.get(
14517                                        childInfo.removedPackage) == null;
14518                            }
14519                        }
14520                    }
14521                }
14522            }
14523        }
14524    }
14525
14526    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14527            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14528            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14529        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14530                + ", old=" + deletedPackage);
14531
14532        final boolean disabledSystem;
14533
14534        // Remove existing system package
14535        removePackageLI(deletedPackage, true);
14536
14537        synchronized (mPackages) {
14538            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14539        }
14540        if (!disabledSystem) {
14541            // We didn't need to disable the .apk as a current system package,
14542            // which means we are replacing another update that is already
14543            // installed.  We need to make sure to delete the older one's .apk.
14544            res.removedInfo.args = createInstallArgsForExisting(0,
14545                    deletedPackage.applicationInfo.getCodePath(),
14546                    deletedPackage.applicationInfo.getResourcePath(),
14547                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14548        } else {
14549            res.removedInfo.args = null;
14550        }
14551
14552        // Successfully disabled the old package. Now proceed with re-installation
14553        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14554                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14555        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14556
14557        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14558        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14559                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14560
14561        PackageParser.Package newPackage = null;
14562        try {
14563            // Add the package to the internal data structures
14564            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14565
14566            // Set the update and install times
14567            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14568            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14569                    System.currentTimeMillis());
14570
14571            // Update the package dynamic state if succeeded
14572            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14573                // Now that the install succeeded make sure we remove data
14574                // directories for any child package the update removed.
14575                final int deletedChildCount = (deletedPackage.childPackages != null)
14576                        ? deletedPackage.childPackages.size() : 0;
14577                final int newChildCount = (newPackage.childPackages != null)
14578                        ? newPackage.childPackages.size() : 0;
14579                for (int i = 0; i < deletedChildCount; i++) {
14580                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14581                    boolean childPackageDeleted = true;
14582                    for (int j = 0; j < newChildCount; j++) {
14583                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14584                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14585                            childPackageDeleted = false;
14586                            break;
14587                        }
14588                    }
14589                    if (childPackageDeleted) {
14590                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14591                                deletedChildPkg.packageName);
14592                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14593                            PackageRemovedInfo removedChildRes = res.removedInfo
14594                                    .removedChildPackages.get(deletedChildPkg.packageName);
14595                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14596                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14597                        }
14598                    }
14599                }
14600
14601                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14602                prepareAppDataAfterInstallLIF(newPackage);
14603            }
14604        } catch (PackageManagerException e) {
14605            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14606            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14607        }
14608
14609        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14610            // Re installation failed. Restore old information
14611            // Remove new pkg information
14612            if (newPackage != null) {
14613                removeInstalledPackageLI(newPackage, true);
14614            }
14615            // Add back the old system package
14616            try {
14617                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14618            } catch (PackageManagerException e) {
14619                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14620            }
14621
14622            synchronized (mPackages) {
14623                if (disabledSystem) {
14624                    enableSystemPackageLPw(deletedPackage);
14625                }
14626
14627                // Ensure the installer package name up to date
14628                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14629
14630                // Update permissions for restored package
14631                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14632
14633                mSettings.writeLPr();
14634            }
14635
14636            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14637                    + " after failed upgrade");
14638        }
14639    }
14640
14641    /**
14642     * Checks whether the parent or any of the child packages have a change shared
14643     * user. For a package to be a valid update the shred users of the parent and
14644     * the children should match. We may later support changing child shared users.
14645     * @param oldPkg The updated package.
14646     * @param newPkg The update package.
14647     * @return The shared user that change between the versions.
14648     */
14649    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14650            PackageParser.Package newPkg) {
14651        // Check parent shared user
14652        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14653            return newPkg.packageName;
14654        }
14655        // Check child shared users
14656        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14657        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14658        for (int i = 0; i < newChildCount; i++) {
14659            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14660            // If this child was present, did it have the same shared user?
14661            for (int j = 0; j < oldChildCount; j++) {
14662                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14663                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14664                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14665                    return newChildPkg.packageName;
14666                }
14667            }
14668        }
14669        return null;
14670    }
14671
14672    private void removeNativeBinariesLI(PackageSetting ps) {
14673        // Remove the lib path for the parent package
14674        if (ps != null) {
14675            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14676            // Remove the lib path for the child packages
14677            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14678            for (int i = 0; i < childCount; i++) {
14679                PackageSetting childPs = null;
14680                synchronized (mPackages) {
14681                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14682                }
14683                if (childPs != null) {
14684                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14685                            .legacyNativeLibraryPathString);
14686                }
14687            }
14688        }
14689    }
14690
14691    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14692        // Enable the parent package
14693        mSettings.enableSystemPackageLPw(pkg.packageName);
14694        // Enable the child packages
14695        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14696        for (int i = 0; i < childCount; i++) {
14697            PackageParser.Package childPkg = pkg.childPackages.get(i);
14698            mSettings.enableSystemPackageLPw(childPkg.packageName);
14699        }
14700    }
14701
14702    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14703            PackageParser.Package newPkg) {
14704        // Disable the parent package (parent always replaced)
14705        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14706        // Disable the child packages
14707        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14708        for (int i = 0; i < childCount; i++) {
14709            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14710            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14711            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14712        }
14713        return disabled;
14714    }
14715
14716    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14717            String installerPackageName) {
14718        // Enable the parent package
14719        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14720        // Enable the child packages
14721        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14722        for (int i = 0; i < childCount; i++) {
14723            PackageParser.Package childPkg = pkg.childPackages.get(i);
14724            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14725        }
14726    }
14727
14728    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14729        // Collect all used permissions in the UID
14730        ArraySet<String> usedPermissions = new ArraySet<>();
14731        final int packageCount = su.packages.size();
14732        for (int i = 0; i < packageCount; i++) {
14733            PackageSetting ps = su.packages.valueAt(i);
14734            if (ps.pkg == null) {
14735                continue;
14736            }
14737            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14738            for (int j = 0; j < requestedPermCount; j++) {
14739                String permission = ps.pkg.requestedPermissions.get(j);
14740                BasePermission bp = mSettings.mPermissions.get(permission);
14741                if (bp != null) {
14742                    usedPermissions.add(permission);
14743                }
14744            }
14745        }
14746
14747        PermissionsState permissionsState = su.getPermissionsState();
14748        // Prune install permissions
14749        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14750        final int installPermCount = installPermStates.size();
14751        for (int i = installPermCount - 1; i >= 0;  i--) {
14752            PermissionState permissionState = installPermStates.get(i);
14753            if (!usedPermissions.contains(permissionState.getName())) {
14754                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14755                if (bp != null) {
14756                    permissionsState.revokeInstallPermission(bp);
14757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14759                }
14760            }
14761        }
14762
14763        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14764
14765        // Prune runtime permissions
14766        for (int userId : allUserIds) {
14767            List<PermissionState> runtimePermStates = permissionsState
14768                    .getRuntimePermissionStates(userId);
14769            final int runtimePermCount = runtimePermStates.size();
14770            for (int i = runtimePermCount - 1; i >= 0; i--) {
14771                PermissionState permissionState = runtimePermStates.get(i);
14772                if (!usedPermissions.contains(permissionState.getName())) {
14773                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14774                    if (bp != null) {
14775                        permissionsState.revokeRuntimePermission(bp, userId);
14776                        permissionsState.updatePermissionFlags(bp, userId,
14777                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14778                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14779                                runtimePermissionChangedUserIds, userId);
14780                    }
14781                }
14782            }
14783        }
14784
14785        return runtimePermissionChangedUserIds;
14786    }
14787
14788    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14789            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14790        // Update the parent package setting
14791        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14792                res, user);
14793        // Update the child packages setting
14794        final int childCount = (newPackage.childPackages != null)
14795                ? newPackage.childPackages.size() : 0;
14796        for (int i = 0; i < childCount; i++) {
14797            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14798            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14799            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14800                    childRes.origUsers, childRes, user);
14801        }
14802    }
14803
14804    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14805            String installerPackageName, int[] allUsers, int[] installedForUsers,
14806            PackageInstalledInfo res, UserHandle user) {
14807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14808
14809        String pkgName = newPackage.packageName;
14810        synchronized (mPackages) {
14811            //write settings. the installStatus will be incomplete at this stage.
14812            //note that the new package setting would have already been
14813            //added to mPackages. It hasn't been persisted yet.
14814            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14816            mSettings.writeLPr();
14817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14818        }
14819
14820        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14821        synchronized (mPackages) {
14822            updatePermissionsLPw(newPackage.packageName, newPackage,
14823                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14824                            ? UPDATE_PERMISSIONS_ALL : 0));
14825            // For system-bundled packages, we assume that installing an upgraded version
14826            // of the package implies that the user actually wants to run that new code,
14827            // so we enable the package.
14828            PackageSetting ps = mSettings.mPackages.get(pkgName);
14829            final int userId = user.getIdentifier();
14830            if (ps != null) {
14831                if (isSystemApp(newPackage)) {
14832                    if (DEBUG_INSTALL) {
14833                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14834                    }
14835                    // Enable system package for requested users
14836                    if (res.origUsers != null) {
14837                        for (int origUserId : res.origUsers) {
14838                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14839                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14840                                        origUserId, installerPackageName);
14841                            }
14842                        }
14843                    }
14844                    // Also convey the prior install/uninstall state
14845                    if (allUsers != null && installedForUsers != null) {
14846                        for (int currentUserId : allUsers) {
14847                            final boolean installed = ArrayUtils.contains(
14848                                    installedForUsers, currentUserId);
14849                            if (DEBUG_INSTALL) {
14850                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14851                            }
14852                            ps.setInstalled(installed, currentUserId);
14853                        }
14854                        // these install state changes will be persisted in the
14855                        // upcoming call to mSettings.writeLPr().
14856                    }
14857                }
14858                // It's implied that when a user requests installation, they want the app to be
14859                // installed and enabled.
14860                if (userId != UserHandle.USER_ALL) {
14861                    ps.setInstalled(true, userId);
14862                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14863                }
14864            }
14865            res.name = pkgName;
14866            res.uid = newPackage.applicationInfo.uid;
14867            res.pkg = newPackage;
14868            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14869            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14870            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14871            //to update install status
14872            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14873            mSettings.writeLPr();
14874            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14875        }
14876
14877        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14878    }
14879
14880    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14881        try {
14882            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14883            installPackageLI(args, res);
14884        } finally {
14885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14886        }
14887    }
14888
14889    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14890        final int installFlags = args.installFlags;
14891        final String installerPackageName = args.installerPackageName;
14892        final String volumeUuid = args.volumeUuid;
14893        final File tmpPackageFile = new File(args.getCodePath());
14894        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14895        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14896                || (args.volumeUuid != null));
14897        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14898        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14899        boolean replace = false;
14900        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14901        if (args.move != null) {
14902            // moving a complete application; perform an initial scan on the new install location
14903            scanFlags |= SCAN_INITIAL;
14904        }
14905        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14906            scanFlags |= SCAN_DONT_KILL_APP;
14907        }
14908
14909        // Result object to be returned
14910        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14911
14912        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14913
14914        // Sanity check
14915        if (ephemeral && (forwardLocked || onExternal)) {
14916            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14917                    + " external=" + onExternal);
14918            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14919            return;
14920        }
14921
14922        // Retrieve PackageSettings and parse package
14923        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14924                | PackageParser.PARSE_ENFORCE_CODE
14925                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14926                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14927                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14928                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14929        PackageParser pp = new PackageParser();
14930        pp.setSeparateProcesses(mSeparateProcesses);
14931        pp.setDisplayMetrics(mMetrics);
14932
14933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14934        final PackageParser.Package pkg;
14935        try {
14936            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14937        } catch (PackageParserException e) {
14938            res.setError("Failed parse during installPackageLI", e);
14939            return;
14940        } finally {
14941            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14942        }
14943
14944        // If we are installing a clustered package add results for the children
14945        if (pkg.childPackages != null) {
14946            synchronized (mPackages) {
14947                final int childCount = pkg.childPackages.size();
14948                for (int i = 0; i < childCount; i++) {
14949                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14950                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14951                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14952                    childRes.pkg = childPkg;
14953                    childRes.name = childPkg.packageName;
14954                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14955                    if (childPs != null) {
14956                        childRes.origUsers = childPs.queryInstalledUsers(
14957                                sUserManager.getUserIds(), true);
14958                    }
14959                    if ((mPackages.containsKey(childPkg.packageName))) {
14960                        childRes.removedInfo = new PackageRemovedInfo();
14961                        childRes.removedInfo.removedPackage = childPkg.packageName;
14962                    }
14963                    if (res.addedChildPackages == null) {
14964                        res.addedChildPackages = new ArrayMap<>();
14965                    }
14966                    res.addedChildPackages.put(childPkg.packageName, childRes);
14967                }
14968            }
14969        }
14970
14971        // If package doesn't declare API override, mark that we have an install
14972        // time CPU ABI override.
14973        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14974            pkg.cpuAbiOverride = args.abiOverride;
14975        }
14976
14977        String pkgName = res.name = pkg.packageName;
14978        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14979            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14980                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14981                return;
14982            }
14983        }
14984
14985        try {
14986            // either use what we've been given or parse directly from the APK
14987            if (args.certificates != null) {
14988                try {
14989                    PackageParser.populateCertificates(pkg, args.certificates);
14990                } catch (PackageParserException e) {
14991                    // there was something wrong with the certificates we were given;
14992                    // try to pull them from the APK
14993                    PackageParser.collectCertificates(pkg, parseFlags);
14994                }
14995            } else {
14996                PackageParser.collectCertificates(pkg, parseFlags);
14997            }
14998        } catch (PackageParserException e) {
14999            res.setError("Failed collect during installPackageLI", e);
15000            return;
15001        }
15002
15003        // Get rid of all references to package scan path via parser.
15004        pp = null;
15005        String oldCodePath = null;
15006        boolean systemApp = false;
15007        synchronized (mPackages) {
15008            // Check if installing already existing package
15009            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15010                String oldName = mSettings.mRenamedPackages.get(pkgName);
15011                if (pkg.mOriginalPackages != null
15012                        && pkg.mOriginalPackages.contains(oldName)
15013                        && mPackages.containsKey(oldName)) {
15014                    // This package is derived from an original package,
15015                    // and this device has been updating from that original
15016                    // name.  We must continue using the original name, so
15017                    // rename the new package here.
15018                    pkg.setPackageName(oldName);
15019                    pkgName = pkg.packageName;
15020                    replace = true;
15021                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15022                            + oldName + " pkgName=" + pkgName);
15023                } else if (mPackages.containsKey(pkgName)) {
15024                    // This package, under its official name, already exists
15025                    // on the device; we should replace it.
15026                    replace = true;
15027                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15028                }
15029
15030                // Child packages are installed through the parent package
15031                if (pkg.parentPackage != null) {
15032                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15033                            "Package " + pkg.packageName + " is child of package "
15034                                    + pkg.parentPackage.parentPackage + ". Child packages "
15035                                    + "can be updated only through the parent package.");
15036                    return;
15037                }
15038
15039                if (replace) {
15040                    // Prevent apps opting out from runtime permissions
15041                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15042                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15043                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15044                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15045                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15046                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15047                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15048                                        + " doesn't support runtime permissions but the old"
15049                                        + " target SDK " + oldTargetSdk + " does.");
15050                        return;
15051                    }
15052
15053                    // Prevent installing of child packages
15054                    if (oldPackage.parentPackage != null) {
15055                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15056                                "Package " + pkg.packageName + " is child of package "
15057                                        + oldPackage.parentPackage + ". Child packages "
15058                                        + "can be updated only through the parent package.");
15059                        return;
15060                    }
15061                }
15062            }
15063
15064            PackageSetting ps = mSettings.mPackages.get(pkgName);
15065            if (ps != null) {
15066                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15067
15068                // Quick sanity check that we're signed correctly if updating;
15069                // we'll check this again later when scanning, but we want to
15070                // bail early here before tripping over redefined permissions.
15071                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15072                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15073                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15074                                + pkg.packageName + " upgrade keys do not match the "
15075                                + "previously installed version");
15076                        return;
15077                    }
15078                } else {
15079                    try {
15080                        verifySignaturesLP(ps, pkg);
15081                    } catch (PackageManagerException e) {
15082                        res.setError(e.error, e.getMessage());
15083                        return;
15084                    }
15085                }
15086
15087                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15088                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15089                    systemApp = (ps.pkg.applicationInfo.flags &
15090                            ApplicationInfo.FLAG_SYSTEM) != 0;
15091                }
15092                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15093            }
15094
15095            // Check whether the newly-scanned package wants to define an already-defined perm
15096            int N = pkg.permissions.size();
15097            for (int i = N-1; i >= 0; i--) {
15098                PackageParser.Permission perm = pkg.permissions.get(i);
15099                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15100                if (bp != null) {
15101                    // If the defining package is signed with our cert, it's okay.  This
15102                    // also includes the "updating the same package" case, of course.
15103                    // "updating same package" could also involve key-rotation.
15104                    final boolean sigsOk;
15105                    if (bp.sourcePackage.equals(pkg.packageName)
15106                            && (bp.packageSetting instanceof PackageSetting)
15107                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15108                                    scanFlags))) {
15109                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15110                    } else {
15111                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15112                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15113                    }
15114                    if (!sigsOk) {
15115                        // If the owning package is the system itself, we log but allow
15116                        // install to proceed; we fail the install on all other permission
15117                        // redefinitions.
15118                        if (!bp.sourcePackage.equals("android")) {
15119                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15120                                    + pkg.packageName + " attempting to redeclare permission "
15121                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15122                            res.origPermission = perm.info.name;
15123                            res.origPackage = bp.sourcePackage;
15124                            return;
15125                        } else {
15126                            Slog.w(TAG, "Package " + pkg.packageName
15127                                    + " attempting to redeclare system permission "
15128                                    + perm.info.name + "; ignoring new declaration");
15129                            pkg.permissions.remove(i);
15130                        }
15131                    }
15132                }
15133            }
15134        }
15135
15136        if (systemApp) {
15137            if (onExternal) {
15138                // Abort update; system app can't be replaced with app on sdcard
15139                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15140                        "Cannot install updates to system apps on sdcard");
15141                return;
15142            } else if (ephemeral) {
15143                // Abort update; system app can't be replaced with an ephemeral app
15144                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15145                        "Cannot update a system app with an ephemeral app");
15146                return;
15147            }
15148        }
15149
15150        if (args.move != null) {
15151            // We did an in-place move, so dex is ready to roll
15152            scanFlags |= SCAN_NO_DEX;
15153            scanFlags |= SCAN_MOVE;
15154
15155            synchronized (mPackages) {
15156                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15157                if (ps == null) {
15158                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15159                            "Missing settings for moved package " + pkgName);
15160                }
15161
15162                // We moved the entire application as-is, so bring over the
15163                // previously derived ABI information.
15164                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15165                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15166            }
15167
15168        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15169            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15170            scanFlags |= SCAN_NO_DEX;
15171
15172            try {
15173                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15174                    args.abiOverride : pkg.cpuAbiOverride);
15175                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15176                        true /* extract libs */);
15177            } catch (PackageManagerException pme) {
15178                Slog.e(TAG, "Error deriving application ABI", pme);
15179                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15180                return;
15181            }
15182
15183            // Shared libraries for the package need to be updated.
15184            synchronized (mPackages) {
15185                try {
15186                    updateSharedLibrariesLPw(pkg, null);
15187                } catch (PackageManagerException e) {
15188                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15189                }
15190            }
15191            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15192            // Do not run PackageDexOptimizer through the local performDexOpt
15193            // method because `pkg` may not be in `mPackages` yet.
15194            //
15195            // Also, don't fail application installs if the dexopt step fails.
15196            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15197                    null /* instructionSets */, false /* checkProfiles */,
15198                    getCompilerFilterForReason(REASON_INSTALL),
15199                    getOrCreateCompilerPackageStats(pkg));
15200            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15201
15202            // Notify BackgroundDexOptService that the package has been changed.
15203            // If this is an update of a package which used to fail to compile,
15204            // BDOS will remove it from its blacklist.
15205            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15206        }
15207
15208        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15209            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15210            return;
15211        }
15212
15213        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15214
15215        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15216                "installPackageLI")) {
15217            if (replace) {
15218                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15219                        installerPackageName, res);
15220            } else {
15221                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15222                        args.user, installerPackageName, volumeUuid, res);
15223            }
15224        }
15225        synchronized (mPackages) {
15226            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15227            if (ps != null) {
15228                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15229            }
15230
15231            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15232            for (int i = 0; i < childCount; i++) {
15233                PackageParser.Package childPkg = pkg.childPackages.get(i);
15234                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15235                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15236                if (childPs != null) {
15237                    childRes.newUsers = childPs.queryInstalledUsers(
15238                            sUserManager.getUserIds(), true);
15239                }
15240            }
15241        }
15242    }
15243
15244    private void startIntentFilterVerifications(int userId, boolean replacing,
15245            PackageParser.Package pkg) {
15246        if (mIntentFilterVerifierComponent == null) {
15247            Slog.w(TAG, "No IntentFilter verification will not be done as "
15248                    + "there is no IntentFilterVerifier available!");
15249            return;
15250        }
15251
15252        final int verifierUid = getPackageUid(
15253                mIntentFilterVerifierComponent.getPackageName(),
15254                MATCH_DEBUG_TRIAGED_MISSING,
15255                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15256
15257        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15258        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15259        mHandler.sendMessage(msg);
15260
15261        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15262        for (int i = 0; i < childCount; i++) {
15263            PackageParser.Package childPkg = pkg.childPackages.get(i);
15264            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15265            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15266            mHandler.sendMessage(msg);
15267        }
15268    }
15269
15270    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15271            PackageParser.Package pkg) {
15272        int size = pkg.activities.size();
15273        if (size == 0) {
15274            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15275                    "No activity, so no need to verify any IntentFilter!");
15276            return;
15277        }
15278
15279        final boolean hasDomainURLs = hasDomainURLs(pkg);
15280        if (!hasDomainURLs) {
15281            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15282                    "No domain URLs, so no need to verify any IntentFilter!");
15283            return;
15284        }
15285
15286        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15287                + " if any IntentFilter from the " + size
15288                + " Activities needs verification ...");
15289
15290        int count = 0;
15291        final String packageName = pkg.packageName;
15292
15293        synchronized (mPackages) {
15294            // If this is a new install and we see that we've already run verification for this
15295            // package, we have nothing to do: it means the state was restored from backup.
15296            if (!replacing) {
15297                IntentFilterVerificationInfo ivi =
15298                        mSettings.getIntentFilterVerificationLPr(packageName);
15299                if (ivi != null) {
15300                    if (DEBUG_DOMAIN_VERIFICATION) {
15301                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15302                                + ivi.getStatusString());
15303                    }
15304                    return;
15305                }
15306            }
15307
15308            // If any filters need to be verified, then all need to be.
15309            boolean needToVerify = false;
15310            for (PackageParser.Activity a : pkg.activities) {
15311                for (ActivityIntentInfo filter : a.intents) {
15312                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15313                        if (DEBUG_DOMAIN_VERIFICATION) {
15314                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15315                        }
15316                        needToVerify = true;
15317                        break;
15318                    }
15319                }
15320            }
15321
15322            if (needToVerify) {
15323                final int verificationId = mIntentFilterVerificationToken++;
15324                for (PackageParser.Activity a : pkg.activities) {
15325                    for (ActivityIntentInfo filter : a.intents) {
15326                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15327                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15328                                    "Verification needed for IntentFilter:" + filter.toString());
15329                            mIntentFilterVerifier.addOneIntentFilterVerification(
15330                                    verifierUid, userId, verificationId, filter, packageName);
15331                            count++;
15332                        }
15333                    }
15334                }
15335            }
15336        }
15337
15338        if (count > 0) {
15339            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15340                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15341                    +  " for userId:" + userId);
15342            mIntentFilterVerifier.startVerifications(userId);
15343        } else {
15344            if (DEBUG_DOMAIN_VERIFICATION) {
15345                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15346            }
15347        }
15348    }
15349
15350    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15351        final ComponentName cn  = filter.activity.getComponentName();
15352        final String packageName = cn.getPackageName();
15353
15354        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15355                packageName);
15356        if (ivi == null) {
15357            return true;
15358        }
15359        int status = ivi.getStatus();
15360        switch (status) {
15361            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15362            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15363                return true;
15364
15365            default:
15366                // Nothing to do
15367                return false;
15368        }
15369    }
15370
15371    private static boolean isMultiArch(ApplicationInfo info) {
15372        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15373    }
15374
15375    private static boolean isExternal(PackageParser.Package pkg) {
15376        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15377    }
15378
15379    private static boolean isExternal(PackageSetting ps) {
15380        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15381    }
15382
15383    private static boolean isEphemeral(PackageParser.Package pkg) {
15384        return pkg.applicationInfo.isEphemeralApp();
15385    }
15386
15387    private static boolean isEphemeral(PackageSetting ps) {
15388        return ps.pkg != null && isEphemeral(ps.pkg);
15389    }
15390
15391    private static boolean isSystemApp(PackageParser.Package pkg) {
15392        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15393    }
15394
15395    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15396        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15397    }
15398
15399    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15400        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15401    }
15402
15403    private static boolean isSystemApp(PackageSetting ps) {
15404        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15405    }
15406
15407    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15408        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15409    }
15410
15411    private int packageFlagsToInstallFlags(PackageSetting ps) {
15412        int installFlags = 0;
15413        if (isEphemeral(ps)) {
15414            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15415        }
15416        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15417            // This existing package was an external ASEC install when we have
15418            // the external flag without a UUID
15419            installFlags |= PackageManager.INSTALL_EXTERNAL;
15420        }
15421        if (ps.isForwardLocked()) {
15422            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15423        }
15424        return installFlags;
15425    }
15426
15427    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15428        if (isExternal(pkg)) {
15429            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15430                return StorageManager.UUID_PRIMARY_PHYSICAL;
15431            } else {
15432                return pkg.volumeUuid;
15433            }
15434        } else {
15435            return StorageManager.UUID_PRIVATE_INTERNAL;
15436        }
15437    }
15438
15439    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15440        if (isExternal(pkg)) {
15441            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15442                return mSettings.getExternalVersion();
15443            } else {
15444                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15445            }
15446        } else {
15447            return mSettings.getInternalVersion();
15448        }
15449    }
15450
15451    private void deleteTempPackageFiles() {
15452        final FilenameFilter filter = new FilenameFilter() {
15453            public boolean accept(File dir, String name) {
15454                return name.startsWith("vmdl") && name.endsWith(".tmp");
15455            }
15456        };
15457        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15458            file.delete();
15459        }
15460    }
15461
15462    @Override
15463    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15464            int flags) {
15465        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15466                flags);
15467    }
15468
15469    @Override
15470    public void deletePackage(final String packageName,
15471            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15472        mContext.enforceCallingOrSelfPermission(
15473                android.Manifest.permission.DELETE_PACKAGES, null);
15474        Preconditions.checkNotNull(packageName);
15475        Preconditions.checkNotNull(observer);
15476        final int uid = Binder.getCallingUid();
15477        if (!isOrphaned(packageName)
15478                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15479            try {
15480                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15481                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15482                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15483                observer.onUserActionRequired(intent);
15484            } catch (RemoteException re) {
15485            }
15486            return;
15487        }
15488        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15489        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15490        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15491            mContext.enforceCallingOrSelfPermission(
15492                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15493                    "deletePackage for user " + userId);
15494        }
15495
15496        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15497            try {
15498                observer.onPackageDeleted(packageName,
15499                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15500            } catch (RemoteException re) {
15501            }
15502            return;
15503        }
15504
15505        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15506            try {
15507                observer.onPackageDeleted(packageName,
15508                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15509            } catch (RemoteException re) {
15510            }
15511            return;
15512        }
15513
15514        if (DEBUG_REMOVE) {
15515            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15516                    + " deleteAllUsers: " + deleteAllUsers );
15517        }
15518        // Queue up an async operation since the package deletion may take a little while.
15519        mHandler.post(new Runnable() {
15520            public void run() {
15521                mHandler.removeCallbacks(this);
15522                int returnCode;
15523                if (!deleteAllUsers) {
15524                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15525                } else {
15526                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15527                    // If nobody is blocking uninstall, proceed with delete for all users
15528                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15529                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15530                    } else {
15531                        // Otherwise uninstall individually for users with blockUninstalls=false
15532                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15533                        for (int userId : users) {
15534                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15535                                returnCode = deletePackageX(packageName, userId, userFlags);
15536                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15537                                    Slog.w(TAG, "Package delete failed for user " + userId
15538                                            + ", returnCode " + returnCode);
15539                                }
15540                            }
15541                        }
15542                        // The app has only been marked uninstalled for certain users.
15543                        // We still need to report that delete was blocked
15544                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15545                    }
15546                }
15547                try {
15548                    observer.onPackageDeleted(packageName, returnCode, null);
15549                } catch (RemoteException e) {
15550                    Log.i(TAG, "Observer no longer exists.");
15551                } //end catch
15552            } //end run
15553        });
15554    }
15555
15556    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15557        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15558              || callingUid == Process.SYSTEM_UID) {
15559            return true;
15560        }
15561        final int callingUserId = UserHandle.getUserId(callingUid);
15562        // If the caller installed the pkgName, then allow it to silently uninstall.
15563        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15564            return true;
15565        }
15566
15567        // Allow package verifier to silently uninstall.
15568        if (mRequiredVerifierPackage != null &&
15569                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15570            return true;
15571        }
15572
15573        // Allow package uninstaller to silently uninstall.
15574        if (mRequiredUninstallerPackage != null &&
15575                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15576            return true;
15577        }
15578
15579        // Allow storage manager to silently uninstall.
15580        if (mStorageManagerPackage != null &&
15581                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15582            return true;
15583        }
15584        return false;
15585    }
15586
15587    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15588        int[] result = EMPTY_INT_ARRAY;
15589        for (int userId : userIds) {
15590            if (getBlockUninstallForUser(packageName, userId)) {
15591                result = ArrayUtils.appendInt(result, userId);
15592            }
15593        }
15594        return result;
15595    }
15596
15597    @Override
15598    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15599        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15600    }
15601
15602    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15603        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15604                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15605        try {
15606            if (dpm != null) {
15607                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15608                        /* callingUserOnly =*/ false);
15609                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15610                        : deviceOwnerComponentName.getPackageName();
15611                // Does the package contains the device owner?
15612                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15613                // this check is probably not needed, since DO should be registered as a device
15614                // admin on some user too. (Original bug for this: b/17657954)
15615                if (packageName.equals(deviceOwnerPackageName)) {
15616                    return true;
15617                }
15618                // Does it contain a device admin for any user?
15619                int[] users;
15620                if (userId == UserHandle.USER_ALL) {
15621                    users = sUserManager.getUserIds();
15622                } else {
15623                    users = new int[]{userId};
15624                }
15625                for (int i = 0; i < users.length; ++i) {
15626                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15627                        return true;
15628                    }
15629                }
15630            }
15631        } catch (RemoteException e) {
15632        }
15633        return false;
15634    }
15635
15636    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15637        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15638    }
15639
15640    /**
15641     *  This method is an internal method that could be get invoked either
15642     *  to delete an installed package or to clean up a failed installation.
15643     *  After deleting an installed package, a broadcast is sent to notify any
15644     *  listeners that the package has been removed. For cleaning up a failed
15645     *  installation, the broadcast is not necessary since the package's
15646     *  installation wouldn't have sent the initial broadcast either
15647     *  The key steps in deleting a package are
15648     *  deleting the package information in internal structures like mPackages,
15649     *  deleting the packages base directories through installd
15650     *  updating mSettings to reflect current status
15651     *  persisting settings for later use
15652     *  sending a broadcast if necessary
15653     */
15654    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15655        final PackageRemovedInfo info = new PackageRemovedInfo();
15656        final boolean res;
15657
15658        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15659                ? UserHandle.USER_ALL : userId;
15660
15661        if (isPackageDeviceAdmin(packageName, removeUser)) {
15662            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15663            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15664        }
15665
15666        PackageSetting uninstalledPs = null;
15667
15668        // for the uninstall-updates case and restricted profiles, remember the per-
15669        // user handle installed state
15670        int[] allUsers;
15671        synchronized (mPackages) {
15672            uninstalledPs = mSettings.mPackages.get(packageName);
15673            if (uninstalledPs == null) {
15674                Slog.w(TAG, "Not removing non-existent package " + packageName);
15675                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15676            }
15677            allUsers = sUserManager.getUserIds();
15678            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15679        }
15680
15681        final int freezeUser;
15682        if (isUpdatedSystemApp(uninstalledPs)
15683                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15684            // We're downgrading a system app, which will apply to all users, so
15685            // freeze them all during the downgrade
15686            freezeUser = UserHandle.USER_ALL;
15687        } else {
15688            freezeUser = removeUser;
15689        }
15690
15691        synchronized (mInstallLock) {
15692            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15693            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15694                    deleteFlags, "deletePackageX")) {
15695                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15696                        deleteFlags | REMOVE_CHATTY, info, true, null);
15697            }
15698            synchronized (mPackages) {
15699                if (res) {
15700                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15701                }
15702            }
15703        }
15704
15705        if (res) {
15706            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15707            info.sendPackageRemovedBroadcasts(killApp);
15708            info.sendSystemPackageUpdatedBroadcasts();
15709            info.sendSystemPackageAppearedBroadcasts();
15710        }
15711        // Force a gc here.
15712        Runtime.getRuntime().gc();
15713        // Delete the resources here after sending the broadcast to let
15714        // other processes clean up before deleting resources.
15715        if (info.args != null) {
15716            synchronized (mInstallLock) {
15717                info.args.doPostDeleteLI(true);
15718            }
15719        }
15720
15721        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15722    }
15723
15724    class PackageRemovedInfo {
15725        String removedPackage;
15726        int uid = -1;
15727        int removedAppId = -1;
15728        int[] origUsers;
15729        int[] removedUsers = null;
15730        boolean isRemovedPackageSystemUpdate = false;
15731        boolean isUpdate;
15732        boolean dataRemoved;
15733        boolean removedForAllUsers;
15734        // Clean up resources deleted packages.
15735        InstallArgs args = null;
15736        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15737        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15738
15739        void sendPackageRemovedBroadcasts(boolean killApp) {
15740            sendPackageRemovedBroadcastInternal(killApp);
15741            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15742            for (int i = 0; i < childCount; i++) {
15743                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15744                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15745            }
15746        }
15747
15748        void sendSystemPackageUpdatedBroadcasts() {
15749            if (isRemovedPackageSystemUpdate) {
15750                sendSystemPackageUpdatedBroadcastsInternal();
15751                final int childCount = (removedChildPackages != null)
15752                        ? removedChildPackages.size() : 0;
15753                for (int i = 0; i < childCount; i++) {
15754                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15755                    if (childInfo.isRemovedPackageSystemUpdate) {
15756                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15757                    }
15758                }
15759            }
15760        }
15761
15762        void sendSystemPackageAppearedBroadcasts() {
15763            final int packageCount = (appearedChildPackages != null)
15764                    ? appearedChildPackages.size() : 0;
15765            for (int i = 0; i < packageCount; i++) {
15766                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15767                for (int userId : installedInfo.newUsers) {
15768                    sendPackageAddedForUser(installedInfo.name, true,
15769                            UserHandle.getAppId(installedInfo.uid), userId);
15770                }
15771            }
15772        }
15773
15774        private void sendSystemPackageUpdatedBroadcastsInternal() {
15775            Bundle extras = new Bundle(2);
15776            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15777            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15778            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15779                    extras, 0, null, null, null);
15780            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15781                    extras, 0, null, null, null);
15782            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15783                    null, 0, removedPackage, null, null);
15784        }
15785
15786        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15787            Bundle extras = new Bundle(2);
15788            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15789            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15790            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15791            if (isUpdate || isRemovedPackageSystemUpdate) {
15792                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15793            }
15794            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15795            if (removedPackage != null) {
15796                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15797                        extras, 0, null, null, removedUsers);
15798                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15799                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15800                            removedPackage, extras, 0, null, null, removedUsers);
15801                }
15802            }
15803            if (removedAppId >= 0) {
15804                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15805                        removedUsers);
15806            }
15807        }
15808    }
15809
15810    /*
15811     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15812     * flag is not set, the data directory is removed as well.
15813     * make sure this flag is set for partially installed apps. If not its meaningless to
15814     * delete a partially installed application.
15815     */
15816    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15817            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15818        String packageName = ps.name;
15819        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15820        // Retrieve object to delete permissions for shared user later on
15821        final PackageParser.Package deletedPkg;
15822        final PackageSetting deletedPs;
15823        // reader
15824        synchronized (mPackages) {
15825            deletedPkg = mPackages.get(packageName);
15826            deletedPs = mSettings.mPackages.get(packageName);
15827            if (outInfo != null) {
15828                outInfo.removedPackage = packageName;
15829                outInfo.removedUsers = deletedPs != null
15830                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15831                        : null;
15832            }
15833        }
15834
15835        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15836
15837        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15838            final PackageParser.Package resolvedPkg;
15839            if (deletedPkg != null) {
15840                resolvedPkg = deletedPkg;
15841            } else {
15842                // We don't have a parsed package when it lives on an ejected
15843                // adopted storage device, so fake something together
15844                resolvedPkg = new PackageParser.Package(ps.name);
15845                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15846            }
15847            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15848                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15849            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15850            if (outInfo != null) {
15851                outInfo.dataRemoved = true;
15852            }
15853            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15854        }
15855
15856        // writer
15857        synchronized (mPackages) {
15858            if (deletedPs != null) {
15859                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15860                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15861                    clearDefaultBrowserIfNeeded(packageName);
15862                    if (outInfo != null) {
15863                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15864                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15865                    }
15866                    updatePermissionsLPw(deletedPs.name, null, 0);
15867                    if (deletedPs.sharedUser != null) {
15868                        // Remove permissions associated with package. Since runtime
15869                        // permissions are per user we have to kill the removed package
15870                        // or packages running under the shared user of the removed
15871                        // package if revoking the permissions requested only by the removed
15872                        // package is successful and this causes a change in gids.
15873                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15874                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15875                                    userId);
15876                            if (userIdToKill == UserHandle.USER_ALL
15877                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15878                                // If gids changed for this user, kill all affected packages.
15879                                mHandler.post(new Runnable() {
15880                                    @Override
15881                                    public void run() {
15882                                        // This has to happen with no lock held.
15883                                        killApplication(deletedPs.name, deletedPs.appId,
15884                                                KILL_APP_REASON_GIDS_CHANGED);
15885                                    }
15886                                });
15887                                break;
15888                            }
15889                        }
15890                    }
15891                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15892                }
15893                // make sure to preserve per-user disabled state if this removal was just
15894                // a downgrade of a system app to the factory package
15895                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15896                    if (DEBUG_REMOVE) {
15897                        Slog.d(TAG, "Propagating install state across downgrade");
15898                    }
15899                    for (int userId : allUserHandles) {
15900                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15901                        if (DEBUG_REMOVE) {
15902                            Slog.d(TAG, "    user " + userId + " => " + installed);
15903                        }
15904                        ps.setInstalled(installed, userId);
15905                    }
15906                }
15907            }
15908            // can downgrade to reader
15909            if (writeSettings) {
15910                // Save settings now
15911                mSettings.writeLPr();
15912            }
15913        }
15914        if (outInfo != null) {
15915            // A user ID was deleted here. Go through all users and remove it
15916            // from KeyStore.
15917            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15918        }
15919    }
15920
15921    static boolean locationIsPrivileged(File path) {
15922        try {
15923            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15924                    .getCanonicalPath();
15925            return path.getCanonicalPath().startsWith(privilegedAppDir);
15926        } catch (IOException e) {
15927            Slog.e(TAG, "Unable to access code path " + path);
15928        }
15929        return false;
15930    }
15931
15932    /*
15933     * Tries to delete system package.
15934     */
15935    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15936            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15937            boolean writeSettings) {
15938        if (deletedPs.parentPackageName != null) {
15939            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15940            return false;
15941        }
15942
15943        final boolean applyUserRestrictions
15944                = (allUserHandles != null) && (outInfo.origUsers != null);
15945        final PackageSetting disabledPs;
15946        // Confirm if the system package has been updated
15947        // An updated system app can be deleted. This will also have to restore
15948        // the system pkg from system partition
15949        // reader
15950        synchronized (mPackages) {
15951            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15952        }
15953
15954        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15955                + " disabledPs=" + disabledPs);
15956
15957        if (disabledPs == null) {
15958            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15959            return false;
15960        } else if (DEBUG_REMOVE) {
15961            Slog.d(TAG, "Deleting system pkg from data partition");
15962        }
15963
15964        if (DEBUG_REMOVE) {
15965            if (applyUserRestrictions) {
15966                Slog.d(TAG, "Remembering install states:");
15967                for (int userId : allUserHandles) {
15968                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15969                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15970                }
15971            }
15972        }
15973
15974        // Delete the updated package
15975        outInfo.isRemovedPackageSystemUpdate = true;
15976        if (outInfo.removedChildPackages != null) {
15977            final int childCount = (deletedPs.childPackageNames != null)
15978                    ? deletedPs.childPackageNames.size() : 0;
15979            for (int i = 0; i < childCount; i++) {
15980                String childPackageName = deletedPs.childPackageNames.get(i);
15981                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15982                        .contains(childPackageName)) {
15983                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15984                            childPackageName);
15985                    if (childInfo != null) {
15986                        childInfo.isRemovedPackageSystemUpdate = true;
15987                    }
15988                }
15989            }
15990        }
15991
15992        if (disabledPs.versionCode < deletedPs.versionCode) {
15993            // Delete data for downgrades
15994            flags &= ~PackageManager.DELETE_KEEP_DATA;
15995        } else {
15996            // Preserve data by setting flag
15997            flags |= PackageManager.DELETE_KEEP_DATA;
15998        }
15999
16000        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16001                outInfo, writeSettings, disabledPs.pkg);
16002        if (!ret) {
16003            return false;
16004        }
16005
16006        // writer
16007        synchronized (mPackages) {
16008            // Reinstate the old system package
16009            enableSystemPackageLPw(disabledPs.pkg);
16010            // Remove any native libraries from the upgraded package.
16011            removeNativeBinariesLI(deletedPs);
16012        }
16013
16014        // Install the system package
16015        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16016        int parseFlags = mDefParseFlags
16017                | PackageParser.PARSE_MUST_BE_APK
16018                | PackageParser.PARSE_IS_SYSTEM
16019                | PackageParser.PARSE_IS_SYSTEM_DIR;
16020        if (locationIsPrivileged(disabledPs.codePath)) {
16021            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16022        }
16023
16024        final PackageParser.Package newPkg;
16025        try {
16026            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16027        } catch (PackageManagerException e) {
16028            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16029                    + e.getMessage());
16030            return false;
16031        }
16032        try {
16033            // update shared libraries for the newly re-installed system package
16034            updateSharedLibrariesLPw(newPkg, null);
16035        } catch (PackageManagerException e) {
16036            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16037        }
16038
16039        prepareAppDataAfterInstallLIF(newPkg);
16040
16041        // writer
16042        synchronized (mPackages) {
16043            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16044
16045            // Propagate the permissions state as we do not want to drop on the floor
16046            // runtime permissions. The update permissions method below will take
16047            // care of removing obsolete permissions and grant install permissions.
16048            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16049            updatePermissionsLPw(newPkg.packageName, newPkg,
16050                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16051
16052            if (applyUserRestrictions) {
16053                if (DEBUG_REMOVE) {
16054                    Slog.d(TAG, "Propagating install state across reinstall");
16055                }
16056                for (int userId : allUserHandles) {
16057                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16058                    if (DEBUG_REMOVE) {
16059                        Slog.d(TAG, "    user " + userId + " => " + installed);
16060                    }
16061                    ps.setInstalled(installed, userId);
16062
16063                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16064                }
16065                // Regardless of writeSettings we need to ensure that this restriction
16066                // state propagation is persisted
16067                mSettings.writeAllUsersPackageRestrictionsLPr();
16068            }
16069            // can downgrade to reader here
16070            if (writeSettings) {
16071                mSettings.writeLPr();
16072            }
16073        }
16074        return true;
16075    }
16076
16077    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16078            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16079            PackageRemovedInfo outInfo, boolean writeSettings,
16080            PackageParser.Package replacingPackage) {
16081        synchronized (mPackages) {
16082            if (outInfo != null) {
16083                outInfo.uid = ps.appId;
16084            }
16085
16086            if (outInfo != null && outInfo.removedChildPackages != null) {
16087                final int childCount = (ps.childPackageNames != null)
16088                        ? ps.childPackageNames.size() : 0;
16089                for (int i = 0; i < childCount; i++) {
16090                    String childPackageName = ps.childPackageNames.get(i);
16091                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16092                    if (childPs == null) {
16093                        return false;
16094                    }
16095                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16096                            childPackageName);
16097                    if (childInfo != null) {
16098                        childInfo.uid = childPs.appId;
16099                    }
16100                }
16101            }
16102        }
16103
16104        // Delete package data from internal structures and also remove data if flag is set
16105        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16106
16107        // Delete the child packages data
16108        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16109        for (int i = 0; i < childCount; i++) {
16110            PackageSetting childPs;
16111            synchronized (mPackages) {
16112                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16113            }
16114            if (childPs != null) {
16115                PackageRemovedInfo childOutInfo = (outInfo != null
16116                        && outInfo.removedChildPackages != null)
16117                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16118                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16119                        && (replacingPackage != null
16120                        && !replacingPackage.hasChildPackage(childPs.name))
16121                        ? flags & ~DELETE_KEEP_DATA : flags;
16122                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16123                        deleteFlags, writeSettings);
16124            }
16125        }
16126
16127        // Delete application code and resources only for parent packages
16128        if (ps.parentPackageName == null) {
16129            if (deleteCodeAndResources && (outInfo != null)) {
16130                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16131                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16132                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16133            }
16134        }
16135
16136        return true;
16137    }
16138
16139    @Override
16140    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16141            int userId) {
16142        mContext.enforceCallingOrSelfPermission(
16143                android.Manifest.permission.DELETE_PACKAGES, null);
16144        synchronized (mPackages) {
16145            PackageSetting ps = mSettings.mPackages.get(packageName);
16146            if (ps == null) {
16147                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16148                return false;
16149            }
16150            if (!ps.getInstalled(userId)) {
16151                // Can't block uninstall for an app that is not installed or enabled.
16152                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16153                return false;
16154            }
16155            ps.setBlockUninstall(blockUninstall, userId);
16156            mSettings.writePackageRestrictionsLPr(userId);
16157        }
16158        return true;
16159    }
16160
16161    @Override
16162    public boolean getBlockUninstallForUser(String packageName, int userId) {
16163        synchronized (mPackages) {
16164            PackageSetting ps = mSettings.mPackages.get(packageName);
16165            if (ps == null) {
16166                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16167                return false;
16168            }
16169            return ps.getBlockUninstall(userId);
16170        }
16171    }
16172
16173    @Override
16174    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16175        int callingUid = Binder.getCallingUid();
16176        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16177            throw new SecurityException(
16178                    "setRequiredForSystemUser can only be run by the system or root");
16179        }
16180        synchronized (mPackages) {
16181            PackageSetting ps = mSettings.mPackages.get(packageName);
16182            if (ps == null) {
16183                Log.w(TAG, "Package doesn't exist: " + packageName);
16184                return false;
16185            }
16186            if (systemUserApp) {
16187                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16188            } else {
16189                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16190            }
16191            mSettings.writeLPr();
16192        }
16193        return true;
16194    }
16195
16196    /*
16197     * This method handles package deletion in general
16198     */
16199    private boolean deletePackageLIF(String packageName, UserHandle user,
16200            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16201            PackageRemovedInfo outInfo, boolean writeSettings,
16202            PackageParser.Package replacingPackage) {
16203        if (packageName == null) {
16204            Slog.w(TAG, "Attempt to delete null packageName.");
16205            return false;
16206        }
16207
16208        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16209
16210        PackageSetting ps;
16211
16212        synchronized (mPackages) {
16213            ps = mSettings.mPackages.get(packageName);
16214            if (ps == null) {
16215                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16216                return false;
16217            }
16218
16219            if (ps.parentPackageName != null && (!isSystemApp(ps)
16220                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16221                if (DEBUG_REMOVE) {
16222                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16223                            + ((user == null) ? UserHandle.USER_ALL : user));
16224                }
16225                final int removedUserId = (user != null) ? user.getIdentifier()
16226                        : UserHandle.USER_ALL;
16227                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16228                    return false;
16229                }
16230                markPackageUninstalledForUserLPw(ps, user);
16231                scheduleWritePackageRestrictionsLocked(user);
16232                return true;
16233            }
16234        }
16235
16236        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16237                && user.getIdentifier() != UserHandle.USER_ALL)) {
16238            // The caller is asking that the package only be deleted for a single
16239            // user.  To do this, we just mark its uninstalled state and delete
16240            // its data. If this is a system app, we only allow this to happen if
16241            // they have set the special DELETE_SYSTEM_APP which requests different
16242            // semantics than normal for uninstalling system apps.
16243            markPackageUninstalledForUserLPw(ps, user);
16244
16245            if (!isSystemApp(ps)) {
16246                // Do not uninstall the APK if an app should be cached
16247                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16248                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16249                    // Other user still have this package installed, so all
16250                    // we need to do is clear this user's data and save that
16251                    // it is uninstalled.
16252                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16253                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16254                        return false;
16255                    }
16256                    scheduleWritePackageRestrictionsLocked(user);
16257                    return true;
16258                } else {
16259                    // We need to set it back to 'installed' so the uninstall
16260                    // broadcasts will be sent correctly.
16261                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16262                    ps.setInstalled(true, user.getIdentifier());
16263                }
16264            } else {
16265                // This is a system app, so we assume that the
16266                // other users still have this package installed, so all
16267                // we need to do is clear this user's data and save that
16268                // it is uninstalled.
16269                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16270                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16271                    return false;
16272                }
16273                scheduleWritePackageRestrictionsLocked(user);
16274                return true;
16275            }
16276        }
16277
16278        // If we are deleting a composite package for all users, keep track
16279        // of result for each child.
16280        if (ps.childPackageNames != null && outInfo != null) {
16281            synchronized (mPackages) {
16282                final int childCount = ps.childPackageNames.size();
16283                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16284                for (int i = 0; i < childCount; i++) {
16285                    String childPackageName = ps.childPackageNames.get(i);
16286                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16287                    childInfo.removedPackage = childPackageName;
16288                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16289                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16290                    if (childPs != null) {
16291                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16292                    }
16293                }
16294            }
16295        }
16296
16297        boolean ret = false;
16298        if (isSystemApp(ps)) {
16299            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16300            // When an updated system application is deleted we delete the existing resources
16301            // as well and fall back to existing code in system partition
16302            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16303        } else {
16304            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16305            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16306                    outInfo, writeSettings, replacingPackage);
16307        }
16308
16309        // Take a note whether we deleted the package for all users
16310        if (outInfo != null) {
16311            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16312            if (outInfo.removedChildPackages != null) {
16313                synchronized (mPackages) {
16314                    final int childCount = outInfo.removedChildPackages.size();
16315                    for (int i = 0; i < childCount; i++) {
16316                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16317                        if (childInfo != null) {
16318                            childInfo.removedForAllUsers = mPackages.get(
16319                                    childInfo.removedPackage) == null;
16320                        }
16321                    }
16322                }
16323            }
16324            // If we uninstalled an update to a system app there may be some
16325            // child packages that appeared as they are declared in the system
16326            // app but were not declared in the update.
16327            if (isSystemApp(ps)) {
16328                synchronized (mPackages) {
16329                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16330                    final int childCount = (updatedPs.childPackageNames != null)
16331                            ? updatedPs.childPackageNames.size() : 0;
16332                    for (int i = 0; i < childCount; i++) {
16333                        String childPackageName = updatedPs.childPackageNames.get(i);
16334                        if (outInfo.removedChildPackages == null
16335                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16336                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16337                            if (childPs == null) {
16338                                continue;
16339                            }
16340                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16341                            installRes.name = childPackageName;
16342                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16343                            installRes.pkg = mPackages.get(childPackageName);
16344                            installRes.uid = childPs.pkg.applicationInfo.uid;
16345                            if (outInfo.appearedChildPackages == null) {
16346                                outInfo.appearedChildPackages = new ArrayMap<>();
16347                            }
16348                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16349                        }
16350                    }
16351                }
16352            }
16353        }
16354
16355        return ret;
16356    }
16357
16358    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16359        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16360                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16361        for (int nextUserId : userIds) {
16362            if (DEBUG_REMOVE) {
16363                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16364            }
16365            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16366                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16367                    false /*hidden*/, false /*suspended*/, null, null, null,
16368                    false /*blockUninstall*/,
16369                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16370        }
16371    }
16372
16373    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16374            PackageRemovedInfo outInfo) {
16375        final PackageParser.Package pkg;
16376        synchronized (mPackages) {
16377            pkg = mPackages.get(ps.name);
16378        }
16379
16380        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16381                : new int[] {userId};
16382        for (int nextUserId : userIds) {
16383            if (DEBUG_REMOVE) {
16384                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16385                        + nextUserId);
16386            }
16387
16388            destroyAppDataLIF(pkg, userId,
16389                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16390            destroyAppProfilesLIF(pkg, userId);
16391            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16392            schedulePackageCleaning(ps.name, nextUserId, false);
16393            synchronized (mPackages) {
16394                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16395                    scheduleWritePackageRestrictionsLocked(nextUserId);
16396                }
16397                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16398            }
16399        }
16400
16401        if (outInfo != null) {
16402            outInfo.removedPackage = ps.name;
16403            outInfo.removedAppId = ps.appId;
16404            outInfo.removedUsers = userIds;
16405        }
16406
16407        return true;
16408    }
16409
16410    private final class ClearStorageConnection implements ServiceConnection {
16411        IMediaContainerService mContainerService;
16412
16413        @Override
16414        public void onServiceConnected(ComponentName name, IBinder service) {
16415            synchronized (this) {
16416                mContainerService = IMediaContainerService.Stub.asInterface(service);
16417                notifyAll();
16418            }
16419        }
16420
16421        @Override
16422        public void onServiceDisconnected(ComponentName name) {
16423        }
16424    }
16425
16426    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16427        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16428
16429        final boolean mounted;
16430        if (Environment.isExternalStorageEmulated()) {
16431            mounted = true;
16432        } else {
16433            final String status = Environment.getExternalStorageState();
16434
16435            mounted = status.equals(Environment.MEDIA_MOUNTED)
16436                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16437        }
16438
16439        if (!mounted) {
16440            return;
16441        }
16442
16443        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16444        int[] users;
16445        if (userId == UserHandle.USER_ALL) {
16446            users = sUserManager.getUserIds();
16447        } else {
16448            users = new int[] { userId };
16449        }
16450        final ClearStorageConnection conn = new ClearStorageConnection();
16451        if (mContext.bindServiceAsUser(
16452                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16453            try {
16454                for (int curUser : users) {
16455                    long timeout = SystemClock.uptimeMillis() + 5000;
16456                    synchronized (conn) {
16457                        long now;
16458                        while (conn.mContainerService == null &&
16459                                (now = SystemClock.uptimeMillis()) < timeout) {
16460                            try {
16461                                conn.wait(timeout - now);
16462                            } catch (InterruptedException e) {
16463                            }
16464                        }
16465                    }
16466                    if (conn.mContainerService == null) {
16467                        return;
16468                    }
16469
16470                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16471                    clearDirectory(conn.mContainerService,
16472                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16473                    if (allData) {
16474                        clearDirectory(conn.mContainerService,
16475                                userEnv.buildExternalStorageAppDataDirs(packageName));
16476                        clearDirectory(conn.mContainerService,
16477                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16478                    }
16479                }
16480            } finally {
16481                mContext.unbindService(conn);
16482            }
16483        }
16484    }
16485
16486    @Override
16487    public void clearApplicationProfileData(String packageName) {
16488        enforceSystemOrRoot("Only the system can clear all profile data");
16489
16490        final PackageParser.Package pkg;
16491        synchronized (mPackages) {
16492            pkg = mPackages.get(packageName);
16493        }
16494
16495        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16496            synchronized (mInstallLock) {
16497                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16498                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16499                        true /* removeBaseMarker */);
16500            }
16501        }
16502    }
16503
16504    @Override
16505    public void clearApplicationUserData(final String packageName,
16506            final IPackageDataObserver observer, final int userId) {
16507        mContext.enforceCallingOrSelfPermission(
16508                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16509
16510        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16511                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16512
16513        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16514            throw new SecurityException("Cannot clear data for a protected package: "
16515                    + packageName);
16516        }
16517        // Queue up an async operation since the package deletion may take a little while.
16518        mHandler.post(new Runnable() {
16519            public void run() {
16520                mHandler.removeCallbacks(this);
16521                final boolean succeeded;
16522                try (PackageFreezer freezer = freezePackage(packageName,
16523                        "clearApplicationUserData")) {
16524                    synchronized (mInstallLock) {
16525                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16526                    }
16527                    clearExternalStorageDataSync(packageName, userId, true);
16528                }
16529                if (succeeded) {
16530                    // invoke DeviceStorageMonitor's update method to clear any notifications
16531                    DeviceStorageMonitorInternal dsm = LocalServices
16532                            .getService(DeviceStorageMonitorInternal.class);
16533                    if (dsm != null) {
16534                        dsm.checkMemory();
16535                    }
16536                }
16537                if(observer != null) {
16538                    try {
16539                        observer.onRemoveCompleted(packageName, succeeded);
16540                    } catch (RemoteException e) {
16541                        Log.i(TAG, "Observer no longer exists.");
16542                    }
16543                } //end if observer
16544            } //end run
16545        });
16546    }
16547
16548    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16549        if (packageName == null) {
16550            Slog.w(TAG, "Attempt to delete null packageName.");
16551            return false;
16552        }
16553
16554        // Try finding details about the requested package
16555        PackageParser.Package pkg;
16556        synchronized (mPackages) {
16557            pkg = mPackages.get(packageName);
16558            if (pkg == null) {
16559                final PackageSetting ps = mSettings.mPackages.get(packageName);
16560                if (ps != null) {
16561                    pkg = ps.pkg;
16562                }
16563            }
16564
16565            if (pkg == null) {
16566                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16567                return false;
16568            }
16569
16570            PackageSetting ps = (PackageSetting) pkg.mExtras;
16571            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16572        }
16573
16574        clearAppDataLIF(pkg, userId,
16575                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16576
16577        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16578        removeKeystoreDataIfNeeded(userId, appId);
16579
16580        UserManagerInternal umInternal = getUserManagerInternal();
16581        final int flags;
16582        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16583            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16584        } else if (umInternal.isUserRunning(userId)) {
16585            flags = StorageManager.FLAG_STORAGE_DE;
16586        } else {
16587            flags = 0;
16588        }
16589        prepareAppDataContentsLIF(pkg, userId, flags);
16590
16591        return true;
16592    }
16593
16594    /**
16595     * Reverts user permission state changes (permissions and flags) in
16596     * all packages for a given user.
16597     *
16598     * @param userId The device user for which to do a reset.
16599     */
16600    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16601        final int packageCount = mPackages.size();
16602        for (int i = 0; i < packageCount; i++) {
16603            PackageParser.Package pkg = mPackages.valueAt(i);
16604            PackageSetting ps = (PackageSetting) pkg.mExtras;
16605            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16606        }
16607    }
16608
16609    private void resetNetworkPolicies(int userId) {
16610        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16611    }
16612
16613    /**
16614     * Reverts user permission state changes (permissions and flags).
16615     *
16616     * @param ps The package for which to reset.
16617     * @param userId The device user for which to do a reset.
16618     */
16619    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16620            final PackageSetting ps, final int userId) {
16621        if (ps.pkg == null) {
16622            return;
16623        }
16624
16625        // These are flags that can change base on user actions.
16626        final int userSettableMask = FLAG_PERMISSION_USER_SET
16627                | FLAG_PERMISSION_USER_FIXED
16628                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16629                | FLAG_PERMISSION_REVIEW_REQUIRED;
16630
16631        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16632                | FLAG_PERMISSION_POLICY_FIXED;
16633
16634        boolean writeInstallPermissions = false;
16635        boolean writeRuntimePermissions = false;
16636
16637        final int permissionCount = ps.pkg.requestedPermissions.size();
16638        for (int i = 0; i < permissionCount; i++) {
16639            String permission = ps.pkg.requestedPermissions.get(i);
16640
16641            BasePermission bp = mSettings.mPermissions.get(permission);
16642            if (bp == null) {
16643                continue;
16644            }
16645
16646            // If shared user we just reset the state to which only this app contributed.
16647            if (ps.sharedUser != null) {
16648                boolean used = false;
16649                final int packageCount = ps.sharedUser.packages.size();
16650                for (int j = 0; j < packageCount; j++) {
16651                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16652                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16653                            && pkg.pkg.requestedPermissions.contains(permission)) {
16654                        used = true;
16655                        break;
16656                    }
16657                }
16658                if (used) {
16659                    continue;
16660                }
16661            }
16662
16663            PermissionsState permissionsState = ps.getPermissionsState();
16664
16665            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16666
16667            // Always clear the user settable flags.
16668            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16669                    bp.name) != null;
16670            // If permission review is enabled and this is a legacy app, mark the
16671            // permission as requiring a review as this is the initial state.
16672            int flags = 0;
16673            if (Build.PERMISSIONS_REVIEW_REQUIRED
16674                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16675                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16676            }
16677            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16678                if (hasInstallState) {
16679                    writeInstallPermissions = true;
16680                } else {
16681                    writeRuntimePermissions = true;
16682                }
16683            }
16684
16685            // Below is only runtime permission handling.
16686            if (!bp.isRuntime()) {
16687                continue;
16688            }
16689
16690            // Never clobber system or policy.
16691            if ((oldFlags & policyOrSystemFlags) != 0) {
16692                continue;
16693            }
16694
16695            // If this permission was granted by default, make sure it is.
16696            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16697                if (permissionsState.grantRuntimePermission(bp, userId)
16698                        != PERMISSION_OPERATION_FAILURE) {
16699                    writeRuntimePermissions = true;
16700                }
16701            // If permission review is enabled the permissions for a legacy apps
16702            // are represented as constantly granted runtime ones, so don't revoke.
16703            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16704                // Otherwise, reset the permission.
16705                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16706                switch (revokeResult) {
16707                    case PERMISSION_OPERATION_SUCCESS:
16708                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16709                        writeRuntimePermissions = true;
16710                        final int appId = ps.appId;
16711                        mHandler.post(new Runnable() {
16712                            @Override
16713                            public void run() {
16714                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16715                            }
16716                        });
16717                    } break;
16718                }
16719            }
16720        }
16721
16722        // Synchronously write as we are taking permissions away.
16723        if (writeRuntimePermissions) {
16724            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16725        }
16726
16727        // Synchronously write as we are taking permissions away.
16728        if (writeInstallPermissions) {
16729            mSettings.writeLPr();
16730        }
16731    }
16732
16733    /**
16734     * Remove entries from the keystore daemon. Will only remove it if the
16735     * {@code appId} is valid.
16736     */
16737    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16738        if (appId < 0) {
16739            return;
16740        }
16741
16742        final KeyStore keyStore = KeyStore.getInstance();
16743        if (keyStore != null) {
16744            if (userId == UserHandle.USER_ALL) {
16745                for (final int individual : sUserManager.getUserIds()) {
16746                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16747                }
16748            } else {
16749                keyStore.clearUid(UserHandle.getUid(userId, appId));
16750            }
16751        } else {
16752            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16753        }
16754    }
16755
16756    @Override
16757    public void deleteApplicationCacheFiles(final String packageName,
16758            final IPackageDataObserver observer) {
16759        final int userId = UserHandle.getCallingUserId();
16760        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16761    }
16762
16763    @Override
16764    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16765            final IPackageDataObserver observer) {
16766        mContext.enforceCallingOrSelfPermission(
16767                android.Manifest.permission.DELETE_CACHE_FILES, null);
16768        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16769                /* requireFullPermission= */ true, /* checkShell= */ false,
16770                "delete application cache files");
16771
16772        final PackageParser.Package pkg;
16773        synchronized (mPackages) {
16774            pkg = mPackages.get(packageName);
16775        }
16776
16777        // Queue up an async operation since the package deletion may take a little while.
16778        mHandler.post(new Runnable() {
16779            public void run() {
16780                synchronized (mInstallLock) {
16781                    final int flags = StorageManager.FLAG_STORAGE_DE
16782                            | StorageManager.FLAG_STORAGE_CE;
16783                    // We're only clearing cache files, so we don't care if the
16784                    // app is unfrozen and still able to run
16785                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16786                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16787                }
16788                clearExternalStorageDataSync(packageName, userId, false);
16789                if (observer != null) {
16790                    try {
16791                        observer.onRemoveCompleted(packageName, true);
16792                    } catch (RemoteException e) {
16793                        Log.i(TAG, "Observer no longer exists.");
16794                    }
16795                }
16796            }
16797        });
16798    }
16799
16800    @Override
16801    public void getPackageSizeInfo(final String packageName, int userHandle,
16802            final IPackageStatsObserver observer) {
16803        mContext.enforceCallingOrSelfPermission(
16804                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16805        if (packageName == null) {
16806            throw new IllegalArgumentException("Attempt to get size of null packageName");
16807        }
16808
16809        PackageStats stats = new PackageStats(packageName, userHandle);
16810
16811        /*
16812         * Queue up an async operation since the package measurement may take a
16813         * little while.
16814         */
16815        Message msg = mHandler.obtainMessage(INIT_COPY);
16816        msg.obj = new MeasureParams(stats, observer);
16817        mHandler.sendMessage(msg);
16818    }
16819
16820    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16821        final PackageSetting ps;
16822        synchronized (mPackages) {
16823            ps = mSettings.mPackages.get(packageName);
16824            if (ps == null) {
16825                Slog.w(TAG, "Failed to find settings for " + packageName);
16826                return false;
16827            }
16828        }
16829        try {
16830            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16831                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16832                    ps.getCeDataInode(userId), ps.codePathString, stats);
16833        } catch (InstallerException e) {
16834            Slog.w(TAG, String.valueOf(e));
16835            return false;
16836        }
16837
16838        // For now, ignore code size of packages on system partition
16839        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16840            stats.codeSize = 0;
16841        }
16842
16843        return true;
16844    }
16845
16846    private int getUidTargetSdkVersionLockedLPr(int uid) {
16847        Object obj = mSettings.getUserIdLPr(uid);
16848        if (obj instanceof SharedUserSetting) {
16849            final SharedUserSetting sus = (SharedUserSetting) obj;
16850            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16851            final Iterator<PackageSetting> it = sus.packages.iterator();
16852            while (it.hasNext()) {
16853                final PackageSetting ps = it.next();
16854                if (ps.pkg != null) {
16855                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16856                    if (v < vers) vers = v;
16857                }
16858            }
16859            return vers;
16860        } else if (obj instanceof PackageSetting) {
16861            final PackageSetting ps = (PackageSetting) obj;
16862            if (ps.pkg != null) {
16863                return ps.pkg.applicationInfo.targetSdkVersion;
16864            }
16865        }
16866        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16867    }
16868
16869    @Override
16870    public void addPreferredActivity(IntentFilter filter, int match,
16871            ComponentName[] set, ComponentName activity, int userId) {
16872        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16873                "Adding preferred");
16874    }
16875
16876    private void addPreferredActivityInternal(IntentFilter filter, int match,
16877            ComponentName[] set, ComponentName activity, boolean always, int userId,
16878            String opname) {
16879        // writer
16880        int callingUid = Binder.getCallingUid();
16881        enforceCrossUserPermission(callingUid, userId,
16882                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16883        if (filter.countActions() == 0) {
16884            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16885            return;
16886        }
16887        synchronized (mPackages) {
16888            if (mContext.checkCallingOrSelfPermission(
16889                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16890                    != PackageManager.PERMISSION_GRANTED) {
16891                if (getUidTargetSdkVersionLockedLPr(callingUid)
16892                        < Build.VERSION_CODES.FROYO) {
16893                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16894                            + callingUid);
16895                    return;
16896                }
16897                mContext.enforceCallingOrSelfPermission(
16898                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16899            }
16900
16901            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16902            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16903                    + userId + ":");
16904            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16905            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16906            scheduleWritePackageRestrictionsLocked(userId);
16907            postPreferredActivityChangedBroadcast(userId);
16908        }
16909    }
16910
16911    private void postPreferredActivityChangedBroadcast(int userId) {
16912        mHandler.post(() -> {
16913            final IActivityManager am = ActivityManagerNative.getDefault();
16914            if (am == null) {
16915                return;
16916            }
16917
16918            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16919            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16920            try {
16921                am.broadcastIntent(null, intent, null, null,
16922                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16923                        null, false, false, userId);
16924            } catch (RemoteException e) {
16925            }
16926        });
16927    }
16928
16929    @Override
16930    public void replacePreferredActivity(IntentFilter filter, int match,
16931            ComponentName[] set, ComponentName activity, int userId) {
16932        if (filter.countActions() != 1) {
16933            throw new IllegalArgumentException(
16934                    "replacePreferredActivity expects filter to have only 1 action.");
16935        }
16936        if (filter.countDataAuthorities() != 0
16937                || filter.countDataPaths() != 0
16938                || filter.countDataSchemes() > 1
16939                || filter.countDataTypes() != 0) {
16940            throw new IllegalArgumentException(
16941                    "replacePreferredActivity expects filter to have no data authorities, " +
16942                    "paths, or types; and at most one scheme.");
16943        }
16944
16945        final int callingUid = Binder.getCallingUid();
16946        enforceCrossUserPermission(callingUid, userId,
16947                true /* requireFullPermission */, false /* checkShell */,
16948                "replace preferred activity");
16949        synchronized (mPackages) {
16950            if (mContext.checkCallingOrSelfPermission(
16951                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16952                    != PackageManager.PERMISSION_GRANTED) {
16953                if (getUidTargetSdkVersionLockedLPr(callingUid)
16954                        < Build.VERSION_CODES.FROYO) {
16955                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16956                            + Binder.getCallingUid());
16957                    return;
16958                }
16959                mContext.enforceCallingOrSelfPermission(
16960                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16961            }
16962
16963            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16964            if (pir != null) {
16965                // Get all of the existing entries that exactly match this filter.
16966                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16967                if (existing != null && existing.size() == 1) {
16968                    PreferredActivity cur = existing.get(0);
16969                    if (DEBUG_PREFERRED) {
16970                        Slog.i(TAG, "Checking replace of preferred:");
16971                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16972                        if (!cur.mPref.mAlways) {
16973                            Slog.i(TAG, "  -- CUR; not mAlways!");
16974                        } else {
16975                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16976                            Slog.i(TAG, "  -- CUR: mSet="
16977                                    + Arrays.toString(cur.mPref.mSetComponents));
16978                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16979                            Slog.i(TAG, "  -- NEW: mMatch="
16980                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16981                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16982                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16983                        }
16984                    }
16985                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16986                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16987                            && cur.mPref.sameSet(set)) {
16988                        // Setting the preferred activity to what it happens to be already
16989                        if (DEBUG_PREFERRED) {
16990                            Slog.i(TAG, "Replacing with same preferred activity "
16991                                    + cur.mPref.mShortComponent + " for user "
16992                                    + userId + ":");
16993                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16994                        }
16995                        return;
16996                    }
16997                }
16998
16999                if (existing != null) {
17000                    if (DEBUG_PREFERRED) {
17001                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17002                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17003                    }
17004                    for (int i = 0; i < existing.size(); i++) {
17005                        PreferredActivity pa = existing.get(i);
17006                        if (DEBUG_PREFERRED) {
17007                            Slog.i(TAG, "Removing existing preferred activity "
17008                                    + pa.mPref.mComponent + ":");
17009                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17010                        }
17011                        pir.removeFilter(pa);
17012                    }
17013                }
17014            }
17015            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17016                    "Replacing preferred");
17017        }
17018    }
17019
17020    @Override
17021    public void clearPackagePreferredActivities(String packageName) {
17022        final int uid = Binder.getCallingUid();
17023        // writer
17024        synchronized (mPackages) {
17025            PackageParser.Package pkg = mPackages.get(packageName);
17026            if (pkg == null || pkg.applicationInfo.uid != uid) {
17027                if (mContext.checkCallingOrSelfPermission(
17028                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17029                        != PackageManager.PERMISSION_GRANTED) {
17030                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17031                            < Build.VERSION_CODES.FROYO) {
17032                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17033                                + Binder.getCallingUid());
17034                        return;
17035                    }
17036                    mContext.enforceCallingOrSelfPermission(
17037                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17038                }
17039            }
17040
17041            int user = UserHandle.getCallingUserId();
17042            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17043                scheduleWritePackageRestrictionsLocked(user);
17044            }
17045        }
17046    }
17047
17048    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17049    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17050        ArrayList<PreferredActivity> removed = null;
17051        boolean changed = false;
17052        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17053            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17054            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17055            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17056                continue;
17057            }
17058            Iterator<PreferredActivity> it = pir.filterIterator();
17059            while (it.hasNext()) {
17060                PreferredActivity pa = it.next();
17061                // Mark entry for removal only if it matches the package name
17062                // and the entry is of type "always".
17063                if (packageName == null ||
17064                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17065                                && pa.mPref.mAlways)) {
17066                    if (removed == null) {
17067                        removed = new ArrayList<PreferredActivity>();
17068                    }
17069                    removed.add(pa);
17070                }
17071            }
17072            if (removed != null) {
17073                for (int j=0; j<removed.size(); j++) {
17074                    PreferredActivity pa = removed.get(j);
17075                    pir.removeFilter(pa);
17076                }
17077                changed = true;
17078            }
17079        }
17080        if (changed) {
17081            postPreferredActivityChangedBroadcast(userId);
17082        }
17083        return changed;
17084    }
17085
17086    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17087    private void clearIntentFilterVerificationsLPw(int userId) {
17088        final int packageCount = mPackages.size();
17089        for (int i = 0; i < packageCount; i++) {
17090            PackageParser.Package pkg = mPackages.valueAt(i);
17091            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17092        }
17093    }
17094
17095    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17096    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17097        if (userId == UserHandle.USER_ALL) {
17098            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17099                    sUserManager.getUserIds())) {
17100                for (int oneUserId : sUserManager.getUserIds()) {
17101                    scheduleWritePackageRestrictionsLocked(oneUserId);
17102                }
17103            }
17104        } else {
17105            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17106                scheduleWritePackageRestrictionsLocked(userId);
17107            }
17108        }
17109    }
17110
17111    void clearDefaultBrowserIfNeeded(String packageName) {
17112        for (int oneUserId : sUserManager.getUserIds()) {
17113            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17114            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17115            if (packageName.equals(defaultBrowserPackageName)) {
17116                setDefaultBrowserPackageName(null, oneUserId);
17117            }
17118        }
17119    }
17120
17121    @Override
17122    public void resetApplicationPreferences(int userId) {
17123        mContext.enforceCallingOrSelfPermission(
17124                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17125        final long identity = Binder.clearCallingIdentity();
17126        // writer
17127        try {
17128            synchronized (mPackages) {
17129                clearPackagePreferredActivitiesLPw(null, userId);
17130                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17131                // TODO: We have to reset the default SMS and Phone. This requires
17132                // significant refactoring to keep all default apps in the package
17133                // manager (cleaner but more work) or have the services provide
17134                // callbacks to the package manager to request a default app reset.
17135                applyFactoryDefaultBrowserLPw(userId);
17136                clearIntentFilterVerificationsLPw(userId);
17137                primeDomainVerificationsLPw(userId);
17138                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17139                scheduleWritePackageRestrictionsLocked(userId);
17140            }
17141            resetNetworkPolicies(userId);
17142        } finally {
17143            Binder.restoreCallingIdentity(identity);
17144        }
17145    }
17146
17147    @Override
17148    public int getPreferredActivities(List<IntentFilter> outFilters,
17149            List<ComponentName> outActivities, String packageName) {
17150
17151        int num = 0;
17152        final int userId = UserHandle.getCallingUserId();
17153        // reader
17154        synchronized (mPackages) {
17155            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17156            if (pir != null) {
17157                final Iterator<PreferredActivity> it = pir.filterIterator();
17158                while (it.hasNext()) {
17159                    final PreferredActivity pa = it.next();
17160                    if (packageName == null
17161                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17162                                    && pa.mPref.mAlways)) {
17163                        if (outFilters != null) {
17164                            outFilters.add(new IntentFilter(pa));
17165                        }
17166                        if (outActivities != null) {
17167                            outActivities.add(pa.mPref.mComponent);
17168                        }
17169                    }
17170                }
17171            }
17172        }
17173
17174        return num;
17175    }
17176
17177    @Override
17178    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17179            int userId) {
17180        int callingUid = Binder.getCallingUid();
17181        if (callingUid != Process.SYSTEM_UID) {
17182            throw new SecurityException(
17183                    "addPersistentPreferredActivity can only be run by the system");
17184        }
17185        if (filter.countActions() == 0) {
17186            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17187            return;
17188        }
17189        synchronized (mPackages) {
17190            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17191                    ":");
17192            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17193            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17194                    new PersistentPreferredActivity(filter, activity));
17195            scheduleWritePackageRestrictionsLocked(userId);
17196            postPreferredActivityChangedBroadcast(userId);
17197        }
17198    }
17199
17200    @Override
17201    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17202        int callingUid = Binder.getCallingUid();
17203        if (callingUid != Process.SYSTEM_UID) {
17204            throw new SecurityException(
17205                    "clearPackagePersistentPreferredActivities can only be run by the system");
17206        }
17207        ArrayList<PersistentPreferredActivity> removed = null;
17208        boolean changed = false;
17209        synchronized (mPackages) {
17210            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17211                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17212                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17213                        .valueAt(i);
17214                if (userId != thisUserId) {
17215                    continue;
17216                }
17217                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17218                while (it.hasNext()) {
17219                    PersistentPreferredActivity ppa = it.next();
17220                    // Mark entry for removal only if it matches the package name.
17221                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17222                        if (removed == null) {
17223                            removed = new ArrayList<PersistentPreferredActivity>();
17224                        }
17225                        removed.add(ppa);
17226                    }
17227                }
17228                if (removed != null) {
17229                    for (int j=0; j<removed.size(); j++) {
17230                        PersistentPreferredActivity ppa = removed.get(j);
17231                        ppir.removeFilter(ppa);
17232                    }
17233                    changed = true;
17234                }
17235            }
17236
17237            if (changed) {
17238                scheduleWritePackageRestrictionsLocked(userId);
17239                postPreferredActivityChangedBroadcast(userId);
17240            }
17241        }
17242    }
17243
17244    /**
17245     * Common machinery for picking apart a restored XML blob and passing
17246     * it to a caller-supplied functor to be applied to the running system.
17247     */
17248    private void restoreFromXml(XmlPullParser parser, int userId,
17249            String expectedStartTag, BlobXmlRestorer functor)
17250            throws IOException, XmlPullParserException {
17251        int type;
17252        while ((type = parser.next()) != XmlPullParser.START_TAG
17253                && type != XmlPullParser.END_DOCUMENT) {
17254        }
17255        if (type != XmlPullParser.START_TAG) {
17256            // oops didn't find a start tag?!
17257            if (DEBUG_BACKUP) {
17258                Slog.e(TAG, "Didn't find start tag during restore");
17259            }
17260            return;
17261        }
17262Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17263        // this is supposed to be TAG_PREFERRED_BACKUP
17264        if (!expectedStartTag.equals(parser.getName())) {
17265            if (DEBUG_BACKUP) {
17266                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17267            }
17268            return;
17269        }
17270
17271        // skip interfering stuff, then we're aligned with the backing implementation
17272        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17273Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17274        functor.apply(parser, userId);
17275    }
17276
17277    private interface BlobXmlRestorer {
17278        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17279    }
17280
17281    /**
17282     * Non-Binder method, support for the backup/restore mechanism: write the
17283     * full set of preferred activities in its canonical XML format.  Returns the
17284     * XML output as a byte array, or null if there is none.
17285     */
17286    @Override
17287    public byte[] getPreferredActivityBackup(int userId) {
17288        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17289            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17290        }
17291
17292        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17293        try {
17294            final XmlSerializer serializer = new FastXmlSerializer();
17295            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17296            serializer.startDocument(null, true);
17297            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17298
17299            synchronized (mPackages) {
17300                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17301            }
17302
17303            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17304            serializer.endDocument();
17305            serializer.flush();
17306        } catch (Exception e) {
17307            if (DEBUG_BACKUP) {
17308                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17309            }
17310            return null;
17311        }
17312
17313        return dataStream.toByteArray();
17314    }
17315
17316    @Override
17317    public void restorePreferredActivities(byte[] backup, int userId) {
17318        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17319            throw new SecurityException("Only the system may call restorePreferredActivities()");
17320        }
17321
17322        try {
17323            final XmlPullParser parser = Xml.newPullParser();
17324            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17325            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17326                    new BlobXmlRestorer() {
17327                        @Override
17328                        public void apply(XmlPullParser parser, int userId)
17329                                throws XmlPullParserException, IOException {
17330                            synchronized (mPackages) {
17331                                mSettings.readPreferredActivitiesLPw(parser, userId);
17332                            }
17333                        }
17334                    } );
17335        } catch (Exception e) {
17336            if (DEBUG_BACKUP) {
17337                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17338            }
17339        }
17340    }
17341
17342    /**
17343     * Non-Binder method, support for the backup/restore mechanism: write the
17344     * default browser (etc) settings in its canonical XML format.  Returns the default
17345     * browser XML representation as a byte array, or null if there is none.
17346     */
17347    @Override
17348    public byte[] getDefaultAppsBackup(int userId) {
17349        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17350            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17351        }
17352
17353        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17354        try {
17355            final XmlSerializer serializer = new FastXmlSerializer();
17356            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17357            serializer.startDocument(null, true);
17358            serializer.startTag(null, TAG_DEFAULT_APPS);
17359
17360            synchronized (mPackages) {
17361                mSettings.writeDefaultAppsLPr(serializer, userId);
17362            }
17363
17364            serializer.endTag(null, TAG_DEFAULT_APPS);
17365            serializer.endDocument();
17366            serializer.flush();
17367        } catch (Exception e) {
17368            if (DEBUG_BACKUP) {
17369                Slog.e(TAG, "Unable to write default apps for backup", e);
17370            }
17371            return null;
17372        }
17373
17374        return dataStream.toByteArray();
17375    }
17376
17377    @Override
17378    public void restoreDefaultApps(byte[] backup, int userId) {
17379        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17380            throw new SecurityException("Only the system may call restoreDefaultApps()");
17381        }
17382
17383        try {
17384            final XmlPullParser parser = Xml.newPullParser();
17385            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17386            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17387                    new BlobXmlRestorer() {
17388                        @Override
17389                        public void apply(XmlPullParser parser, int userId)
17390                                throws XmlPullParserException, IOException {
17391                            synchronized (mPackages) {
17392                                mSettings.readDefaultAppsLPw(parser, userId);
17393                            }
17394                        }
17395                    } );
17396        } catch (Exception e) {
17397            if (DEBUG_BACKUP) {
17398                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17399            }
17400        }
17401    }
17402
17403    @Override
17404    public byte[] getIntentFilterVerificationBackup(int userId) {
17405        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17406            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17407        }
17408
17409        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17410        try {
17411            final XmlSerializer serializer = new FastXmlSerializer();
17412            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17413            serializer.startDocument(null, true);
17414            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17415
17416            synchronized (mPackages) {
17417                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17418            }
17419
17420            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17421            serializer.endDocument();
17422            serializer.flush();
17423        } catch (Exception e) {
17424            if (DEBUG_BACKUP) {
17425                Slog.e(TAG, "Unable to write default apps for backup", e);
17426            }
17427            return null;
17428        }
17429
17430        return dataStream.toByteArray();
17431    }
17432
17433    @Override
17434    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17435        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17436            throw new SecurityException("Only the system may call restorePreferredActivities()");
17437        }
17438
17439        try {
17440            final XmlPullParser parser = Xml.newPullParser();
17441            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17442            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17443                    new BlobXmlRestorer() {
17444                        @Override
17445                        public void apply(XmlPullParser parser, int userId)
17446                                throws XmlPullParserException, IOException {
17447                            synchronized (mPackages) {
17448                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17449                                mSettings.writeLPr();
17450                            }
17451                        }
17452                    } );
17453        } catch (Exception e) {
17454            if (DEBUG_BACKUP) {
17455                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17456            }
17457        }
17458    }
17459
17460    @Override
17461    public byte[] getPermissionGrantBackup(int userId) {
17462        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17463            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17464        }
17465
17466        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17467        try {
17468            final XmlSerializer serializer = new FastXmlSerializer();
17469            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17470            serializer.startDocument(null, true);
17471            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17472
17473            synchronized (mPackages) {
17474                serializeRuntimePermissionGrantsLPr(serializer, userId);
17475            }
17476
17477            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17478            serializer.endDocument();
17479            serializer.flush();
17480        } catch (Exception e) {
17481            if (DEBUG_BACKUP) {
17482                Slog.e(TAG, "Unable to write default apps for backup", e);
17483            }
17484            return null;
17485        }
17486
17487        return dataStream.toByteArray();
17488    }
17489
17490    @Override
17491    public void restorePermissionGrants(byte[] backup, int userId) {
17492        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17493            throw new SecurityException("Only the system may call restorePermissionGrants()");
17494        }
17495
17496        try {
17497            final XmlPullParser parser = Xml.newPullParser();
17498            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17499            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17500                    new BlobXmlRestorer() {
17501                        @Override
17502                        public void apply(XmlPullParser parser, int userId)
17503                                throws XmlPullParserException, IOException {
17504                            synchronized (mPackages) {
17505                                processRestoredPermissionGrantsLPr(parser, userId);
17506                            }
17507                        }
17508                    } );
17509        } catch (Exception e) {
17510            if (DEBUG_BACKUP) {
17511                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17512            }
17513        }
17514    }
17515
17516    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17517            throws IOException {
17518        serializer.startTag(null, TAG_ALL_GRANTS);
17519
17520        final int N = mSettings.mPackages.size();
17521        for (int i = 0; i < N; i++) {
17522            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17523            boolean pkgGrantsKnown = false;
17524
17525            PermissionsState packagePerms = ps.getPermissionsState();
17526
17527            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17528                final int grantFlags = state.getFlags();
17529                // only look at grants that are not system/policy fixed
17530                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17531                    final boolean isGranted = state.isGranted();
17532                    // And only back up the user-twiddled state bits
17533                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17534                        final String packageName = mSettings.mPackages.keyAt(i);
17535                        if (!pkgGrantsKnown) {
17536                            serializer.startTag(null, TAG_GRANT);
17537                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17538                            pkgGrantsKnown = true;
17539                        }
17540
17541                        final boolean userSet =
17542                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17543                        final boolean userFixed =
17544                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17545                        final boolean revoke =
17546                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17547
17548                        serializer.startTag(null, TAG_PERMISSION);
17549                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17550                        if (isGranted) {
17551                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17552                        }
17553                        if (userSet) {
17554                            serializer.attribute(null, ATTR_USER_SET, "true");
17555                        }
17556                        if (userFixed) {
17557                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17558                        }
17559                        if (revoke) {
17560                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17561                        }
17562                        serializer.endTag(null, TAG_PERMISSION);
17563                    }
17564                }
17565            }
17566
17567            if (pkgGrantsKnown) {
17568                serializer.endTag(null, TAG_GRANT);
17569            }
17570        }
17571
17572        serializer.endTag(null, TAG_ALL_GRANTS);
17573    }
17574
17575    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17576            throws XmlPullParserException, IOException {
17577        String pkgName = null;
17578        int outerDepth = parser.getDepth();
17579        int type;
17580        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17581                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17582            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17583                continue;
17584            }
17585
17586            final String tagName = parser.getName();
17587            if (tagName.equals(TAG_GRANT)) {
17588                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17589                if (DEBUG_BACKUP) {
17590                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17591                }
17592            } else if (tagName.equals(TAG_PERMISSION)) {
17593
17594                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17595                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17596
17597                int newFlagSet = 0;
17598                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17599                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17600                }
17601                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17602                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17603                }
17604                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17605                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17606                }
17607                if (DEBUG_BACKUP) {
17608                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17609                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17610                }
17611                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17612                if (ps != null) {
17613                    // Already installed so we apply the grant immediately
17614                    if (DEBUG_BACKUP) {
17615                        Slog.v(TAG, "        + already installed; applying");
17616                    }
17617                    PermissionsState perms = ps.getPermissionsState();
17618                    BasePermission bp = mSettings.mPermissions.get(permName);
17619                    if (bp != null) {
17620                        if (isGranted) {
17621                            perms.grantRuntimePermission(bp, userId);
17622                        }
17623                        if (newFlagSet != 0) {
17624                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17625                        }
17626                    }
17627                } else {
17628                    // Need to wait for post-restore install to apply the grant
17629                    if (DEBUG_BACKUP) {
17630                        Slog.v(TAG, "        - not yet installed; saving for later");
17631                    }
17632                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17633                            isGranted, newFlagSet, userId);
17634                }
17635            } else {
17636                PackageManagerService.reportSettingsProblem(Log.WARN,
17637                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17638                XmlUtils.skipCurrentTag(parser);
17639            }
17640        }
17641
17642        scheduleWriteSettingsLocked();
17643        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17644    }
17645
17646    @Override
17647    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17648            int sourceUserId, int targetUserId, int flags) {
17649        mContext.enforceCallingOrSelfPermission(
17650                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17651        int callingUid = Binder.getCallingUid();
17652        enforceOwnerRights(ownerPackage, callingUid);
17653        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17654        if (intentFilter.countActions() == 0) {
17655            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17656            return;
17657        }
17658        synchronized (mPackages) {
17659            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17660                    ownerPackage, targetUserId, flags);
17661            CrossProfileIntentResolver resolver =
17662                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17663            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17664            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17665            if (existing != null) {
17666                int size = existing.size();
17667                for (int i = 0; i < size; i++) {
17668                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17669                        return;
17670                    }
17671                }
17672            }
17673            resolver.addFilter(newFilter);
17674            scheduleWritePackageRestrictionsLocked(sourceUserId);
17675        }
17676    }
17677
17678    @Override
17679    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17680        mContext.enforceCallingOrSelfPermission(
17681                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17682        int callingUid = Binder.getCallingUid();
17683        enforceOwnerRights(ownerPackage, callingUid);
17684        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17685        synchronized (mPackages) {
17686            CrossProfileIntentResolver resolver =
17687                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17688            ArraySet<CrossProfileIntentFilter> set =
17689                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17690            for (CrossProfileIntentFilter filter : set) {
17691                if (filter.getOwnerPackage().equals(ownerPackage)) {
17692                    resolver.removeFilter(filter);
17693                }
17694            }
17695            scheduleWritePackageRestrictionsLocked(sourceUserId);
17696        }
17697    }
17698
17699    // Enforcing that callingUid is owning pkg on userId
17700    private void enforceOwnerRights(String pkg, int callingUid) {
17701        // The system owns everything.
17702        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17703            return;
17704        }
17705        int callingUserId = UserHandle.getUserId(callingUid);
17706        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17707        if (pi == null) {
17708            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17709                    + callingUserId);
17710        }
17711        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17712            throw new SecurityException("Calling uid " + callingUid
17713                    + " does not own package " + pkg);
17714        }
17715    }
17716
17717    @Override
17718    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17719        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17720    }
17721
17722    private Intent getHomeIntent() {
17723        Intent intent = new Intent(Intent.ACTION_MAIN);
17724        intent.addCategory(Intent.CATEGORY_HOME);
17725        intent.addCategory(Intent.CATEGORY_DEFAULT);
17726        return intent;
17727    }
17728
17729    private IntentFilter getHomeFilter() {
17730        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17731        filter.addCategory(Intent.CATEGORY_HOME);
17732        filter.addCategory(Intent.CATEGORY_DEFAULT);
17733        return filter;
17734    }
17735
17736    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17737            int userId) {
17738        Intent intent  = getHomeIntent();
17739        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17740                PackageManager.GET_META_DATA, userId);
17741        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17742                true, false, false, userId);
17743
17744        allHomeCandidates.clear();
17745        if (list != null) {
17746            for (ResolveInfo ri : list) {
17747                allHomeCandidates.add(ri);
17748            }
17749        }
17750        return (preferred == null || preferred.activityInfo == null)
17751                ? null
17752                : new ComponentName(preferred.activityInfo.packageName,
17753                        preferred.activityInfo.name);
17754    }
17755
17756    @Override
17757    public void setHomeActivity(ComponentName comp, int userId) {
17758        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17759        getHomeActivitiesAsUser(homeActivities, userId);
17760
17761        boolean found = false;
17762
17763        final int size = homeActivities.size();
17764        final ComponentName[] set = new ComponentName[size];
17765        for (int i = 0; i < size; i++) {
17766            final ResolveInfo candidate = homeActivities.get(i);
17767            final ActivityInfo info = candidate.activityInfo;
17768            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17769            set[i] = activityName;
17770            if (!found && activityName.equals(comp)) {
17771                found = true;
17772            }
17773        }
17774        if (!found) {
17775            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17776                    + userId);
17777        }
17778        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17779                set, comp, userId);
17780    }
17781
17782    private @Nullable String getSetupWizardPackageName() {
17783        final Intent intent = new Intent(Intent.ACTION_MAIN);
17784        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17785
17786        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17787                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17788                        | MATCH_DISABLED_COMPONENTS,
17789                UserHandle.myUserId());
17790        if (matches.size() == 1) {
17791            return matches.get(0).getComponentInfo().packageName;
17792        } else {
17793            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17794                    + ": matches=" + matches);
17795            return null;
17796        }
17797    }
17798
17799    private @Nullable String getStorageManagerPackageName() {
17800        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17801
17802        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17803                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17804                        | MATCH_DISABLED_COMPONENTS,
17805                UserHandle.myUserId());
17806        if (matches.size() == 1) {
17807            return matches.get(0).getComponentInfo().packageName;
17808        } else {
17809            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17810                    + matches.size() + ": matches=" + matches);
17811            return null;
17812        }
17813    }
17814
17815    @Override
17816    public void setApplicationEnabledSetting(String appPackageName,
17817            int newState, int flags, int userId, String callingPackage) {
17818        if (!sUserManager.exists(userId)) return;
17819        if (callingPackage == null) {
17820            callingPackage = Integer.toString(Binder.getCallingUid());
17821        }
17822        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17823    }
17824
17825    @Override
17826    public void setComponentEnabledSetting(ComponentName componentName,
17827            int newState, int flags, int userId) {
17828        if (!sUserManager.exists(userId)) return;
17829        setEnabledSetting(componentName.getPackageName(),
17830                componentName.getClassName(), newState, flags, userId, null);
17831    }
17832
17833    private void setEnabledSetting(final String packageName, String className, int newState,
17834            final int flags, int userId, String callingPackage) {
17835        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17836              || newState == COMPONENT_ENABLED_STATE_ENABLED
17837              || newState == COMPONENT_ENABLED_STATE_DISABLED
17838              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17839              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17840            throw new IllegalArgumentException("Invalid new component state: "
17841                    + newState);
17842        }
17843        PackageSetting pkgSetting;
17844        final int uid = Binder.getCallingUid();
17845        final int permission;
17846        if (uid == Process.SYSTEM_UID) {
17847            permission = PackageManager.PERMISSION_GRANTED;
17848        } else {
17849            permission = mContext.checkCallingOrSelfPermission(
17850                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17851        }
17852        enforceCrossUserPermission(uid, userId,
17853                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17854        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17855        boolean sendNow = false;
17856        boolean isApp = (className == null);
17857        String componentName = isApp ? packageName : className;
17858        int packageUid = -1;
17859        ArrayList<String> components;
17860
17861        // writer
17862        synchronized (mPackages) {
17863            pkgSetting = mSettings.mPackages.get(packageName);
17864            if (pkgSetting == null) {
17865                if (className == null) {
17866                    throw new IllegalArgumentException("Unknown package: " + packageName);
17867                }
17868                throw new IllegalArgumentException(
17869                        "Unknown component: " + packageName + "/" + className);
17870            }
17871        }
17872
17873        // Limit who can change which apps
17874        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17875            // Don't allow apps that don't have permission to modify other apps
17876            if (!allowedByPermission) {
17877                throw new SecurityException(
17878                        "Permission Denial: attempt to change component state from pid="
17879                        + Binder.getCallingPid()
17880                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17881            }
17882            // Don't allow changing protected packages.
17883            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17884                throw new SecurityException("Cannot disable a protected package: " + packageName);
17885            }
17886        }
17887
17888        synchronized (mPackages) {
17889            if (uid == Process.SHELL_UID) {
17890                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17891                int oldState = pkgSetting.getEnabled(userId);
17892                if (className == null
17893                    &&
17894                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17895                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17896                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17897                    &&
17898                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17899                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17900                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17901                    // ok
17902                } else {
17903                    throw new SecurityException(
17904                            "Shell cannot change component state for " + packageName + "/"
17905                            + className + " to " + newState);
17906                }
17907            }
17908            if (className == null) {
17909                // We're dealing with an application/package level state change
17910                if (pkgSetting.getEnabled(userId) == newState) {
17911                    // Nothing to do
17912                    return;
17913                }
17914                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17915                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17916                    // Don't care about who enables an app.
17917                    callingPackage = null;
17918                }
17919                pkgSetting.setEnabled(newState, userId, callingPackage);
17920                // pkgSetting.pkg.mSetEnabled = newState;
17921            } else {
17922                // We're dealing with a component level state change
17923                // First, verify that this is a valid class name.
17924                PackageParser.Package pkg = pkgSetting.pkg;
17925                if (pkg == null || !pkg.hasComponentClassName(className)) {
17926                    if (pkg != null &&
17927                            pkg.applicationInfo.targetSdkVersion >=
17928                                    Build.VERSION_CODES.JELLY_BEAN) {
17929                        throw new IllegalArgumentException("Component class " + className
17930                                + " does not exist in " + packageName);
17931                    } else {
17932                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17933                                + className + " does not exist in " + packageName);
17934                    }
17935                }
17936                switch (newState) {
17937                case COMPONENT_ENABLED_STATE_ENABLED:
17938                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17939                        return;
17940                    }
17941                    break;
17942                case COMPONENT_ENABLED_STATE_DISABLED:
17943                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17944                        return;
17945                    }
17946                    break;
17947                case COMPONENT_ENABLED_STATE_DEFAULT:
17948                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17949                        return;
17950                    }
17951                    break;
17952                default:
17953                    Slog.e(TAG, "Invalid new component state: " + newState);
17954                    return;
17955                }
17956            }
17957            scheduleWritePackageRestrictionsLocked(userId);
17958            components = mPendingBroadcasts.get(userId, packageName);
17959            final boolean newPackage = components == null;
17960            if (newPackage) {
17961                components = new ArrayList<String>();
17962            }
17963            if (!components.contains(componentName)) {
17964                components.add(componentName);
17965            }
17966            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17967                sendNow = true;
17968                // Purge entry from pending broadcast list if another one exists already
17969                // since we are sending one right away.
17970                mPendingBroadcasts.remove(userId, packageName);
17971            } else {
17972                if (newPackage) {
17973                    mPendingBroadcasts.put(userId, packageName, components);
17974                }
17975                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17976                    // Schedule a message
17977                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17978                }
17979            }
17980        }
17981
17982        long callingId = Binder.clearCallingIdentity();
17983        try {
17984            if (sendNow) {
17985                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17986                sendPackageChangedBroadcast(packageName,
17987                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17988            }
17989        } finally {
17990            Binder.restoreCallingIdentity(callingId);
17991        }
17992    }
17993
17994    @Override
17995    public void flushPackageRestrictionsAsUser(int userId) {
17996        if (!sUserManager.exists(userId)) {
17997            return;
17998        }
17999        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18000                false /* checkShell */, "flushPackageRestrictions");
18001        synchronized (mPackages) {
18002            mSettings.writePackageRestrictionsLPr(userId);
18003            mDirtyUsers.remove(userId);
18004            if (mDirtyUsers.isEmpty()) {
18005                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18006            }
18007        }
18008    }
18009
18010    private void sendPackageChangedBroadcast(String packageName,
18011            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18012        if (DEBUG_INSTALL)
18013            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18014                    + componentNames);
18015        Bundle extras = new Bundle(4);
18016        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18017        String nameList[] = new String[componentNames.size()];
18018        componentNames.toArray(nameList);
18019        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18020        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18021        extras.putInt(Intent.EXTRA_UID, packageUid);
18022        // If this is not reporting a change of the overall package, then only send it
18023        // to registered receivers.  We don't want to launch a swath of apps for every
18024        // little component state change.
18025        final int flags = !componentNames.contains(packageName)
18026                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18027        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18028                new int[] {UserHandle.getUserId(packageUid)});
18029    }
18030
18031    @Override
18032    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18033        if (!sUserManager.exists(userId)) return;
18034        final int uid = Binder.getCallingUid();
18035        final int permission = mContext.checkCallingOrSelfPermission(
18036                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18037        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18038        enforceCrossUserPermission(uid, userId,
18039                true /* requireFullPermission */, true /* checkShell */, "stop package");
18040        // writer
18041        synchronized (mPackages) {
18042            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18043                    allowedByPermission, uid, userId)) {
18044                scheduleWritePackageRestrictionsLocked(userId);
18045            }
18046        }
18047    }
18048
18049    @Override
18050    public String getInstallerPackageName(String packageName) {
18051        // reader
18052        synchronized (mPackages) {
18053            return mSettings.getInstallerPackageNameLPr(packageName);
18054        }
18055    }
18056
18057    public boolean isOrphaned(String packageName) {
18058        // reader
18059        synchronized (mPackages) {
18060            return mSettings.isOrphaned(packageName);
18061        }
18062    }
18063
18064    @Override
18065    public int getApplicationEnabledSetting(String packageName, int userId) {
18066        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18067        int uid = Binder.getCallingUid();
18068        enforceCrossUserPermission(uid, userId,
18069                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18070        // reader
18071        synchronized (mPackages) {
18072            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18073        }
18074    }
18075
18076    @Override
18077    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18078        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18079        int uid = Binder.getCallingUid();
18080        enforceCrossUserPermission(uid, userId,
18081                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18082        // reader
18083        synchronized (mPackages) {
18084            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18085        }
18086    }
18087
18088    @Override
18089    public void enterSafeMode() {
18090        enforceSystemOrRoot("Only the system can request entering safe mode");
18091
18092        if (!mSystemReady) {
18093            mSafeMode = true;
18094        }
18095    }
18096
18097    @Override
18098    public void systemReady() {
18099        mSystemReady = true;
18100
18101        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18102        // disabled after already being started.
18103        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18104                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18105
18106        // Read the compatibilty setting when the system is ready.
18107        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18108                mContext.getContentResolver(),
18109                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18110        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18111        if (DEBUG_SETTINGS) {
18112            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18113        }
18114
18115        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18116
18117        synchronized (mPackages) {
18118            // Verify that all of the preferred activity components actually
18119            // exist.  It is possible for applications to be updated and at
18120            // that point remove a previously declared activity component that
18121            // had been set as a preferred activity.  We try to clean this up
18122            // the next time we encounter that preferred activity, but it is
18123            // possible for the user flow to never be able to return to that
18124            // situation so here we do a sanity check to make sure we haven't
18125            // left any junk around.
18126            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18127            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18128                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18129                removed.clear();
18130                for (PreferredActivity pa : pir.filterSet()) {
18131                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18132                        removed.add(pa);
18133                    }
18134                }
18135                if (removed.size() > 0) {
18136                    for (int r=0; r<removed.size(); r++) {
18137                        PreferredActivity pa = removed.get(r);
18138                        Slog.w(TAG, "Removing dangling preferred activity: "
18139                                + pa.mPref.mComponent);
18140                        pir.removeFilter(pa);
18141                    }
18142                    mSettings.writePackageRestrictionsLPr(
18143                            mSettings.mPreferredActivities.keyAt(i));
18144                }
18145            }
18146
18147            for (int userId : UserManagerService.getInstance().getUserIds()) {
18148                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18149                    grantPermissionsUserIds = ArrayUtils.appendInt(
18150                            grantPermissionsUserIds, userId);
18151                }
18152            }
18153        }
18154        sUserManager.systemReady();
18155
18156        // If we upgraded grant all default permissions before kicking off.
18157        for (int userId : grantPermissionsUserIds) {
18158            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18159        }
18160
18161        // If we did not grant default permissions, we preload from this the
18162        // default permission exceptions lazily to ensure we don't hit the
18163        // disk on a new user creation.
18164        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18165            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18166        }
18167
18168        // Kick off any messages waiting for system ready
18169        if (mPostSystemReadyMessages != null) {
18170            for (Message msg : mPostSystemReadyMessages) {
18171                msg.sendToTarget();
18172            }
18173            mPostSystemReadyMessages = null;
18174        }
18175
18176        // Watch for external volumes that come and go over time
18177        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18178        storage.registerListener(mStorageListener);
18179
18180        mInstallerService.systemReady();
18181        mPackageDexOptimizer.systemReady();
18182
18183        MountServiceInternal mountServiceInternal = LocalServices.getService(
18184                MountServiceInternal.class);
18185        mountServiceInternal.addExternalStoragePolicy(
18186                new MountServiceInternal.ExternalStorageMountPolicy() {
18187            @Override
18188            public int getMountMode(int uid, String packageName) {
18189                if (Process.isIsolated(uid)) {
18190                    return Zygote.MOUNT_EXTERNAL_NONE;
18191                }
18192                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18193                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18194                }
18195                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18196                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18197                }
18198                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18199                    return Zygote.MOUNT_EXTERNAL_READ;
18200                }
18201                return Zygote.MOUNT_EXTERNAL_WRITE;
18202            }
18203
18204            @Override
18205            public boolean hasExternalStorage(int uid, String packageName) {
18206                return true;
18207            }
18208        });
18209
18210        // Now that we're mostly running, clean up stale users and apps
18211        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18212        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18213    }
18214
18215    @Override
18216    public boolean isSafeMode() {
18217        return mSafeMode;
18218    }
18219
18220    @Override
18221    public boolean hasSystemUidErrors() {
18222        return mHasSystemUidErrors;
18223    }
18224
18225    static String arrayToString(int[] array) {
18226        StringBuffer buf = new StringBuffer(128);
18227        buf.append('[');
18228        if (array != null) {
18229            for (int i=0; i<array.length; i++) {
18230                if (i > 0) buf.append(", ");
18231                buf.append(array[i]);
18232            }
18233        }
18234        buf.append(']');
18235        return buf.toString();
18236    }
18237
18238    static class DumpState {
18239        public static final int DUMP_LIBS = 1 << 0;
18240        public static final int DUMP_FEATURES = 1 << 1;
18241        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18242        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18243        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18244        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18245        public static final int DUMP_PERMISSIONS = 1 << 6;
18246        public static final int DUMP_PACKAGES = 1 << 7;
18247        public static final int DUMP_SHARED_USERS = 1 << 8;
18248        public static final int DUMP_MESSAGES = 1 << 9;
18249        public static final int DUMP_PROVIDERS = 1 << 10;
18250        public static final int DUMP_VERIFIERS = 1 << 11;
18251        public static final int DUMP_PREFERRED = 1 << 12;
18252        public static final int DUMP_PREFERRED_XML = 1 << 13;
18253        public static final int DUMP_KEYSETS = 1 << 14;
18254        public static final int DUMP_VERSION = 1 << 15;
18255        public static final int DUMP_INSTALLS = 1 << 16;
18256        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18257        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18258        public static final int DUMP_FROZEN = 1 << 19;
18259        public static final int DUMP_DEXOPT = 1 << 20;
18260        public static final int DUMP_COMPILER_STATS = 1 << 21;
18261
18262        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18263
18264        private int mTypes;
18265
18266        private int mOptions;
18267
18268        private boolean mTitlePrinted;
18269
18270        private SharedUserSetting mSharedUser;
18271
18272        public boolean isDumping(int type) {
18273            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18274                return true;
18275            }
18276
18277            return (mTypes & type) != 0;
18278        }
18279
18280        public void setDump(int type) {
18281            mTypes |= type;
18282        }
18283
18284        public boolean isOptionEnabled(int option) {
18285            return (mOptions & option) != 0;
18286        }
18287
18288        public void setOptionEnabled(int option) {
18289            mOptions |= option;
18290        }
18291
18292        public boolean onTitlePrinted() {
18293            final boolean printed = mTitlePrinted;
18294            mTitlePrinted = true;
18295            return printed;
18296        }
18297
18298        public boolean getTitlePrinted() {
18299            return mTitlePrinted;
18300        }
18301
18302        public void setTitlePrinted(boolean enabled) {
18303            mTitlePrinted = enabled;
18304        }
18305
18306        public SharedUserSetting getSharedUser() {
18307            return mSharedUser;
18308        }
18309
18310        public void setSharedUser(SharedUserSetting user) {
18311            mSharedUser = user;
18312        }
18313    }
18314
18315    @Override
18316    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18317            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18318        (new PackageManagerShellCommand(this)).exec(
18319                this, in, out, err, args, resultReceiver);
18320    }
18321
18322    @Override
18323    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18324        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18325                != PackageManager.PERMISSION_GRANTED) {
18326            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18327                    + Binder.getCallingPid()
18328                    + ", uid=" + Binder.getCallingUid()
18329                    + " without permission "
18330                    + android.Manifest.permission.DUMP);
18331            return;
18332        }
18333
18334        DumpState dumpState = new DumpState();
18335        boolean fullPreferred = false;
18336        boolean checkin = false;
18337
18338        String packageName = null;
18339        ArraySet<String> permissionNames = null;
18340
18341        int opti = 0;
18342        while (opti < args.length) {
18343            String opt = args[opti];
18344            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18345                break;
18346            }
18347            opti++;
18348
18349            if ("-a".equals(opt)) {
18350                // Right now we only know how to print all.
18351            } else if ("-h".equals(opt)) {
18352                pw.println("Package manager dump options:");
18353                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18354                pw.println("    --checkin: dump for a checkin");
18355                pw.println("    -f: print details of intent filters");
18356                pw.println("    -h: print this help");
18357                pw.println("  cmd may be one of:");
18358                pw.println("    l[ibraries]: list known shared libraries");
18359                pw.println("    f[eatures]: list device features");
18360                pw.println("    k[eysets]: print known keysets");
18361                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18362                pw.println("    perm[issions]: dump permissions");
18363                pw.println("    permission [name ...]: dump declaration and use of given permission");
18364                pw.println("    pref[erred]: print preferred package settings");
18365                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18366                pw.println("    prov[iders]: dump content providers");
18367                pw.println("    p[ackages]: dump installed packages");
18368                pw.println("    s[hared-users]: dump shared user IDs");
18369                pw.println("    m[essages]: print collected runtime messages");
18370                pw.println("    v[erifiers]: print package verifier info");
18371                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18372                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18373                pw.println("    version: print database version info");
18374                pw.println("    write: write current settings now");
18375                pw.println("    installs: details about install sessions");
18376                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18377                pw.println("    dexopt: dump dexopt state");
18378                pw.println("    compiler-stats: dump compiler statistics");
18379                pw.println("    <package.name>: info about given package");
18380                return;
18381            } else if ("--checkin".equals(opt)) {
18382                checkin = true;
18383            } else if ("-f".equals(opt)) {
18384                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18385            } else {
18386                pw.println("Unknown argument: " + opt + "; use -h for help");
18387            }
18388        }
18389
18390        // Is the caller requesting to dump a particular piece of data?
18391        if (opti < args.length) {
18392            String cmd = args[opti];
18393            opti++;
18394            // Is this a package name?
18395            if ("android".equals(cmd) || cmd.contains(".")) {
18396                packageName = cmd;
18397                // When dumping a single package, we always dump all of its
18398                // filter information since the amount of data will be reasonable.
18399                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18400            } else if ("check-permission".equals(cmd)) {
18401                if (opti >= args.length) {
18402                    pw.println("Error: check-permission missing permission argument");
18403                    return;
18404                }
18405                String perm = args[opti];
18406                opti++;
18407                if (opti >= args.length) {
18408                    pw.println("Error: check-permission missing package argument");
18409                    return;
18410                }
18411                String pkg = args[opti];
18412                opti++;
18413                int user = UserHandle.getUserId(Binder.getCallingUid());
18414                if (opti < args.length) {
18415                    try {
18416                        user = Integer.parseInt(args[opti]);
18417                    } catch (NumberFormatException e) {
18418                        pw.println("Error: check-permission user argument is not a number: "
18419                                + args[opti]);
18420                        return;
18421                    }
18422                }
18423                pw.println(checkPermission(perm, pkg, user));
18424                return;
18425            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18426                dumpState.setDump(DumpState.DUMP_LIBS);
18427            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18428                dumpState.setDump(DumpState.DUMP_FEATURES);
18429            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18430                if (opti >= args.length) {
18431                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18432                            | DumpState.DUMP_SERVICE_RESOLVERS
18433                            | DumpState.DUMP_RECEIVER_RESOLVERS
18434                            | DumpState.DUMP_CONTENT_RESOLVERS);
18435                } else {
18436                    while (opti < args.length) {
18437                        String name = args[opti];
18438                        if ("a".equals(name) || "activity".equals(name)) {
18439                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18440                        } else if ("s".equals(name) || "service".equals(name)) {
18441                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18442                        } else if ("r".equals(name) || "receiver".equals(name)) {
18443                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18444                        } else if ("c".equals(name) || "content".equals(name)) {
18445                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18446                        } else {
18447                            pw.println("Error: unknown resolver table type: " + name);
18448                            return;
18449                        }
18450                        opti++;
18451                    }
18452                }
18453            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18454                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18455            } else if ("permission".equals(cmd)) {
18456                if (opti >= args.length) {
18457                    pw.println("Error: permission requires permission name");
18458                    return;
18459                }
18460                permissionNames = new ArraySet<>();
18461                while (opti < args.length) {
18462                    permissionNames.add(args[opti]);
18463                    opti++;
18464                }
18465                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18466                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18467            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18468                dumpState.setDump(DumpState.DUMP_PREFERRED);
18469            } else if ("preferred-xml".equals(cmd)) {
18470                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18471                if (opti < args.length && "--full".equals(args[opti])) {
18472                    fullPreferred = true;
18473                    opti++;
18474                }
18475            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18476                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18477            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18478                dumpState.setDump(DumpState.DUMP_PACKAGES);
18479            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18480                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18481            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18482                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18483            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18484                dumpState.setDump(DumpState.DUMP_MESSAGES);
18485            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18486                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18487            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18488                    || "intent-filter-verifiers".equals(cmd)) {
18489                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18490            } else if ("version".equals(cmd)) {
18491                dumpState.setDump(DumpState.DUMP_VERSION);
18492            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18493                dumpState.setDump(DumpState.DUMP_KEYSETS);
18494            } else if ("installs".equals(cmd)) {
18495                dumpState.setDump(DumpState.DUMP_INSTALLS);
18496            } else if ("frozen".equals(cmd)) {
18497                dumpState.setDump(DumpState.DUMP_FROZEN);
18498            } else if ("dexopt".equals(cmd)) {
18499                dumpState.setDump(DumpState.DUMP_DEXOPT);
18500            } else if ("compiler-stats".equals(cmd)) {
18501                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18502            } else if ("write".equals(cmd)) {
18503                synchronized (mPackages) {
18504                    mSettings.writeLPr();
18505                    pw.println("Settings written.");
18506                    return;
18507                }
18508            }
18509        }
18510
18511        if (checkin) {
18512            pw.println("vers,1");
18513        }
18514
18515        // reader
18516        synchronized (mPackages) {
18517            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18518                if (!checkin) {
18519                    if (dumpState.onTitlePrinted())
18520                        pw.println();
18521                    pw.println("Database versions:");
18522                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18523                }
18524            }
18525
18526            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18527                if (!checkin) {
18528                    if (dumpState.onTitlePrinted())
18529                        pw.println();
18530                    pw.println("Verifiers:");
18531                    pw.print("  Required: ");
18532                    pw.print(mRequiredVerifierPackage);
18533                    pw.print(" (uid=");
18534                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18535                            UserHandle.USER_SYSTEM));
18536                    pw.println(")");
18537                } else if (mRequiredVerifierPackage != null) {
18538                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18539                    pw.print(",");
18540                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18541                            UserHandle.USER_SYSTEM));
18542                }
18543            }
18544
18545            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18546                    packageName == null) {
18547                if (mIntentFilterVerifierComponent != null) {
18548                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18549                    if (!checkin) {
18550                        if (dumpState.onTitlePrinted())
18551                            pw.println();
18552                        pw.println("Intent Filter Verifier:");
18553                        pw.print("  Using: ");
18554                        pw.print(verifierPackageName);
18555                        pw.print(" (uid=");
18556                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18557                                UserHandle.USER_SYSTEM));
18558                        pw.println(")");
18559                    } else if (verifierPackageName != null) {
18560                        pw.print("ifv,"); pw.print(verifierPackageName);
18561                        pw.print(",");
18562                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18563                                UserHandle.USER_SYSTEM));
18564                    }
18565                } else {
18566                    pw.println();
18567                    pw.println("No Intent Filter Verifier available!");
18568                }
18569            }
18570
18571            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18572                boolean printedHeader = false;
18573                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18574                while (it.hasNext()) {
18575                    String name = it.next();
18576                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18577                    if (!checkin) {
18578                        if (!printedHeader) {
18579                            if (dumpState.onTitlePrinted())
18580                                pw.println();
18581                            pw.println("Libraries:");
18582                            printedHeader = true;
18583                        }
18584                        pw.print("  ");
18585                    } else {
18586                        pw.print("lib,");
18587                    }
18588                    pw.print(name);
18589                    if (!checkin) {
18590                        pw.print(" -> ");
18591                    }
18592                    if (ent.path != null) {
18593                        if (!checkin) {
18594                            pw.print("(jar) ");
18595                            pw.print(ent.path);
18596                        } else {
18597                            pw.print(",jar,");
18598                            pw.print(ent.path);
18599                        }
18600                    } else {
18601                        if (!checkin) {
18602                            pw.print("(apk) ");
18603                            pw.print(ent.apk);
18604                        } else {
18605                            pw.print(",apk,");
18606                            pw.print(ent.apk);
18607                        }
18608                    }
18609                    pw.println();
18610                }
18611            }
18612
18613            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18614                if (dumpState.onTitlePrinted())
18615                    pw.println();
18616                if (!checkin) {
18617                    pw.println("Features:");
18618                }
18619
18620                for (FeatureInfo feat : mAvailableFeatures.values()) {
18621                    if (checkin) {
18622                        pw.print("feat,");
18623                        pw.print(feat.name);
18624                        pw.print(",");
18625                        pw.println(feat.version);
18626                    } else {
18627                        pw.print("  ");
18628                        pw.print(feat.name);
18629                        if (feat.version > 0) {
18630                            pw.print(" version=");
18631                            pw.print(feat.version);
18632                        }
18633                        pw.println();
18634                    }
18635                }
18636            }
18637
18638            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18639                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18640                        : "Activity Resolver Table:", "  ", packageName,
18641                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18642                    dumpState.setTitlePrinted(true);
18643                }
18644            }
18645            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18646                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18647                        : "Receiver Resolver Table:", "  ", packageName,
18648                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18649                    dumpState.setTitlePrinted(true);
18650                }
18651            }
18652            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18653                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18654                        : "Service Resolver Table:", "  ", packageName,
18655                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18656                    dumpState.setTitlePrinted(true);
18657                }
18658            }
18659            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18660                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18661                        : "Provider Resolver Table:", "  ", packageName,
18662                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18663                    dumpState.setTitlePrinted(true);
18664                }
18665            }
18666
18667            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18668                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18669                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18670                    int user = mSettings.mPreferredActivities.keyAt(i);
18671                    if (pir.dump(pw,
18672                            dumpState.getTitlePrinted()
18673                                ? "\nPreferred Activities User " + user + ":"
18674                                : "Preferred Activities User " + user + ":", "  ",
18675                            packageName, true, false)) {
18676                        dumpState.setTitlePrinted(true);
18677                    }
18678                }
18679            }
18680
18681            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18682                pw.flush();
18683                FileOutputStream fout = new FileOutputStream(fd);
18684                BufferedOutputStream str = new BufferedOutputStream(fout);
18685                XmlSerializer serializer = new FastXmlSerializer();
18686                try {
18687                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18688                    serializer.startDocument(null, true);
18689                    serializer.setFeature(
18690                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18691                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18692                    serializer.endDocument();
18693                    serializer.flush();
18694                } catch (IllegalArgumentException e) {
18695                    pw.println("Failed writing: " + e);
18696                } catch (IllegalStateException e) {
18697                    pw.println("Failed writing: " + e);
18698                } catch (IOException e) {
18699                    pw.println("Failed writing: " + e);
18700                }
18701            }
18702
18703            if (!checkin
18704                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18705                    && packageName == null) {
18706                pw.println();
18707                int count = mSettings.mPackages.size();
18708                if (count == 0) {
18709                    pw.println("No applications!");
18710                    pw.println();
18711                } else {
18712                    final String prefix = "  ";
18713                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18714                    if (allPackageSettings.size() == 0) {
18715                        pw.println("No domain preferred apps!");
18716                        pw.println();
18717                    } else {
18718                        pw.println("App verification status:");
18719                        pw.println();
18720                        count = 0;
18721                        for (PackageSetting ps : allPackageSettings) {
18722                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18723                            if (ivi == null || ivi.getPackageName() == null) continue;
18724                            pw.println(prefix + "Package: " + ivi.getPackageName());
18725                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18726                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18727                            pw.println();
18728                            count++;
18729                        }
18730                        if (count == 0) {
18731                            pw.println(prefix + "No app verification established.");
18732                            pw.println();
18733                        }
18734                        for (int userId : sUserManager.getUserIds()) {
18735                            pw.println("App linkages for user " + userId + ":");
18736                            pw.println();
18737                            count = 0;
18738                            for (PackageSetting ps : allPackageSettings) {
18739                                final long status = ps.getDomainVerificationStatusForUser(userId);
18740                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18741                                    continue;
18742                                }
18743                                pw.println(prefix + "Package: " + ps.name);
18744                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18745                                String statusStr = IntentFilterVerificationInfo.
18746                                        getStatusStringFromValue(status);
18747                                pw.println(prefix + "Status:  " + statusStr);
18748                                pw.println();
18749                                count++;
18750                            }
18751                            if (count == 0) {
18752                                pw.println(prefix + "No configured app linkages.");
18753                                pw.println();
18754                            }
18755                        }
18756                    }
18757                }
18758            }
18759
18760            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18761                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18762                if (packageName == null && permissionNames == null) {
18763                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18764                        if (iperm == 0) {
18765                            if (dumpState.onTitlePrinted())
18766                                pw.println();
18767                            pw.println("AppOp Permissions:");
18768                        }
18769                        pw.print("  AppOp Permission ");
18770                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18771                        pw.println(":");
18772                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18773                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18774                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18775                        }
18776                    }
18777                }
18778            }
18779
18780            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18781                boolean printedSomething = false;
18782                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18783                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18784                        continue;
18785                    }
18786                    if (!printedSomething) {
18787                        if (dumpState.onTitlePrinted())
18788                            pw.println();
18789                        pw.println("Registered ContentProviders:");
18790                        printedSomething = true;
18791                    }
18792                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18793                    pw.print("    "); pw.println(p.toString());
18794                }
18795                printedSomething = false;
18796                for (Map.Entry<String, PackageParser.Provider> entry :
18797                        mProvidersByAuthority.entrySet()) {
18798                    PackageParser.Provider p = entry.getValue();
18799                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18800                        continue;
18801                    }
18802                    if (!printedSomething) {
18803                        if (dumpState.onTitlePrinted())
18804                            pw.println();
18805                        pw.println("ContentProvider Authorities:");
18806                        printedSomething = true;
18807                    }
18808                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18809                    pw.print("    "); pw.println(p.toString());
18810                    if (p.info != null && p.info.applicationInfo != null) {
18811                        final String appInfo = p.info.applicationInfo.toString();
18812                        pw.print("      applicationInfo="); pw.println(appInfo);
18813                    }
18814                }
18815            }
18816
18817            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18818                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18819            }
18820
18821            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18822                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18823            }
18824
18825            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18826                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18827            }
18828
18829            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18830                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18831            }
18832
18833            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18834                // XXX should handle packageName != null by dumping only install data that
18835                // the given package is involved with.
18836                if (dumpState.onTitlePrinted()) pw.println();
18837                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18838            }
18839
18840            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18841                // XXX should handle packageName != null by dumping only install data that
18842                // the given package is involved with.
18843                if (dumpState.onTitlePrinted()) pw.println();
18844
18845                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18846                ipw.println();
18847                ipw.println("Frozen packages:");
18848                ipw.increaseIndent();
18849                if (mFrozenPackages.size() == 0) {
18850                    ipw.println("(none)");
18851                } else {
18852                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18853                        ipw.println(mFrozenPackages.valueAt(i));
18854                    }
18855                }
18856                ipw.decreaseIndent();
18857            }
18858
18859            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18860                if (dumpState.onTitlePrinted()) pw.println();
18861                dumpDexoptStateLPr(pw, packageName);
18862            }
18863
18864            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18865                if (dumpState.onTitlePrinted()) pw.println();
18866                dumpCompilerStatsLPr(pw, packageName);
18867            }
18868
18869            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18870                if (dumpState.onTitlePrinted()) pw.println();
18871                mSettings.dumpReadMessagesLPr(pw, dumpState);
18872
18873                pw.println();
18874                pw.println("Package warning messages:");
18875                BufferedReader in = null;
18876                String line = null;
18877                try {
18878                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18879                    while ((line = in.readLine()) != null) {
18880                        if (line.contains("ignored: updated version")) continue;
18881                        pw.println(line);
18882                    }
18883                } catch (IOException ignored) {
18884                } finally {
18885                    IoUtils.closeQuietly(in);
18886                }
18887            }
18888
18889            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18890                BufferedReader in = null;
18891                String line = null;
18892                try {
18893                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18894                    while ((line = in.readLine()) != null) {
18895                        if (line.contains("ignored: updated version")) continue;
18896                        pw.print("msg,");
18897                        pw.println(line);
18898                    }
18899                } catch (IOException ignored) {
18900                } finally {
18901                    IoUtils.closeQuietly(in);
18902                }
18903            }
18904        }
18905    }
18906
18907    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18908        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18909        ipw.println();
18910        ipw.println("Dexopt state:");
18911        ipw.increaseIndent();
18912        Collection<PackageParser.Package> packages = null;
18913        if (packageName != null) {
18914            PackageParser.Package targetPackage = mPackages.get(packageName);
18915            if (targetPackage != null) {
18916                packages = Collections.singletonList(targetPackage);
18917            } else {
18918                ipw.println("Unable to find package: " + packageName);
18919                return;
18920            }
18921        } else {
18922            packages = mPackages.values();
18923        }
18924
18925        for (PackageParser.Package pkg : packages) {
18926            ipw.println("[" + pkg.packageName + "]");
18927            ipw.increaseIndent();
18928            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18929            ipw.decreaseIndent();
18930        }
18931    }
18932
18933    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18934        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18935        ipw.println();
18936        ipw.println("Compiler stats:");
18937        ipw.increaseIndent();
18938        Collection<PackageParser.Package> packages = null;
18939        if (packageName != null) {
18940            PackageParser.Package targetPackage = mPackages.get(packageName);
18941            if (targetPackage != null) {
18942                packages = Collections.singletonList(targetPackage);
18943            } else {
18944                ipw.println("Unable to find package: " + packageName);
18945                return;
18946            }
18947        } else {
18948            packages = mPackages.values();
18949        }
18950
18951        for (PackageParser.Package pkg : packages) {
18952            ipw.println("[" + pkg.packageName + "]");
18953            ipw.increaseIndent();
18954
18955            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18956            if (stats == null) {
18957                ipw.println("(No recorded stats)");
18958            } else {
18959                stats.dump(ipw);
18960            }
18961            ipw.decreaseIndent();
18962        }
18963    }
18964
18965    private String dumpDomainString(String packageName) {
18966        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18967                .getList();
18968        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18969
18970        ArraySet<String> result = new ArraySet<>();
18971        if (iviList.size() > 0) {
18972            for (IntentFilterVerificationInfo ivi : iviList) {
18973                for (String host : ivi.getDomains()) {
18974                    result.add(host);
18975                }
18976            }
18977        }
18978        if (filters != null && filters.size() > 0) {
18979            for (IntentFilter filter : filters) {
18980                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18981                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18982                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18983                    result.addAll(filter.getHostsList());
18984                }
18985            }
18986        }
18987
18988        StringBuilder sb = new StringBuilder(result.size() * 16);
18989        for (String domain : result) {
18990            if (sb.length() > 0) sb.append(" ");
18991            sb.append(domain);
18992        }
18993        return sb.toString();
18994    }
18995
18996    // ------- apps on sdcard specific code -------
18997    static final boolean DEBUG_SD_INSTALL = false;
18998
18999    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19000
19001    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19002
19003    private boolean mMediaMounted = false;
19004
19005    static String getEncryptKey() {
19006        try {
19007            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19008                    SD_ENCRYPTION_KEYSTORE_NAME);
19009            if (sdEncKey == null) {
19010                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19011                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19012                if (sdEncKey == null) {
19013                    Slog.e(TAG, "Failed to create encryption keys");
19014                    return null;
19015                }
19016            }
19017            return sdEncKey;
19018        } catch (NoSuchAlgorithmException nsae) {
19019            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19020            return null;
19021        } catch (IOException ioe) {
19022            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19023            return null;
19024        }
19025    }
19026
19027    /*
19028     * Update media status on PackageManager.
19029     */
19030    @Override
19031    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19032        int callingUid = Binder.getCallingUid();
19033        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19034            throw new SecurityException("Media status can only be updated by the system");
19035        }
19036        // reader; this apparently protects mMediaMounted, but should probably
19037        // be a different lock in that case.
19038        synchronized (mPackages) {
19039            Log.i(TAG, "Updating external media status from "
19040                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19041                    + (mediaStatus ? "mounted" : "unmounted"));
19042            if (DEBUG_SD_INSTALL)
19043                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19044                        + ", mMediaMounted=" + mMediaMounted);
19045            if (mediaStatus == mMediaMounted) {
19046                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19047                        : 0, -1);
19048                mHandler.sendMessage(msg);
19049                return;
19050            }
19051            mMediaMounted = mediaStatus;
19052        }
19053        // Queue up an async operation since the package installation may take a
19054        // little while.
19055        mHandler.post(new Runnable() {
19056            public void run() {
19057                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19058            }
19059        });
19060    }
19061
19062    /**
19063     * Called by MountService when the initial ASECs to scan are available.
19064     * Should block until all the ASEC containers are finished being scanned.
19065     */
19066    public void scanAvailableAsecs() {
19067        updateExternalMediaStatusInner(true, false, false);
19068    }
19069
19070    /*
19071     * Collect information of applications on external media, map them against
19072     * existing containers and update information based on current mount status.
19073     * Please note that we always have to report status if reportStatus has been
19074     * set to true especially when unloading packages.
19075     */
19076    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19077            boolean externalStorage) {
19078        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19079        int[] uidArr = EmptyArray.INT;
19080
19081        final String[] list = PackageHelper.getSecureContainerList();
19082        if (ArrayUtils.isEmpty(list)) {
19083            Log.i(TAG, "No secure containers found");
19084        } else {
19085            // Process list of secure containers and categorize them
19086            // as active or stale based on their package internal state.
19087
19088            // reader
19089            synchronized (mPackages) {
19090                for (String cid : list) {
19091                    // Leave stages untouched for now; installer service owns them
19092                    if (PackageInstallerService.isStageName(cid)) continue;
19093
19094                    if (DEBUG_SD_INSTALL)
19095                        Log.i(TAG, "Processing container " + cid);
19096                    String pkgName = getAsecPackageName(cid);
19097                    if (pkgName == null) {
19098                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19099                        continue;
19100                    }
19101                    if (DEBUG_SD_INSTALL)
19102                        Log.i(TAG, "Looking for pkg : " + pkgName);
19103
19104                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19105                    if (ps == null) {
19106                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19107                        continue;
19108                    }
19109
19110                    /*
19111                     * Skip packages that are not external if we're unmounting
19112                     * external storage.
19113                     */
19114                    if (externalStorage && !isMounted && !isExternal(ps)) {
19115                        continue;
19116                    }
19117
19118                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19119                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19120                    // The package status is changed only if the code path
19121                    // matches between settings and the container id.
19122                    if (ps.codePathString != null
19123                            && ps.codePathString.startsWith(args.getCodePath())) {
19124                        if (DEBUG_SD_INSTALL) {
19125                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19126                                    + " at code path: " + ps.codePathString);
19127                        }
19128
19129                        // We do have a valid package installed on sdcard
19130                        processCids.put(args, ps.codePathString);
19131                        final int uid = ps.appId;
19132                        if (uid != -1) {
19133                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19134                        }
19135                    } else {
19136                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19137                                + ps.codePathString);
19138                    }
19139                }
19140            }
19141
19142            Arrays.sort(uidArr);
19143        }
19144
19145        // Process packages with valid entries.
19146        if (isMounted) {
19147            if (DEBUG_SD_INSTALL)
19148                Log.i(TAG, "Loading packages");
19149            loadMediaPackages(processCids, uidArr, externalStorage);
19150            startCleaningPackages();
19151            mInstallerService.onSecureContainersAvailable();
19152        } else {
19153            if (DEBUG_SD_INSTALL)
19154                Log.i(TAG, "Unloading packages");
19155            unloadMediaPackages(processCids, uidArr, reportStatus);
19156        }
19157    }
19158
19159    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19160            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19161        final int size = infos.size();
19162        final String[] packageNames = new String[size];
19163        final int[] packageUids = new int[size];
19164        for (int i = 0; i < size; i++) {
19165            final ApplicationInfo info = infos.get(i);
19166            packageNames[i] = info.packageName;
19167            packageUids[i] = info.uid;
19168        }
19169        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19170                finishedReceiver);
19171    }
19172
19173    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19174            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19175        sendResourcesChangedBroadcast(mediaStatus, replacing,
19176                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19177    }
19178
19179    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19180            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19181        int size = pkgList.length;
19182        if (size > 0) {
19183            // Send broadcasts here
19184            Bundle extras = new Bundle();
19185            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19186            if (uidArr != null) {
19187                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19188            }
19189            if (replacing) {
19190                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19191            }
19192            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19193                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19194            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19195        }
19196    }
19197
19198   /*
19199     * Look at potentially valid container ids from processCids If package
19200     * information doesn't match the one on record or package scanning fails,
19201     * the cid is added to list of removeCids. We currently don't delete stale
19202     * containers.
19203     */
19204    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19205            boolean externalStorage) {
19206        ArrayList<String> pkgList = new ArrayList<String>();
19207        Set<AsecInstallArgs> keys = processCids.keySet();
19208
19209        for (AsecInstallArgs args : keys) {
19210            String codePath = processCids.get(args);
19211            if (DEBUG_SD_INSTALL)
19212                Log.i(TAG, "Loading container : " + args.cid);
19213            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19214            try {
19215                // Make sure there are no container errors first.
19216                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19217                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19218                            + " when installing from sdcard");
19219                    continue;
19220                }
19221                // Check code path here.
19222                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19223                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19224                            + " does not match one in settings " + codePath);
19225                    continue;
19226                }
19227                // Parse package
19228                int parseFlags = mDefParseFlags;
19229                if (args.isExternalAsec()) {
19230                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19231                }
19232                if (args.isFwdLocked()) {
19233                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19234                }
19235
19236                synchronized (mInstallLock) {
19237                    PackageParser.Package pkg = null;
19238                    try {
19239                        // Sadly we don't know the package name yet to freeze it
19240                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19241                                SCAN_IGNORE_FROZEN, 0, null);
19242                    } catch (PackageManagerException e) {
19243                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19244                    }
19245                    // Scan the package
19246                    if (pkg != null) {
19247                        /*
19248                         * TODO why is the lock being held? doPostInstall is
19249                         * called in other places without the lock. This needs
19250                         * to be straightened out.
19251                         */
19252                        // writer
19253                        synchronized (mPackages) {
19254                            retCode = PackageManager.INSTALL_SUCCEEDED;
19255                            pkgList.add(pkg.packageName);
19256                            // Post process args
19257                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19258                                    pkg.applicationInfo.uid);
19259                        }
19260                    } else {
19261                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19262                    }
19263                }
19264
19265            } finally {
19266                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19267                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19268                }
19269            }
19270        }
19271        // writer
19272        synchronized (mPackages) {
19273            // If the platform SDK has changed since the last time we booted,
19274            // we need to re-grant app permission to catch any new ones that
19275            // appear. This is really a hack, and means that apps can in some
19276            // cases get permissions that the user didn't initially explicitly
19277            // allow... it would be nice to have some better way to handle
19278            // this situation.
19279            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19280                    : mSettings.getInternalVersion();
19281            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19282                    : StorageManager.UUID_PRIVATE_INTERNAL;
19283
19284            int updateFlags = UPDATE_PERMISSIONS_ALL;
19285            if (ver.sdkVersion != mSdkVersion) {
19286                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19287                        + mSdkVersion + "; regranting permissions for external");
19288                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19289            }
19290            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19291
19292            // Yay, everything is now upgraded
19293            ver.forceCurrent();
19294
19295            // can downgrade to reader
19296            // Persist settings
19297            mSettings.writeLPr();
19298        }
19299        // Send a broadcast to let everyone know we are done processing
19300        if (pkgList.size() > 0) {
19301            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19302        }
19303    }
19304
19305   /*
19306     * Utility method to unload a list of specified containers
19307     */
19308    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19309        // Just unmount all valid containers.
19310        for (AsecInstallArgs arg : cidArgs) {
19311            synchronized (mInstallLock) {
19312                arg.doPostDeleteLI(false);
19313           }
19314       }
19315   }
19316
19317    /*
19318     * Unload packages mounted on external media. This involves deleting package
19319     * data from internal structures, sending broadcasts about disabled packages,
19320     * gc'ing to free up references, unmounting all secure containers
19321     * corresponding to packages on external media, and posting a
19322     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19323     * that we always have to post this message if status has been requested no
19324     * matter what.
19325     */
19326    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19327            final boolean reportStatus) {
19328        if (DEBUG_SD_INSTALL)
19329            Log.i(TAG, "unloading media packages");
19330        ArrayList<String> pkgList = new ArrayList<String>();
19331        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19332        final Set<AsecInstallArgs> keys = processCids.keySet();
19333        for (AsecInstallArgs args : keys) {
19334            String pkgName = args.getPackageName();
19335            if (DEBUG_SD_INSTALL)
19336                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19337            // Delete package internally
19338            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19339            synchronized (mInstallLock) {
19340                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19341                final boolean res;
19342                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19343                        "unloadMediaPackages")) {
19344                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19345                            null);
19346                }
19347                if (res) {
19348                    pkgList.add(pkgName);
19349                } else {
19350                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19351                    failedList.add(args);
19352                }
19353            }
19354        }
19355
19356        // reader
19357        synchronized (mPackages) {
19358            // We didn't update the settings after removing each package;
19359            // write them now for all packages.
19360            mSettings.writeLPr();
19361        }
19362
19363        // We have to absolutely send UPDATED_MEDIA_STATUS only
19364        // after confirming that all the receivers processed the ordered
19365        // broadcast when packages get disabled, force a gc to clean things up.
19366        // and unload all the containers.
19367        if (pkgList.size() > 0) {
19368            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19369                    new IIntentReceiver.Stub() {
19370                public void performReceive(Intent intent, int resultCode, String data,
19371                        Bundle extras, boolean ordered, boolean sticky,
19372                        int sendingUser) throws RemoteException {
19373                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19374                            reportStatus ? 1 : 0, 1, keys);
19375                    mHandler.sendMessage(msg);
19376                }
19377            });
19378        } else {
19379            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19380                    keys);
19381            mHandler.sendMessage(msg);
19382        }
19383    }
19384
19385    private void loadPrivatePackages(final VolumeInfo vol) {
19386        mHandler.post(new Runnable() {
19387            @Override
19388            public void run() {
19389                loadPrivatePackagesInner(vol);
19390            }
19391        });
19392    }
19393
19394    private void loadPrivatePackagesInner(VolumeInfo vol) {
19395        final String volumeUuid = vol.fsUuid;
19396        if (TextUtils.isEmpty(volumeUuid)) {
19397            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19398            return;
19399        }
19400
19401        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19402        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19403        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19404
19405        final VersionInfo ver;
19406        final List<PackageSetting> packages;
19407        synchronized (mPackages) {
19408            ver = mSettings.findOrCreateVersion(volumeUuid);
19409            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19410        }
19411
19412        for (PackageSetting ps : packages) {
19413            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19414            synchronized (mInstallLock) {
19415                final PackageParser.Package pkg;
19416                try {
19417                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19418                    loaded.add(pkg.applicationInfo);
19419
19420                } catch (PackageManagerException e) {
19421                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19422                }
19423
19424                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19425                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19426                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19427                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19428                }
19429            }
19430        }
19431
19432        // Reconcile app data for all started/unlocked users
19433        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19434        final UserManager um = mContext.getSystemService(UserManager.class);
19435        UserManagerInternal umInternal = getUserManagerInternal();
19436        for (UserInfo user : um.getUsers()) {
19437            final int flags;
19438            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19439                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19440            } else if (umInternal.isUserRunning(user.id)) {
19441                flags = StorageManager.FLAG_STORAGE_DE;
19442            } else {
19443                continue;
19444            }
19445
19446            try {
19447                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19448                synchronized (mInstallLock) {
19449                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19450                }
19451            } catch (IllegalStateException e) {
19452                // Device was probably ejected, and we'll process that event momentarily
19453                Slog.w(TAG, "Failed to prepare storage: " + e);
19454            }
19455        }
19456
19457        synchronized (mPackages) {
19458            int updateFlags = UPDATE_PERMISSIONS_ALL;
19459            if (ver.sdkVersion != mSdkVersion) {
19460                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19461                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19462                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19463            }
19464            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19465
19466            // Yay, everything is now upgraded
19467            ver.forceCurrent();
19468
19469            mSettings.writeLPr();
19470        }
19471
19472        for (PackageFreezer freezer : freezers) {
19473            freezer.close();
19474        }
19475
19476        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19477        sendResourcesChangedBroadcast(true, false, loaded, null);
19478    }
19479
19480    private void unloadPrivatePackages(final VolumeInfo vol) {
19481        mHandler.post(new Runnable() {
19482            @Override
19483            public void run() {
19484                unloadPrivatePackagesInner(vol);
19485            }
19486        });
19487    }
19488
19489    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19490        final String volumeUuid = vol.fsUuid;
19491        if (TextUtils.isEmpty(volumeUuid)) {
19492            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19493            return;
19494        }
19495
19496        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19497        synchronized (mInstallLock) {
19498        synchronized (mPackages) {
19499            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19500            for (PackageSetting ps : packages) {
19501                if (ps.pkg == null) continue;
19502
19503                final ApplicationInfo info = ps.pkg.applicationInfo;
19504                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19505                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19506
19507                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19508                        "unloadPrivatePackagesInner")) {
19509                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19510                            false, null)) {
19511                        unloaded.add(info);
19512                    } else {
19513                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19514                    }
19515                }
19516
19517                // Try very hard to release any references to this package
19518                // so we don't risk the system server being killed due to
19519                // open FDs
19520                AttributeCache.instance().removePackage(ps.name);
19521            }
19522
19523            mSettings.writeLPr();
19524        }
19525        }
19526
19527        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19528        sendResourcesChangedBroadcast(false, false, unloaded, null);
19529
19530        // Try very hard to release any references to this path so we don't risk
19531        // the system server being killed due to open FDs
19532        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19533
19534        for (int i = 0; i < 3; i++) {
19535            System.gc();
19536            System.runFinalization();
19537        }
19538    }
19539
19540    /**
19541     * Prepare storage areas for given user on all mounted devices.
19542     */
19543    void prepareUserData(int userId, int userSerial, int flags) {
19544        synchronized (mInstallLock) {
19545            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19546            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19547                final String volumeUuid = vol.getFsUuid();
19548                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19549            }
19550        }
19551    }
19552
19553    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19554            boolean allowRecover) {
19555        // Prepare storage and verify that serial numbers are consistent; if
19556        // there's a mismatch we need to destroy to avoid leaking data
19557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19558        try {
19559            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19560
19561            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19562                UserManagerService.enforceSerialNumber(
19563                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19564                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19565                    UserManagerService.enforceSerialNumber(
19566                            Environment.getDataSystemDeDirectory(userId), userSerial);
19567                }
19568            }
19569            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19570                UserManagerService.enforceSerialNumber(
19571                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19572                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19573                    UserManagerService.enforceSerialNumber(
19574                            Environment.getDataSystemCeDirectory(userId), userSerial);
19575                }
19576            }
19577
19578            synchronized (mInstallLock) {
19579                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19580            }
19581        } catch (Exception e) {
19582            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19583                    + " because we failed to prepare: " + e);
19584            destroyUserDataLI(volumeUuid, userId,
19585                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19586
19587            if (allowRecover) {
19588                // Try one last time; if we fail again we're really in trouble
19589                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19590            }
19591        }
19592    }
19593
19594    /**
19595     * Destroy storage areas for given user on all mounted devices.
19596     */
19597    void destroyUserData(int userId, int flags) {
19598        synchronized (mInstallLock) {
19599            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19600            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19601                final String volumeUuid = vol.getFsUuid();
19602                destroyUserDataLI(volumeUuid, userId, flags);
19603            }
19604        }
19605    }
19606
19607    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19608        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19609        try {
19610            // Clean up app data, profile data, and media data
19611            mInstaller.destroyUserData(volumeUuid, userId, flags);
19612
19613            // Clean up system data
19614            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19615                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19616                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19617                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19618                }
19619                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19620                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19621                }
19622            }
19623
19624            // Data with special labels is now gone, so finish the job
19625            storage.destroyUserStorage(volumeUuid, userId, flags);
19626
19627        } catch (Exception e) {
19628            logCriticalInfo(Log.WARN,
19629                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19630        }
19631    }
19632
19633    /**
19634     * Examine all users present on given mounted volume, and destroy data
19635     * belonging to users that are no longer valid, or whose user ID has been
19636     * recycled.
19637     */
19638    private void reconcileUsers(String volumeUuid) {
19639        final List<File> files = new ArrayList<>();
19640        Collections.addAll(files, FileUtils
19641                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19642        Collections.addAll(files, FileUtils
19643                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19644        Collections.addAll(files, FileUtils
19645                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19646        Collections.addAll(files, FileUtils
19647                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19648        for (File file : files) {
19649            if (!file.isDirectory()) continue;
19650
19651            final int userId;
19652            final UserInfo info;
19653            try {
19654                userId = Integer.parseInt(file.getName());
19655                info = sUserManager.getUserInfo(userId);
19656            } catch (NumberFormatException e) {
19657                Slog.w(TAG, "Invalid user directory " + file);
19658                continue;
19659            }
19660
19661            boolean destroyUser = false;
19662            if (info == null) {
19663                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19664                        + " because no matching user was found");
19665                destroyUser = true;
19666            } else if (!mOnlyCore) {
19667                try {
19668                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19669                } catch (IOException e) {
19670                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19671                            + " because we failed to enforce serial number: " + e);
19672                    destroyUser = true;
19673                }
19674            }
19675
19676            if (destroyUser) {
19677                synchronized (mInstallLock) {
19678                    destroyUserDataLI(volumeUuid, userId,
19679                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19680                }
19681            }
19682        }
19683    }
19684
19685    private void assertPackageKnown(String volumeUuid, String packageName)
19686            throws PackageManagerException {
19687        synchronized (mPackages) {
19688            final PackageSetting ps = mSettings.mPackages.get(packageName);
19689            if (ps == null) {
19690                throw new PackageManagerException("Package " + packageName + " is unknown");
19691            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19692                throw new PackageManagerException(
19693                        "Package " + packageName + " found on unknown volume " + volumeUuid
19694                                + "; expected volume " + ps.volumeUuid);
19695            }
19696        }
19697    }
19698
19699    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19700            throws PackageManagerException {
19701        synchronized (mPackages) {
19702            final PackageSetting ps = mSettings.mPackages.get(packageName);
19703            if (ps == null) {
19704                throw new PackageManagerException("Package " + packageName + " is unknown");
19705            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19706                throw new PackageManagerException(
19707                        "Package " + packageName + " found on unknown volume " + volumeUuid
19708                                + "; expected volume " + ps.volumeUuid);
19709            } else if (!ps.getInstalled(userId)) {
19710                throw new PackageManagerException(
19711                        "Package " + packageName + " not installed for user " + userId);
19712            }
19713        }
19714    }
19715
19716    /**
19717     * Examine all apps present on given mounted volume, and destroy apps that
19718     * aren't expected, either due to uninstallation or reinstallation on
19719     * another volume.
19720     */
19721    private void reconcileApps(String volumeUuid) {
19722        final File[] files = FileUtils
19723                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19724        for (File file : files) {
19725            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19726                    && !PackageInstallerService.isStageName(file.getName());
19727            if (!isPackage) {
19728                // Ignore entries which are not packages
19729                continue;
19730            }
19731
19732            try {
19733                final PackageLite pkg = PackageParser.parsePackageLite(file,
19734                        PackageParser.PARSE_MUST_BE_APK);
19735                assertPackageKnown(volumeUuid, pkg.packageName);
19736
19737            } catch (PackageParserException | PackageManagerException e) {
19738                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19739                synchronized (mInstallLock) {
19740                    removeCodePathLI(file);
19741                }
19742            }
19743        }
19744    }
19745
19746    /**
19747     * Reconcile all app data for the given user.
19748     * <p>
19749     * Verifies that directories exist and that ownership and labeling is
19750     * correct for all installed apps on all mounted volumes.
19751     */
19752    void reconcileAppsData(int userId, int flags) {
19753        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19754        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19755            final String volumeUuid = vol.getFsUuid();
19756            synchronized (mInstallLock) {
19757                reconcileAppsDataLI(volumeUuid, userId, flags);
19758            }
19759        }
19760    }
19761
19762    /**
19763     * Reconcile all app data on given mounted volume.
19764     * <p>
19765     * Destroys app data that isn't expected, either due to uninstallation or
19766     * reinstallation on another volume.
19767     * <p>
19768     * Verifies that directories exist and that ownership and labeling is
19769     * correct for all installed apps.
19770     */
19771    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19772        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19773                + Integer.toHexString(flags));
19774
19775        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19776        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19777
19778        boolean restoreconNeeded = false;
19779
19780        // First look for stale data that doesn't belong, and check if things
19781        // have changed since we did our last restorecon
19782        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19783            if (StorageManager.isFileEncryptedNativeOrEmulated()
19784                    && !StorageManager.isUserKeyUnlocked(userId)) {
19785                throw new RuntimeException(
19786                        "Yikes, someone asked us to reconcile CE storage while " + userId
19787                                + " was still locked; this would have caused massive data loss!");
19788            }
19789
19790            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19791
19792            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19793            for (File file : files) {
19794                final String packageName = file.getName();
19795                try {
19796                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19797                } catch (PackageManagerException e) {
19798                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19799                    try {
19800                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19801                                StorageManager.FLAG_STORAGE_CE, 0);
19802                    } catch (InstallerException e2) {
19803                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19804                    }
19805                }
19806            }
19807        }
19808        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19809            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19810
19811            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19812            for (File file : files) {
19813                final String packageName = file.getName();
19814                try {
19815                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19816                } catch (PackageManagerException e) {
19817                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19818                    try {
19819                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19820                                StorageManager.FLAG_STORAGE_DE, 0);
19821                    } catch (InstallerException e2) {
19822                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19823                    }
19824                }
19825            }
19826        }
19827
19828        // Ensure that data directories are ready to roll for all packages
19829        // installed for this volume and user
19830        final List<PackageSetting> packages;
19831        synchronized (mPackages) {
19832            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19833        }
19834        int preparedCount = 0;
19835        for (PackageSetting ps : packages) {
19836            final String packageName = ps.name;
19837            if (ps.pkg == null) {
19838                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19839                // TODO: might be due to legacy ASEC apps; we should circle back
19840                // and reconcile again once they're scanned
19841                continue;
19842            }
19843
19844            if (ps.getInstalled(userId)) {
19845                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19846
19847                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19848                    // We may have just shuffled around app data directories, so
19849                    // prepare them one more time
19850                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19851                }
19852
19853                preparedCount++;
19854            }
19855        }
19856
19857        if (restoreconNeeded) {
19858            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19859                SELinuxMMAC.setRestoreconDone(ceDir);
19860            }
19861            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19862                SELinuxMMAC.setRestoreconDone(deDir);
19863            }
19864        }
19865
19866        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19867                + " packages; restoreconNeeded was " + restoreconNeeded);
19868    }
19869
19870    /**
19871     * Prepare app data for the given app just after it was installed or
19872     * upgraded. This method carefully only touches users that it's installed
19873     * for, and it forces a restorecon to handle any seinfo changes.
19874     * <p>
19875     * Verifies that directories exist and that ownership and labeling is
19876     * correct for all installed apps. If there is an ownership mismatch, it
19877     * will try recovering system apps by wiping data; third-party app data is
19878     * left intact.
19879     * <p>
19880     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19881     */
19882    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19883        final PackageSetting ps;
19884        synchronized (mPackages) {
19885            ps = mSettings.mPackages.get(pkg.packageName);
19886            mSettings.writeKernelMappingLPr(ps);
19887        }
19888
19889        final UserManager um = mContext.getSystemService(UserManager.class);
19890        UserManagerInternal umInternal = getUserManagerInternal();
19891        for (UserInfo user : um.getUsers()) {
19892            final int flags;
19893            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19894                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19895            } else if (umInternal.isUserRunning(user.id)) {
19896                flags = StorageManager.FLAG_STORAGE_DE;
19897            } else {
19898                continue;
19899            }
19900
19901            if (ps.getInstalled(user.id)) {
19902                // Whenever an app changes, force a restorecon of its data
19903                // TODO: when user data is locked, mark that we're still dirty
19904                prepareAppDataLIF(pkg, user.id, flags, true);
19905            }
19906        }
19907    }
19908
19909    /**
19910     * Prepare app data for the given app.
19911     * <p>
19912     * Verifies that directories exist and that ownership and labeling is
19913     * correct for all installed apps. If there is an ownership mismatch, this
19914     * will try recovering system apps by wiping data; third-party app data is
19915     * left intact.
19916     */
19917    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19918            boolean restoreconNeeded) {
19919        if (pkg == null) {
19920            Slog.wtf(TAG, "Package was null!", new Throwable());
19921            return;
19922        }
19923        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19925        for (int i = 0; i < childCount; i++) {
19926            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19927        }
19928    }
19929
19930    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19931            boolean restoreconNeeded) {
19932        if (DEBUG_APP_DATA) {
19933            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19934                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19935        }
19936
19937        final String volumeUuid = pkg.volumeUuid;
19938        final String packageName = pkg.packageName;
19939        final ApplicationInfo app = pkg.applicationInfo;
19940        final int appId = UserHandle.getAppId(app.uid);
19941
19942        Preconditions.checkNotNull(app.seinfo);
19943
19944        try {
19945            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19946                    appId, app.seinfo, app.targetSdkVersion);
19947        } catch (InstallerException e) {
19948            if (app.isSystemApp()) {
19949                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19950                        + ", but trying to recover: " + e);
19951                destroyAppDataLeafLIF(pkg, userId, flags);
19952                try {
19953                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19954                            appId, app.seinfo, app.targetSdkVersion);
19955                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19956                } catch (InstallerException e2) {
19957                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19958                }
19959            } else {
19960                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19961            }
19962        }
19963
19964        if (restoreconNeeded) {
19965            try {
19966                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19967                        app.seinfo);
19968            } catch (InstallerException e) {
19969                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19970            }
19971        }
19972
19973        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19974            try {
19975                // CE storage is unlocked right now, so read out the inode and
19976                // remember for use later when it's locked
19977                // TODO: mark this structure as dirty so we persist it!
19978                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19979                        StorageManager.FLAG_STORAGE_CE);
19980                synchronized (mPackages) {
19981                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19982                    if (ps != null) {
19983                        ps.setCeDataInode(ceDataInode, userId);
19984                    }
19985                }
19986            } catch (InstallerException e) {
19987                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19988            }
19989        }
19990
19991        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19992    }
19993
19994    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19995        if (pkg == null) {
19996            Slog.wtf(TAG, "Package was null!", new Throwable());
19997            return;
19998        }
19999        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20000        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20001        for (int i = 0; i < childCount; i++) {
20002            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20003        }
20004    }
20005
20006    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20007        final String volumeUuid = pkg.volumeUuid;
20008        final String packageName = pkg.packageName;
20009        final ApplicationInfo app = pkg.applicationInfo;
20010
20011        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20012            // Create a native library symlink only if we have native libraries
20013            // and if the native libraries are 32 bit libraries. We do not provide
20014            // this symlink for 64 bit libraries.
20015            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20016                final String nativeLibPath = app.nativeLibraryDir;
20017                try {
20018                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20019                            nativeLibPath, userId);
20020                } catch (InstallerException e) {
20021                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20022                }
20023            }
20024        }
20025    }
20026
20027    /**
20028     * For system apps on non-FBE devices, this method migrates any existing
20029     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20030     * requested by the app.
20031     */
20032    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20033        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20034                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20035            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20036                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20037            try {
20038                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20039                        storageTarget);
20040            } catch (InstallerException e) {
20041                logCriticalInfo(Log.WARN,
20042                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20043            }
20044            return true;
20045        } else {
20046            return false;
20047        }
20048    }
20049
20050    public PackageFreezer freezePackage(String packageName, String killReason) {
20051        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20052    }
20053
20054    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20055        return new PackageFreezer(packageName, userId, killReason);
20056    }
20057
20058    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20059            String killReason) {
20060        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20061    }
20062
20063    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20064            String killReason) {
20065        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20066            return new PackageFreezer();
20067        } else {
20068            return freezePackage(packageName, userId, killReason);
20069        }
20070    }
20071
20072    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20073            String killReason) {
20074        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20075    }
20076
20077    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20078            String killReason) {
20079        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20080            return new PackageFreezer();
20081        } else {
20082            return freezePackage(packageName, userId, killReason);
20083        }
20084    }
20085
20086    /**
20087     * Class that freezes and kills the given package upon creation, and
20088     * unfreezes it upon closing. This is typically used when doing surgery on
20089     * app code/data to prevent the app from running while you're working.
20090     */
20091    private class PackageFreezer implements AutoCloseable {
20092        private final String mPackageName;
20093        private final PackageFreezer[] mChildren;
20094
20095        private final boolean mWeFroze;
20096
20097        private final AtomicBoolean mClosed = new AtomicBoolean();
20098        private final CloseGuard mCloseGuard = CloseGuard.get();
20099
20100        /**
20101         * Create and return a stub freezer that doesn't actually do anything,
20102         * typically used when someone requested
20103         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20104         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20105         */
20106        public PackageFreezer() {
20107            mPackageName = null;
20108            mChildren = null;
20109            mWeFroze = false;
20110            mCloseGuard.open("close");
20111        }
20112
20113        public PackageFreezer(String packageName, int userId, String killReason) {
20114            synchronized (mPackages) {
20115                mPackageName = packageName;
20116                mWeFroze = mFrozenPackages.add(mPackageName);
20117
20118                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20119                if (ps != null) {
20120                    killApplication(ps.name, ps.appId, userId, killReason);
20121                }
20122
20123                final PackageParser.Package p = mPackages.get(packageName);
20124                if (p != null && p.childPackages != null) {
20125                    final int N = p.childPackages.size();
20126                    mChildren = new PackageFreezer[N];
20127                    for (int i = 0; i < N; i++) {
20128                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20129                                userId, killReason);
20130                    }
20131                } else {
20132                    mChildren = null;
20133                }
20134            }
20135            mCloseGuard.open("close");
20136        }
20137
20138        @Override
20139        protected void finalize() throws Throwable {
20140            try {
20141                mCloseGuard.warnIfOpen();
20142                close();
20143            } finally {
20144                super.finalize();
20145            }
20146        }
20147
20148        @Override
20149        public void close() {
20150            mCloseGuard.close();
20151            if (mClosed.compareAndSet(false, true)) {
20152                synchronized (mPackages) {
20153                    if (mWeFroze) {
20154                        mFrozenPackages.remove(mPackageName);
20155                    }
20156
20157                    if (mChildren != null) {
20158                        for (PackageFreezer freezer : mChildren) {
20159                            freezer.close();
20160                        }
20161                    }
20162                }
20163            }
20164        }
20165    }
20166
20167    /**
20168     * Verify that given package is currently frozen.
20169     */
20170    private void checkPackageFrozen(String packageName) {
20171        synchronized (mPackages) {
20172            if (!mFrozenPackages.contains(packageName)) {
20173                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20174            }
20175        }
20176    }
20177
20178    @Override
20179    public int movePackage(final String packageName, final String volumeUuid) {
20180        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20181
20182        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20183        final int moveId = mNextMoveId.getAndIncrement();
20184        mHandler.post(new Runnable() {
20185            @Override
20186            public void run() {
20187                try {
20188                    movePackageInternal(packageName, volumeUuid, moveId, user);
20189                } catch (PackageManagerException e) {
20190                    Slog.w(TAG, "Failed to move " + packageName, e);
20191                    mMoveCallbacks.notifyStatusChanged(moveId,
20192                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20193                }
20194            }
20195        });
20196        return moveId;
20197    }
20198
20199    private void movePackageInternal(final String packageName, final String volumeUuid,
20200            final int moveId, UserHandle user) throws PackageManagerException {
20201        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20202        final PackageManager pm = mContext.getPackageManager();
20203
20204        final boolean currentAsec;
20205        final String currentVolumeUuid;
20206        final File codeFile;
20207        final String installerPackageName;
20208        final String packageAbiOverride;
20209        final int appId;
20210        final String seinfo;
20211        final String label;
20212        final int targetSdkVersion;
20213        final PackageFreezer freezer;
20214        final int[] installedUserIds;
20215
20216        // reader
20217        synchronized (mPackages) {
20218            final PackageParser.Package pkg = mPackages.get(packageName);
20219            final PackageSetting ps = mSettings.mPackages.get(packageName);
20220            if (pkg == null || ps == null) {
20221                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20222            }
20223
20224            if (pkg.applicationInfo.isSystemApp()) {
20225                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20226                        "Cannot move system application");
20227            }
20228
20229            if (pkg.applicationInfo.isExternalAsec()) {
20230                currentAsec = true;
20231                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20232            } else if (pkg.applicationInfo.isForwardLocked()) {
20233                currentAsec = true;
20234                currentVolumeUuid = "forward_locked";
20235            } else {
20236                currentAsec = false;
20237                currentVolumeUuid = ps.volumeUuid;
20238
20239                final File probe = new File(pkg.codePath);
20240                final File probeOat = new File(probe, "oat");
20241                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20242                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20243                            "Move only supported for modern cluster style installs");
20244                }
20245            }
20246
20247            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20248                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20249                        "Package already moved to " + volumeUuid);
20250            }
20251            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20252                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20253                        "Device admin cannot be moved");
20254            }
20255
20256            if (mFrozenPackages.contains(packageName)) {
20257                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20258                        "Failed to move already frozen package");
20259            }
20260
20261            codeFile = new File(pkg.codePath);
20262            installerPackageName = ps.installerPackageName;
20263            packageAbiOverride = ps.cpuAbiOverrideString;
20264            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20265            seinfo = pkg.applicationInfo.seinfo;
20266            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20267            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20268            freezer = freezePackage(packageName, "movePackageInternal");
20269            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20270        }
20271
20272        final Bundle extras = new Bundle();
20273        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20274        extras.putString(Intent.EXTRA_TITLE, label);
20275        mMoveCallbacks.notifyCreated(moveId, extras);
20276
20277        int installFlags;
20278        final boolean moveCompleteApp;
20279        final File measurePath;
20280
20281        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20282            installFlags = INSTALL_INTERNAL;
20283            moveCompleteApp = !currentAsec;
20284            measurePath = Environment.getDataAppDirectory(volumeUuid);
20285        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20286            installFlags = INSTALL_EXTERNAL;
20287            moveCompleteApp = false;
20288            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20289        } else {
20290            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20291            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20292                    || !volume.isMountedWritable()) {
20293                freezer.close();
20294                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20295                        "Move location not mounted private volume");
20296            }
20297
20298            Preconditions.checkState(!currentAsec);
20299
20300            installFlags = INSTALL_INTERNAL;
20301            moveCompleteApp = true;
20302            measurePath = Environment.getDataAppDirectory(volumeUuid);
20303        }
20304
20305        final PackageStats stats = new PackageStats(null, -1);
20306        synchronized (mInstaller) {
20307            for (int userId : installedUserIds) {
20308                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20309                    freezer.close();
20310                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20311                            "Failed to measure package size");
20312                }
20313            }
20314        }
20315
20316        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20317                + stats.dataSize);
20318
20319        final long startFreeBytes = measurePath.getFreeSpace();
20320        final long sizeBytes;
20321        if (moveCompleteApp) {
20322            sizeBytes = stats.codeSize + stats.dataSize;
20323        } else {
20324            sizeBytes = stats.codeSize;
20325        }
20326
20327        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20328            freezer.close();
20329            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20330                    "Not enough free space to move");
20331        }
20332
20333        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20334
20335        final CountDownLatch installedLatch = new CountDownLatch(1);
20336        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20337            @Override
20338            public void onUserActionRequired(Intent intent) throws RemoteException {
20339                throw new IllegalStateException();
20340            }
20341
20342            @Override
20343            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20344                    Bundle extras) throws RemoteException {
20345                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20346                        + PackageManager.installStatusToString(returnCode, msg));
20347
20348                installedLatch.countDown();
20349                freezer.close();
20350
20351                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20352                switch (status) {
20353                    case PackageInstaller.STATUS_SUCCESS:
20354                        mMoveCallbacks.notifyStatusChanged(moveId,
20355                                PackageManager.MOVE_SUCCEEDED);
20356                        break;
20357                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20358                        mMoveCallbacks.notifyStatusChanged(moveId,
20359                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20360                        break;
20361                    default:
20362                        mMoveCallbacks.notifyStatusChanged(moveId,
20363                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20364                        break;
20365                }
20366            }
20367        };
20368
20369        final MoveInfo move;
20370        if (moveCompleteApp) {
20371            // Kick off a thread to report progress estimates
20372            new Thread() {
20373                @Override
20374                public void run() {
20375                    while (true) {
20376                        try {
20377                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20378                                break;
20379                            }
20380                        } catch (InterruptedException ignored) {
20381                        }
20382
20383                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20384                        final int progress = 10 + (int) MathUtils.constrain(
20385                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20386                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20387                    }
20388                }
20389            }.start();
20390
20391            final String dataAppName = codeFile.getName();
20392            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20393                    dataAppName, appId, seinfo, targetSdkVersion);
20394        } else {
20395            move = null;
20396        }
20397
20398        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20399
20400        final Message msg = mHandler.obtainMessage(INIT_COPY);
20401        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20402        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20403                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20404                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20405        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20406        msg.obj = params;
20407
20408        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20409                System.identityHashCode(msg.obj));
20410        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20411                System.identityHashCode(msg.obj));
20412
20413        mHandler.sendMessage(msg);
20414    }
20415
20416    @Override
20417    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20418        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20419
20420        final int realMoveId = mNextMoveId.getAndIncrement();
20421        final Bundle extras = new Bundle();
20422        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20423        mMoveCallbacks.notifyCreated(realMoveId, extras);
20424
20425        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20426            @Override
20427            public void onCreated(int moveId, Bundle extras) {
20428                // Ignored
20429            }
20430
20431            @Override
20432            public void onStatusChanged(int moveId, int status, long estMillis) {
20433                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20434            }
20435        };
20436
20437        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20438        storage.setPrimaryStorageUuid(volumeUuid, callback);
20439        return realMoveId;
20440    }
20441
20442    @Override
20443    public int getMoveStatus(int moveId) {
20444        mContext.enforceCallingOrSelfPermission(
20445                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20446        return mMoveCallbacks.mLastStatus.get(moveId);
20447    }
20448
20449    @Override
20450    public void registerMoveCallback(IPackageMoveObserver callback) {
20451        mContext.enforceCallingOrSelfPermission(
20452                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20453        mMoveCallbacks.register(callback);
20454    }
20455
20456    @Override
20457    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20458        mContext.enforceCallingOrSelfPermission(
20459                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20460        mMoveCallbacks.unregister(callback);
20461    }
20462
20463    @Override
20464    public boolean setInstallLocation(int loc) {
20465        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20466                null);
20467        if (getInstallLocation() == loc) {
20468            return true;
20469        }
20470        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20471                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20472            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20473                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20474            return true;
20475        }
20476        return false;
20477   }
20478
20479    @Override
20480    public int getInstallLocation() {
20481        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20482                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20483                PackageHelper.APP_INSTALL_AUTO);
20484    }
20485
20486    /** Called by UserManagerService */
20487    void cleanUpUser(UserManagerService userManager, int userHandle) {
20488        synchronized (mPackages) {
20489            mDirtyUsers.remove(userHandle);
20490            mUserNeedsBadging.delete(userHandle);
20491            mSettings.removeUserLPw(userHandle);
20492            mPendingBroadcasts.remove(userHandle);
20493            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20494            removeUnusedPackagesLPw(userManager, userHandle);
20495        }
20496    }
20497
20498    /**
20499     * We're removing userHandle and would like to remove any downloaded packages
20500     * that are no longer in use by any other user.
20501     * @param userHandle the user being removed
20502     */
20503    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20504        final boolean DEBUG_CLEAN_APKS = false;
20505        int [] users = userManager.getUserIds();
20506        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20507        while (psit.hasNext()) {
20508            PackageSetting ps = psit.next();
20509            if (ps.pkg == null) {
20510                continue;
20511            }
20512            final String packageName = ps.pkg.packageName;
20513            // Skip over if system app
20514            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20515                continue;
20516            }
20517            if (DEBUG_CLEAN_APKS) {
20518                Slog.i(TAG, "Checking package " + packageName);
20519            }
20520            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20521            if (keep) {
20522                if (DEBUG_CLEAN_APKS) {
20523                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20524                }
20525            } else {
20526                for (int i = 0; i < users.length; i++) {
20527                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20528                        keep = true;
20529                        if (DEBUG_CLEAN_APKS) {
20530                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20531                                    + users[i]);
20532                        }
20533                        break;
20534                    }
20535                }
20536            }
20537            if (!keep) {
20538                if (DEBUG_CLEAN_APKS) {
20539                    Slog.i(TAG, "  Removing package " + packageName);
20540                }
20541                mHandler.post(new Runnable() {
20542                    public void run() {
20543                        deletePackageX(packageName, userHandle, 0);
20544                    } //end run
20545                });
20546            }
20547        }
20548    }
20549
20550    /** Called by UserManagerService */
20551    void createNewUser(int userId) {
20552        synchronized (mInstallLock) {
20553            mSettings.createNewUserLI(this, mInstaller, userId);
20554        }
20555        synchronized (mPackages) {
20556            scheduleWritePackageRestrictionsLocked(userId);
20557            scheduleWritePackageListLocked(userId);
20558            applyFactoryDefaultBrowserLPw(userId);
20559            primeDomainVerificationsLPw(userId);
20560        }
20561    }
20562
20563    void onNewUserCreated(final int userId) {
20564        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20565        // If permission review for legacy apps is required, we represent
20566        // dagerous permissions for such apps as always granted runtime
20567        // permissions to keep per user flag state whether review is needed.
20568        // Hence, if a new user is added we have to propagate dangerous
20569        // permission grants for these legacy apps.
20570        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20571            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20572                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20573        }
20574    }
20575
20576    @Override
20577    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20578        mContext.enforceCallingOrSelfPermission(
20579                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20580                "Only package verification agents can read the verifier device identity");
20581
20582        synchronized (mPackages) {
20583            return mSettings.getVerifierDeviceIdentityLPw();
20584        }
20585    }
20586
20587    @Override
20588    public void setPermissionEnforced(String permission, boolean enforced) {
20589        // TODO: Now that we no longer change GID for storage, this should to away.
20590        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20591                "setPermissionEnforced");
20592        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20593            synchronized (mPackages) {
20594                if (mSettings.mReadExternalStorageEnforced == null
20595                        || mSettings.mReadExternalStorageEnforced != enforced) {
20596                    mSettings.mReadExternalStorageEnforced = enforced;
20597                    mSettings.writeLPr();
20598                }
20599            }
20600            // kill any non-foreground processes so we restart them and
20601            // grant/revoke the GID.
20602            final IActivityManager am = ActivityManagerNative.getDefault();
20603            if (am != null) {
20604                final long token = Binder.clearCallingIdentity();
20605                try {
20606                    am.killProcessesBelowForeground("setPermissionEnforcement");
20607                } catch (RemoteException e) {
20608                } finally {
20609                    Binder.restoreCallingIdentity(token);
20610                }
20611            }
20612        } else {
20613            throw new IllegalArgumentException("No selective enforcement for " + permission);
20614        }
20615    }
20616
20617    @Override
20618    @Deprecated
20619    public boolean isPermissionEnforced(String permission) {
20620        return true;
20621    }
20622
20623    @Override
20624    public boolean isStorageLow() {
20625        final long token = Binder.clearCallingIdentity();
20626        try {
20627            final DeviceStorageMonitorInternal
20628                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20629            if (dsm != null) {
20630                return dsm.isMemoryLow();
20631            } else {
20632                return false;
20633            }
20634        } finally {
20635            Binder.restoreCallingIdentity(token);
20636        }
20637    }
20638
20639    @Override
20640    public IPackageInstaller getPackageInstaller() {
20641        return mInstallerService;
20642    }
20643
20644    private boolean userNeedsBadging(int userId) {
20645        int index = mUserNeedsBadging.indexOfKey(userId);
20646        if (index < 0) {
20647            final UserInfo userInfo;
20648            final long token = Binder.clearCallingIdentity();
20649            try {
20650                userInfo = sUserManager.getUserInfo(userId);
20651            } finally {
20652                Binder.restoreCallingIdentity(token);
20653            }
20654            final boolean b;
20655            if (userInfo != null && userInfo.isManagedProfile()) {
20656                b = true;
20657            } else {
20658                b = false;
20659            }
20660            mUserNeedsBadging.put(userId, b);
20661            return b;
20662        }
20663        return mUserNeedsBadging.valueAt(index);
20664    }
20665
20666    @Override
20667    public KeySet getKeySetByAlias(String packageName, String alias) {
20668        if (packageName == null || alias == null) {
20669            return null;
20670        }
20671        synchronized(mPackages) {
20672            final PackageParser.Package pkg = mPackages.get(packageName);
20673            if (pkg == null) {
20674                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20675                throw new IllegalArgumentException("Unknown package: " + packageName);
20676            }
20677            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20678            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20679        }
20680    }
20681
20682    @Override
20683    public KeySet getSigningKeySet(String packageName) {
20684        if (packageName == null) {
20685            return null;
20686        }
20687        synchronized(mPackages) {
20688            final PackageParser.Package pkg = mPackages.get(packageName);
20689            if (pkg == null) {
20690                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20691                throw new IllegalArgumentException("Unknown package: " + packageName);
20692            }
20693            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20694                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20695                throw new SecurityException("May not access signing KeySet of other apps.");
20696            }
20697            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20698            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20699        }
20700    }
20701
20702    @Override
20703    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20704        if (packageName == null || ks == null) {
20705            return false;
20706        }
20707        synchronized(mPackages) {
20708            final PackageParser.Package pkg = mPackages.get(packageName);
20709            if (pkg == null) {
20710                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20711                throw new IllegalArgumentException("Unknown package: " + packageName);
20712            }
20713            IBinder ksh = ks.getToken();
20714            if (ksh instanceof KeySetHandle) {
20715                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20716                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20717            }
20718            return false;
20719        }
20720    }
20721
20722    @Override
20723    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20724        if (packageName == null || ks == null) {
20725            return false;
20726        }
20727        synchronized(mPackages) {
20728            final PackageParser.Package pkg = mPackages.get(packageName);
20729            if (pkg == null) {
20730                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20731                throw new IllegalArgumentException("Unknown package: " + packageName);
20732            }
20733            IBinder ksh = ks.getToken();
20734            if (ksh instanceof KeySetHandle) {
20735                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20736                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20737            }
20738            return false;
20739        }
20740    }
20741
20742    private void deletePackageIfUnusedLPr(final String packageName) {
20743        PackageSetting ps = mSettings.mPackages.get(packageName);
20744        if (ps == null) {
20745            return;
20746        }
20747        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20748            // TODO Implement atomic delete if package is unused
20749            // It is currently possible that the package will be deleted even if it is installed
20750            // after this method returns.
20751            mHandler.post(new Runnable() {
20752                public void run() {
20753                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20754                }
20755            });
20756        }
20757    }
20758
20759    /**
20760     * Check and throw if the given before/after packages would be considered a
20761     * downgrade.
20762     */
20763    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20764            throws PackageManagerException {
20765        if (after.versionCode < before.mVersionCode) {
20766            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20767                    "Update version code " + after.versionCode + " is older than current "
20768                    + before.mVersionCode);
20769        } else if (after.versionCode == before.mVersionCode) {
20770            if (after.baseRevisionCode < before.baseRevisionCode) {
20771                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20772                        "Update base revision code " + after.baseRevisionCode
20773                        + " is older than current " + before.baseRevisionCode);
20774            }
20775
20776            if (!ArrayUtils.isEmpty(after.splitNames)) {
20777                for (int i = 0; i < after.splitNames.length; i++) {
20778                    final String splitName = after.splitNames[i];
20779                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20780                    if (j != -1) {
20781                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20782                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20783                                    "Update split " + splitName + " revision code "
20784                                    + after.splitRevisionCodes[i] + " is older than current "
20785                                    + before.splitRevisionCodes[j]);
20786                        }
20787                    }
20788                }
20789            }
20790        }
20791    }
20792
20793    private static class MoveCallbacks extends Handler {
20794        private static final int MSG_CREATED = 1;
20795        private static final int MSG_STATUS_CHANGED = 2;
20796
20797        private final RemoteCallbackList<IPackageMoveObserver>
20798                mCallbacks = new RemoteCallbackList<>();
20799
20800        private final SparseIntArray mLastStatus = new SparseIntArray();
20801
20802        public MoveCallbacks(Looper looper) {
20803            super(looper);
20804        }
20805
20806        public void register(IPackageMoveObserver callback) {
20807            mCallbacks.register(callback);
20808        }
20809
20810        public void unregister(IPackageMoveObserver callback) {
20811            mCallbacks.unregister(callback);
20812        }
20813
20814        @Override
20815        public void handleMessage(Message msg) {
20816            final SomeArgs args = (SomeArgs) msg.obj;
20817            final int n = mCallbacks.beginBroadcast();
20818            for (int i = 0; i < n; i++) {
20819                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20820                try {
20821                    invokeCallback(callback, msg.what, args);
20822                } catch (RemoteException ignored) {
20823                }
20824            }
20825            mCallbacks.finishBroadcast();
20826            args.recycle();
20827        }
20828
20829        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20830                throws RemoteException {
20831            switch (what) {
20832                case MSG_CREATED: {
20833                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20834                    break;
20835                }
20836                case MSG_STATUS_CHANGED: {
20837                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20838                    break;
20839                }
20840            }
20841        }
20842
20843        private void notifyCreated(int moveId, Bundle extras) {
20844            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20845
20846            final SomeArgs args = SomeArgs.obtain();
20847            args.argi1 = moveId;
20848            args.arg2 = extras;
20849            obtainMessage(MSG_CREATED, args).sendToTarget();
20850        }
20851
20852        private void notifyStatusChanged(int moveId, int status) {
20853            notifyStatusChanged(moveId, status, -1);
20854        }
20855
20856        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20857            Slog.v(TAG, "Move " + moveId + " status " + status);
20858
20859            final SomeArgs args = SomeArgs.obtain();
20860            args.argi1 = moveId;
20861            args.argi2 = status;
20862            args.arg3 = estMillis;
20863            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20864
20865            synchronized (mLastStatus) {
20866                mLastStatus.put(moveId, status);
20867            }
20868        }
20869    }
20870
20871    private final static class OnPermissionChangeListeners extends Handler {
20872        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20873
20874        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20875                new RemoteCallbackList<>();
20876
20877        public OnPermissionChangeListeners(Looper looper) {
20878            super(looper);
20879        }
20880
20881        @Override
20882        public void handleMessage(Message msg) {
20883            switch (msg.what) {
20884                case MSG_ON_PERMISSIONS_CHANGED: {
20885                    final int uid = msg.arg1;
20886                    handleOnPermissionsChanged(uid);
20887                } break;
20888            }
20889        }
20890
20891        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20892            mPermissionListeners.register(listener);
20893
20894        }
20895
20896        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20897            mPermissionListeners.unregister(listener);
20898        }
20899
20900        public void onPermissionsChanged(int uid) {
20901            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20902                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20903            }
20904        }
20905
20906        private void handleOnPermissionsChanged(int uid) {
20907            final int count = mPermissionListeners.beginBroadcast();
20908            try {
20909                for (int i = 0; i < count; i++) {
20910                    IOnPermissionsChangeListener callback = mPermissionListeners
20911                            .getBroadcastItem(i);
20912                    try {
20913                        callback.onPermissionsChanged(uid);
20914                    } catch (RemoteException e) {
20915                        Log.e(TAG, "Permission listener is dead", e);
20916                    }
20917                }
20918            } finally {
20919                mPermissionListeners.finishBroadcast();
20920            }
20921        }
20922    }
20923
20924    private class PackageManagerInternalImpl extends PackageManagerInternal {
20925        @Override
20926        public void setLocationPackagesProvider(PackagesProvider provider) {
20927            synchronized (mPackages) {
20928                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20929            }
20930        }
20931
20932        @Override
20933        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20934            synchronized (mPackages) {
20935                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20936            }
20937        }
20938
20939        @Override
20940        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20941            synchronized (mPackages) {
20942                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20943            }
20944        }
20945
20946        @Override
20947        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20948            synchronized (mPackages) {
20949                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20950            }
20951        }
20952
20953        @Override
20954        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20955            synchronized (mPackages) {
20956                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20957            }
20958        }
20959
20960        @Override
20961        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20962            synchronized (mPackages) {
20963                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20964            }
20965        }
20966
20967        @Override
20968        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20969            synchronized (mPackages) {
20970                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20971                        packageName, userId);
20972            }
20973        }
20974
20975        @Override
20976        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20977            synchronized (mPackages) {
20978                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20979                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20980                        packageName, userId);
20981            }
20982        }
20983
20984        @Override
20985        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20986            synchronized (mPackages) {
20987                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20988                        packageName, userId);
20989            }
20990        }
20991
20992        @Override
20993        public void setKeepUninstalledPackages(final List<String> packageList) {
20994            Preconditions.checkNotNull(packageList);
20995            List<String> removedFromList = null;
20996            synchronized (mPackages) {
20997                if (mKeepUninstalledPackages != null) {
20998                    final int packagesCount = mKeepUninstalledPackages.size();
20999                    for (int i = 0; i < packagesCount; i++) {
21000                        String oldPackage = mKeepUninstalledPackages.get(i);
21001                        if (packageList != null && packageList.contains(oldPackage)) {
21002                            continue;
21003                        }
21004                        if (removedFromList == null) {
21005                            removedFromList = new ArrayList<>();
21006                        }
21007                        removedFromList.add(oldPackage);
21008                    }
21009                }
21010                mKeepUninstalledPackages = new ArrayList<>(packageList);
21011                if (removedFromList != null) {
21012                    final int removedCount = removedFromList.size();
21013                    for (int i = 0; i < removedCount; i++) {
21014                        deletePackageIfUnusedLPr(removedFromList.get(i));
21015                    }
21016                }
21017            }
21018        }
21019
21020        @Override
21021        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21022            synchronized (mPackages) {
21023                // If we do not support permission review, done.
21024                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
21025                    return false;
21026                }
21027
21028                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21029                if (packageSetting == null) {
21030                    return false;
21031                }
21032
21033                // Permission review applies only to apps not supporting the new permission model.
21034                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21035                    return false;
21036                }
21037
21038                // Legacy apps have the permission and get user consent on launch.
21039                PermissionsState permissionsState = packageSetting.getPermissionsState();
21040                return permissionsState.isPermissionReviewRequired(userId);
21041            }
21042        }
21043
21044        @Override
21045        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21046            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21047        }
21048
21049        @Override
21050        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21051                int userId) {
21052            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21053        }
21054
21055        @Override
21056        public void setDeviceAndProfileOwnerPackages(
21057                int deviceOwnerUserId, String deviceOwnerPackage,
21058                SparseArray<String> profileOwnerPackages) {
21059            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21060                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21061        }
21062
21063        @Override
21064        public boolean isPackageDataProtected(int userId, String packageName) {
21065            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21066        }
21067    }
21068
21069    @Override
21070    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21071        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21072        synchronized (mPackages) {
21073            final long identity = Binder.clearCallingIdentity();
21074            try {
21075                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21076                        packageNames, userId);
21077            } finally {
21078                Binder.restoreCallingIdentity(identity);
21079            }
21080        }
21081    }
21082
21083    private static void enforceSystemOrPhoneCaller(String tag) {
21084        int callingUid = Binder.getCallingUid();
21085        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21086            throw new SecurityException(
21087                    "Cannot call " + tag + " from UID " + callingUid);
21088        }
21089    }
21090
21091    boolean isHistoricalPackageUsageAvailable() {
21092        return mPackageUsage.isHistoricalPackageUsageAvailable();
21093    }
21094
21095    /**
21096     * Return a <b>copy</b> of the collection of packages known to the package manager.
21097     * @return A copy of the values of mPackages.
21098     */
21099    Collection<PackageParser.Package> getPackages() {
21100        synchronized (mPackages) {
21101            return new ArrayList<>(mPackages.values());
21102        }
21103    }
21104
21105    /**
21106     * Logs process start information (including base APK hash) to the security log.
21107     * @hide
21108     */
21109    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21110            String apkFile, int pid) {
21111        if (!SecurityLog.isLoggingEnabled()) {
21112            return;
21113        }
21114        Bundle data = new Bundle();
21115        data.putLong("startTimestamp", System.currentTimeMillis());
21116        data.putString("processName", processName);
21117        data.putInt("uid", uid);
21118        data.putString("seinfo", seinfo);
21119        data.putString("apkFile", apkFile);
21120        data.putInt("pid", pid);
21121        Message msg = mProcessLoggingHandler.obtainMessage(
21122                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21123        msg.setData(data);
21124        mProcessLoggingHandler.sendMessage(msg);
21125    }
21126
21127    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21128        return mCompilerStats.getPackageStats(pkgName);
21129    }
21130
21131    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21132        return getOrCreateCompilerPackageStats(pkg.packageName);
21133    }
21134
21135    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21136        return mCompilerStats.getOrCreatePackageStats(pkgName);
21137    }
21138
21139    public void deleteCompilerPackageStats(String pkgName) {
21140        mCompilerStats.deletePackageStats(pkgName);
21141    }
21142}
21143