PackageManagerService.java revision c200bb7be484c116c0f8ae177a8ff6d41095ff34
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.ResourcesManager;
107import android.app.admin.IDevicePolicyManager;
108import android.app.admin.SecurityLog;
109import android.app.backup.IBackupManager;
110import android.content.BroadcastReceiver;
111import android.content.ComponentName;
112import android.content.ContentResolver;
113import android.content.Context;
114import android.content.IIntentReceiver;
115import android.content.Intent;
116import android.content.IntentFilter;
117import android.content.IntentSender;
118import android.content.IntentSender.SendIntentException;
119import android.content.ServiceConnection;
120import android.content.pm.ActivityInfo;
121import android.content.pm.ApplicationInfo;
122import android.content.pm.AppsQueryHelper;
123import android.content.pm.ComponentInfo;
124import android.content.pm.EphemeralApplicationInfo;
125import android.content.pm.EphemeralResolveInfo;
126import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.Uri;
168import android.os.Binder;
169import android.os.Build;
170import android.os.Bundle;
171import android.os.Debug;
172import android.os.Environment;
173import android.os.Environment.UserEnvironment;
174import android.os.FileUtils;
175import android.os.Handler;
176import android.os.IBinder;
177import android.os.Looper;
178import android.os.Message;
179import android.os.Parcel;
180import android.os.ParcelFileDescriptor;
181import android.os.PatternMatcher;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.ShellCallback;
189import android.os.SystemClock;
190import android.os.SystemProperties;
191import android.os.Trace;
192import android.os.UserHandle;
193import android.os.UserManager;
194import android.os.UserManagerInternal;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.provider.Settings.Global;
202import android.provider.Settings.Secure;
203import android.security.KeyStore;
204import android.security.SystemKeyStore;
205import android.system.ErrnoException;
206import android.system.Os;
207import android.text.TextUtils;
208import android.text.format.DateUtils;
209import android.util.ArrayMap;
210import android.util.ArraySet;
211import android.util.DisplayMetrics;
212import android.util.EventLog;
213import android.util.ExceptionUtils;
214import android.util.Log;
215import android.util.LogPrinter;
216import android.util.MathUtils;
217import android.util.Pair;
218import android.util.PrintStreamPrinter;
219import android.util.Slog;
220import android.util.SparseArray;
221import android.util.SparseBooleanArray;
222import android.util.SparseIntArray;
223import android.util.Xml;
224import android.util.jar.StrictJarFile;
225import android.view.Display;
226
227import com.android.internal.R;
228import com.android.internal.annotations.GuardedBy;
229import com.android.internal.app.IMediaContainerService;
230import com.android.internal.app.ResolverActivity;
231import com.android.internal.content.NativeLibraryHelper;
232import com.android.internal.content.PackageHelper;
233import com.android.internal.logging.MetricsLogger;
234import com.android.internal.os.IParcelFileDescriptorFactory;
235import com.android.internal.os.InstallerConnection.InstallerException;
236import com.android.internal.os.SomeArgs;
237import com.android.internal.os.Zygote;
238import com.android.internal.telephony.CarrierAppUtils;
239import com.android.internal.util.ArrayUtils;
240import com.android.internal.util.FastPrintWriter;
241import com.android.internal.util.FastXmlSerializer;
242import com.android.internal.util.IndentingPrintWriter;
243import com.android.internal.util.Preconditions;
244import com.android.internal.util.XmlUtils;
245import com.android.server.AttributeCache;
246import com.android.server.EventLogTags;
247import com.android.server.FgThread;
248import com.android.server.IntentResolver;
249import com.android.server.LocalServices;
250import com.android.server.ServiceThread;
251import com.android.server.SystemConfig;
252import com.android.server.Watchdog;
253import com.android.server.net.NetworkPolicyManagerInternal;
254import com.android.server.pm.PermissionsState.PermissionState;
255import com.android.server.pm.Settings.DatabaseVersion;
256import com.android.server.pm.Settings.VersionInfo;
257import com.android.server.storage.DeviceStorageMonitorInternal;
258
259import dalvik.system.CloseGuard;
260import dalvik.system.DexFile;
261import dalvik.system.VMRuntime;
262
263import libcore.io.IoUtils;
264import libcore.util.EmptyArray;
265
266import org.xmlpull.v1.XmlPullParser;
267import org.xmlpull.v1.XmlPullParserException;
268import org.xmlpull.v1.XmlSerializer;
269
270import java.io.BufferedOutputStream;
271import java.io.BufferedReader;
272import java.io.ByteArrayInputStream;
273import java.io.ByteArrayOutputStream;
274import java.io.File;
275import java.io.FileDescriptor;
276import java.io.FileInputStream;
277import java.io.FileNotFoundException;
278import java.io.FileOutputStream;
279import java.io.FileReader;
280import java.io.FilenameFilter;
281import java.io.IOException;
282import java.io.PrintWriter;
283import java.nio.charset.StandardCharsets;
284import java.security.DigestInputStream;
285import java.security.MessageDigest;
286import java.security.NoSuchAlgorithmException;
287import java.security.PublicKey;
288import java.security.cert.Certificate;
289import java.security.cert.CertificateEncodingException;
290import java.security.cert.CertificateException;
291import java.text.SimpleDateFormat;
292import java.util.ArrayList;
293import java.util.Arrays;
294import java.util.Collection;
295import java.util.Collections;
296import java.util.Comparator;
297import java.util.Date;
298import java.util.HashSet;
299import java.util.Iterator;
300import java.util.List;
301import java.util.Map;
302import java.util.Objects;
303import java.util.Set;
304import java.util.concurrent.CountDownLatch;
305import java.util.concurrent.TimeUnit;
306import java.util.concurrent.atomic.AtomicBoolean;
307import java.util.concurrent.atomic.AtomicInteger;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
370    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
371
372    private static final boolean DISABLE_EPHEMERAL_APPS = false;
373    private static final boolean HIDE_EPHEMERAL_APIS = true;
374
375    private static final int RADIO_UID = Process.PHONE_UID;
376    private static final int LOG_UID = Process.LOG_UID;
377    private static final int NFC_UID = Process.NFC_UID;
378    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
379    private static final int SHELL_UID = Process.SHELL_UID;
380
381    // Cap the size of permission trees that 3rd party apps can define
382    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
383
384    // Suffix used during package installation when copying/moving
385    // package apks to install directory.
386    private static final String INSTALL_PACKAGE_SUFFIX = "-";
387
388    static final int SCAN_NO_DEX = 1<<1;
389    static final int SCAN_FORCE_DEX = 1<<2;
390    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
391    static final int SCAN_NEW_INSTALL = 1<<4;
392    static final int SCAN_NO_PATHS = 1<<5;
393    static final int SCAN_UPDATE_TIME = 1<<6;
394    static final int SCAN_DEFER_DEX = 1<<7;
395    static final int SCAN_BOOTING = 1<<8;
396    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
397    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
398    static final int SCAN_REPLACING = 1<<11;
399    static final int SCAN_REQUIRE_KNOWN = 1<<12;
400    static final int SCAN_MOVE = 1<<13;
401    static final int SCAN_INITIAL = 1<<14;
402    static final int SCAN_CHECK_ONLY = 1<<15;
403    static final int SCAN_DONT_KILL_APP = 1<<17;
404    static final int SCAN_IGNORE_FROZEN = 1<<18;
405
406    static final int REMOVE_CHATTY = 1<<16;
407
408    private static final int[] EMPTY_INT_ARRAY = new int[0];
409
410    /**
411     * Timeout (in milliseconds) after which the watchdog should declare that
412     * our handler thread is wedged.  The usual default for such things is one
413     * minute but we sometimes do very lengthy I/O operations on this thread,
414     * such as installing multi-gigabyte applications, so ours needs to be longer.
415     */
416    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
417
418    /**
419     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
420     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
421     * settings entry if available, otherwise we use the hardcoded default.  If it's been
422     * more than this long since the last fstrim, we force one during the boot sequence.
423     *
424     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
425     * one gets run at the next available charging+idle time.  This final mandatory
426     * no-fstrim check kicks in only of the other scheduling criteria is never met.
427     */
428    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
429
430    /**
431     * Whether verification is enabled by default.
432     */
433    private static final boolean DEFAULT_VERIFY_ENABLE = true;
434
435    /**
436     * The default maximum time to wait for the verification agent to return in
437     * milliseconds.
438     */
439    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
440
441    /**
442     * The default response for package verification timeout.
443     *
444     * This can be either PackageManager.VERIFICATION_ALLOW or
445     * PackageManager.VERIFICATION_REJECT.
446     */
447    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
448
449    static final String PLATFORM_PACKAGE_NAME = "android";
450
451    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
452
453    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
454            DEFAULT_CONTAINER_PACKAGE,
455            "com.android.defcontainer.DefaultContainerService");
456
457    private static final String KILL_APP_REASON_GIDS_CHANGED =
458            "permission grant or revoke changed gids";
459
460    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
461            "permissions revoked";
462
463    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
464
465    private static final String PACKAGE_SCHEME = "package";
466
467    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
468    /**
469     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
474
475    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
476    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
477
478    /** Permission grant: not grant the permission. */
479    private static final int GRANT_DENIED = 1;
480
481    /** Permission grant: grant the permission as an install permission. */
482    private static final int GRANT_INSTALL = 2;
483
484    /** Permission grant: grant the permission as a runtime one. */
485    private static final int GRANT_RUNTIME = 3;
486
487    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
488    private static final int GRANT_UPGRADE = 4;
489
490    /** Canonical intent used to identify what counts as a "web browser" app */
491    private static final Intent sBrowserIntent;
492    static {
493        sBrowserIntent = new Intent();
494        sBrowserIntent.setAction(Intent.ACTION_VIEW);
495        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
496        sBrowserIntent.setData(Uri.parse("http:"));
497    }
498
499    /**
500     * The set of all protected actions [i.e. those actions for which a high priority
501     * intent filter is disallowed].
502     */
503    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
504    static {
505        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
506        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
507        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
508        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
509    }
510
511    // Compilation reasons.
512    public static final int REASON_FIRST_BOOT = 0;
513    public static final int REASON_BOOT = 1;
514    public static final int REASON_INSTALL = 2;
515    public static final int REASON_BACKGROUND_DEXOPT = 3;
516    public static final int REASON_AB_OTA = 4;
517    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
518    public static final int REASON_SHARED_APK = 6;
519    public static final int REASON_FORCED_DEXOPT = 7;
520    public static final int REASON_CORE_APP = 8;
521
522    public static final int REASON_LAST = REASON_CORE_APP;
523
524    /** Special library name that skips shared libraries check during compilation. */
525    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
526
527    final ServiceThread mHandlerThread;
528
529    final PackageHandler mHandler;
530
531    private final ProcessLoggingHandler mProcessLoggingHandler;
532
533    /**
534     * Messages for {@link #mHandler} that need to wait for system ready before
535     * being dispatched.
536     */
537    private ArrayList<Message> mPostSystemReadyMessages;
538
539    final int mSdkVersion = Build.VERSION.SDK_INT;
540
541    final Context mContext;
542    final boolean mFactoryTest;
543    final boolean mOnlyCore;
544    final DisplayMetrics mMetrics;
545    final int mDefParseFlags;
546    final String[] mSeparateProcesses;
547    final boolean mIsUpgrade;
548    final boolean mIsPreNUpgrade;
549    final boolean mIsPreNMR1Upgrade;
550
551    @GuardedBy("mPackages")
552    private boolean mDexOptDialogShown;
553
554    /** The location for ASEC container files on internal storage. */
555    final String mAsecInternalPath;
556
557    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
558    // LOCK HELD.  Can be called with mInstallLock held.
559    @GuardedBy("mInstallLock")
560    final Installer mInstaller;
561
562    /** Directory where installed third-party apps stored */
563    final File mAppInstallDir;
564    final File mEphemeralInstallDir;
565
566    /**
567     * Directory to which applications installed internally have their
568     * 32 bit native libraries copied.
569     */
570    private File mAppLib32InstallDir;
571
572    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
573    // apps.
574    final File mDrmAppPrivateInstallDir;
575
576    // ----------------------------------------------------------------
577
578    // Lock for state used when installing and doing other long running
579    // operations.  Methods that must be called with this lock held have
580    // the suffix "LI".
581    final Object mInstallLock = new Object();
582
583    // ----------------------------------------------------------------
584
585    // Keys are String (package name), values are Package.  This also serves
586    // as the lock for the global state.  Methods that must be called with
587    // this lock held have the prefix "LP".
588    @GuardedBy("mPackages")
589    final ArrayMap<String, PackageParser.Package> mPackages =
590            new ArrayMap<String, PackageParser.Package>();
591
592    final ArrayMap<String, Set<String>> mKnownCodebase =
593            new ArrayMap<String, Set<String>>();
594
595    // Tracks available target package names -> overlay package paths.
596    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
597        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
598
599    /**
600     * Tracks new system packages [received in an OTA] that we expect to
601     * find updated user-installed versions. Keys are package name, values
602     * are package location.
603     */
604    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
605    /**
606     * Tracks high priority intent filters for protected actions. During boot, certain
607     * filter actions are protected and should never be allowed to have a high priority
608     * intent filter for them. However, there is one, and only one exception -- the
609     * setup wizard. It must be able to define a high priority intent filter for these
610     * actions to ensure there are no escapes from the wizard. We need to delay processing
611     * of these during boot as we need to look at all of the system packages in order
612     * to know which component is the setup wizard.
613     */
614    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
615    /**
616     * Whether or not processing protected filters should be deferred.
617     */
618    private boolean mDeferProtectedFilters = true;
619
620    /**
621     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
622     */
623    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
624    /**
625     * Whether or not system app permissions should be promoted from install to runtime.
626     */
627    boolean mPromoteSystemApps;
628
629    @GuardedBy("mPackages")
630    final Settings mSettings;
631
632    /**
633     * Set of package names that are currently "frozen", which means active
634     * surgery is being done on the code/data for that package. The platform
635     * will refuse to launch frozen packages to avoid race conditions.
636     *
637     * @see PackageFreezer
638     */
639    @GuardedBy("mPackages")
640    final ArraySet<String> mFrozenPackages = new ArraySet<>();
641
642    final ProtectedPackages mProtectedPackages;
643
644    boolean mFirstBoot;
645
646    // System configuration read by SystemConfig.
647    final int[] mGlobalGids;
648    final SparseArray<ArraySet<String>> mSystemPermissions;
649    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
650
651    // If mac_permissions.xml was found for seinfo labeling.
652    boolean mFoundPolicyFile;
653
654    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
655
656    public static final class SharedLibraryEntry {
657        public final String path;
658        public final String apk;
659
660        SharedLibraryEntry(String _path, String _apk) {
661            path = _path;
662            apk = _apk;
663        }
664    }
665
666    // Currently known shared libraries.
667    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
668            new ArrayMap<String, SharedLibraryEntry>();
669
670    // All available activities, for your resolving pleasure.
671    final ActivityIntentResolver mActivities =
672            new ActivityIntentResolver();
673
674    // All available receivers, for your resolving pleasure.
675    final ActivityIntentResolver mReceivers =
676            new ActivityIntentResolver();
677
678    // All available services, for your resolving pleasure.
679    final ServiceIntentResolver mServices = new ServiceIntentResolver();
680
681    // All available providers, for your resolving pleasure.
682    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
683
684    // Mapping from provider base names (first directory in content URI codePath)
685    // to the provider information.
686    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
687            new ArrayMap<String, PackageParser.Provider>();
688
689    // Mapping from instrumentation class names to info about them.
690    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
691            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
692
693    // Mapping from permission names to info about them.
694    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
695            new ArrayMap<String, PackageParser.PermissionGroup>();
696
697    // Packages whose data we have transfered into another package, thus
698    // should no longer exist.
699    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
700
701    // Broadcast actions that are only available to the system.
702    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
703
704    /** List of packages waiting for verification. */
705    final SparseArray<PackageVerificationState> mPendingVerification
706            = new SparseArray<PackageVerificationState>();
707
708    /** Set of packages associated with each app op permission. */
709    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
710
711    final PackageInstallerService mInstallerService;
712
713    private final PackageDexOptimizer mPackageDexOptimizer;
714
715    private AtomicInteger mNextMoveId = new AtomicInteger();
716    private final MoveCallbacks mMoveCallbacks;
717
718    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
719
720    // Cache of users who need badging.
721    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
722
723    /** Token for keys in mPendingVerification. */
724    private int mPendingVerificationToken = 0;
725
726    volatile boolean mSystemReady;
727    volatile boolean mSafeMode;
728    volatile boolean mHasSystemUidErrors;
729
730    ApplicationInfo mAndroidApplication;
731    final ActivityInfo mResolveActivity = new ActivityInfo();
732    final ResolveInfo mResolveInfo = new ResolveInfo();
733    ComponentName mResolveComponentName;
734    PackageParser.Package mPlatformPackage;
735    ComponentName mCustomResolverComponentName;
736
737    boolean mResolverReplaced = false;
738
739    private final @Nullable ComponentName mIntentFilterVerifierComponent;
740    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
741
742    private int mIntentFilterVerificationToken = 0;
743
744    /** Component that knows whether or not an ephemeral application exists */
745    final ComponentName mEphemeralResolverComponent;
746    /** The service connection to the ephemeral resolver */
747    final EphemeralResolverConnection mEphemeralResolverConnection;
748
749    /** Component used to install ephemeral applications */
750    final ComponentName mEphemeralInstallerComponent;
751    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
752    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
753
754    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
755            = new SparseArray<IntentFilterVerificationState>();
756
757    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
758
759    // List of packages names to keep cached, even if they are uninstalled for all users
760    private List<String> mKeepUninstalledPackages;
761
762    private UserManagerInternal mUserManagerInternal;
763
764    private static class IFVerificationParams {
765        PackageParser.Package pkg;
766        boolean replacing;
767        int userId;
768        int verifierUid;
769
770        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
771                int _userId, int _verifierUid) {
772            pkg = _pkg;
773            replacing = _replacing;
774            userId = _userId;
775            replacing = _replacing;
776            verifierUid = _verifierUid;
777        }
778    }
779
780    private interface IntentFilterVerifier<T extends IntentFilter> {
781        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
782                                               T filter, String packageName);
783        void startVerifications(int userId);
784        void receiveVerificationResponse(int verificationId);
785    }
786
787    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
788        private Context mContext;
789        private ComponentName mIntentFilterVerifierComponent;
790        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
791
792        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
793            mContext = context;
794            mIntentFilterVerifierComponent = verifierComponent;
795        }
796
797        private String getDefaultScheme() {
798            return IntentFilter.SCHEME_HTTPS;
799        }
800
801        @Override
802        public void startVerifications(int userId) {
803            // Launch verifications requests
804            int count = mCurrentIntentFilterVerifications.size();
805            for (int n=0; n<count; n++) {
806                int verificationId = mCurrentIntentFilterVerifications.get(n);
807                final IntentFilterVerificationState ivs =
808                        mIntentFilterVerificationStates.get(verificationId);
809
810                String packageName = ivs.getPackageName();
811
812                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
813                final int filterCount = filters.size();
814                ArraySet<String> domainsSet = new ArraySet<>();
815                for (int m=0; m<filterCount; m++) {
816                    PackageParser.ActivityIntentInfo filter = filters.get(m);
817                    domainsSet.addAll(filter.getHostsList());
818                }
819                synchronized (mPackages) {
820                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
821                            packageName, domainsSet) != null) {
822                        scheduleWriteSettingsLocked();
823                    }
824                }
825                sendVerificationRequest(userId, verificationId, ivs);
826            }
827            mCurrentIntentFilterVerifications.clear();
828        }
829
830        private void sendVerificationRequest(int userId, int verificationId,
831                IntentFilterVerificationState ivs) {
832
833            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
836                    verificationId);
837            verificationIntent.putExtra(
838                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
839                    getDefaultScheme());
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
842                    ivs.getHostsString());
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
845                    ivs.getPackageName());
846            verificationIntent.setComponent(mIntentFilterVerifierComponent);
847            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
848
849            UserHandle user = new UserHandle(userId);
850            mContext.sendBroadcastAsUser(verificationIntent, user);
851            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
852                    "Sending IntentFilter verification broadcast");
853        }
854
855        public void receiveVerificationResponse(int verificationId) {
856            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
857
858            final boolean verified = ivs.isVerified();
859
860            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
861            final int count = filters.size();
862            if (DEBUG_DOMAIN_VERIFICATION) {
863                Slog.i(TAG, "Received verification response " + verificationId
864                        + " for " + count + " filters, verified=" + verified);
865            }
866            for (int n=0; n<count; n++) {
867                PackageParser.ActivityIntentInfo filter = filters.get(n);
868                filter.setVerified(verified);
869
870                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
871                        + " verified with result:" + verified + " and hosts:"
872                        + ivs.getHostsString());
873            }
874
875            mIntentFilterVerificationStates.remove(verificationId);
876
877            final String packageName = ivs.getPackageName();
878            IntentFilterVerificationInfo ivi = null;
879
880            synchronized (mPackages) {
881                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
882            }
883            if (ivi == null) {
884                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
885                        + verificationId + " packageName:" + packageName);
886                return;
887            }
888            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
889                    "Updating IntentFilterVerificationInfo for package " + packageName
890                            +" verificationId:" + verificationId);
891
892            synchronized (mPackages) {
893                if (verified) {
894                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
895                } else {
896                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
897                }
898                scheduleWriteSettingsLocked();
899
900                final int userId = ivs.getUserId();
901                if (userId != UserHandle.USER_ALL) {
902                    final int userStatus =
903                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
904
905                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
906                    boolean needUpdate = false;
907
908                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
909                    // already been set by the User thru the Disambiguation dialog
910                    switch (userStatus) {
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                            } else {
915                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
916                            }
917                            needUpdate = true;
918                            break;
919
920                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
921                            if (verified) {
922                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
923                                needUpdate = true;
924                            }
925                            break;
926
927                        default:
928                            // Nothing to do
929                    }
930
931                    if (needUpdate) {
932                        mSettings.updateIntentFilterVerificationStatusLPw(
933                                packageName, updatedStatus, userId);
934                        scheduleWritePackageRestrictionsLocked(userId);
935                    }
936                }
937            }
938        }
939
940        @Override
941        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
942                    ActivityIntentInfo filter, String packageName) {
943            if (!hasValidDomains(filter)) {
944                return false;
945            }
946            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
947            if (ivs == null) {
948                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
949                        packageName);
950            }
951            if (DEBUG_DOMAIN_VERIFICATION) {
952                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
953            }
954            ivs.addFilter(filter);
955            return true;
956        }
957
958        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
959                int userId, int verificationId, String packageName) {
960            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
961                    verifierUid, userId, packageName);
962            ivs.setPendingState();
963            synchronized (mPackages) {
964                mIntentFilterVerificationStates.append(verificationId, ivs);
965                mCurrentIntentFilterVerifications.add(verificationId);
966            }
967            return ivs;
968        }
969    }
970
971    private static boolean hasValidDomains(ActivityIntentInfo filter) {
972        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
973                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
974                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
975    }
976
977    // Set of pending broadcasts for aggregating enable/disable of components.
978    static class PendingPackageBroadcasts {
979        // for each user id, a map of <package name -> components within that package>
980        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
981
982        public PendingPackageBroadcasts() {
983            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
984        }
985
986        public ArrayList<String> get(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
988            return packages.get(packageName);
989        }
990
991        public void put(int userId, String packageName, ArrayList<String> components) {
992            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
993            packages.put(packageName, components);
994        }
995
996        public void remove(int userId, String packageName) {
997            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
998            if (packages != null) {
999                packages.remove(packageName);
1000            }
1001        }
1002
1003        public void remove(int userId) {
1004            mUidMap.remove(userId);
1005        }
1006
1007        public int userIdCount() {
1008            return mUidMap.size();
1009        }
1010
1011        public int userIdAt(int n) {
1012            return mUidMap.keyAt(n);
1013        }
1014
1015        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1016            return mUidMap.get(userId);
1017        }
1018
1019        public int size() {
1020            // total number of pending broadcast entries across all userIds
1021            int num = 0;
1022            for (int i = 0; i< mUidMap.size(); i++) {
1023                num += mUidMap.valueAt(i).size();
1024            }
1025            return num;
1026        }
1027
1028        public void clear() {
1029            mUidMap.clear();
1030        }
1031
1032        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1033            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1034            if (map == null) {
1035                map = new ArrayMap<String, ArrayList<String>>();
1036                mUidMap.put(userId, map);
1037            }
1038            return map;
1039        }
1040    }
1041    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1042
1043    // Service Connection to remote media container service to copy
1044    // package uri's from external media onto secure containers
1045    // or internal storage.
1046    private IMediaContainerService mContainerService = null;
1047
1048    static final int SEND_PENDING_BROADCAST = 1;
1049    static final int MCS_BOUND = 3;
1050    static final int END_COPY = 4;
1051    static final int INIT_COPY = 5;
1052    static final int MCS_UNBIND = 6;
1053    static final int START_CLEANING_PACKAGE = 7;
1054    static final int FIND_INSTALL_LOC = 8;
1055    static final int POST_INSTALL = 9;
1056    static final int MCS_RECONNECT = 10;
1057    static final int MCS_GIVE_UP = 11;
1058    static final int UPDATED_MEDIA_STATUS = 12;
1059    static final int WRITE_SETTINGS = 13;
1060    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1061    static final int PACKAGE_VERIFIED = 15;
1062    static final int CHECK_PENDING_VERIFICATION = 16;
1063    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1064    static final int INTENT_FILTER_VERIFIED = 18;
1065    static final int WRITE_PACKAGE_LIST = 19;
1066
1067    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1068
1069    // Delay time in millisecs
1070    static final int BROADCAST_DELAY = 10 * 1000;
1071
1072    static UserManagerService sUserManager;
1073
1074    // Stores a list of users whose package restrictions file needs to be updated
1075    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1076
1077    final private DefaultContainerConnection mDefContainerConn =
1078            new DefaultContainerConnection();
1079    class DefaultContainerConnection implements ServiceConnection {
1080        public void onServiceConnected(ComponentName name, IBinder service) {
1081            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1082            IMediaContainerService imcs =
1083                IMediaContainerService.Stub.asInterface(service);
1084            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1085        }
1086
1087        public void onServiceDisconnected(ComponentName name) {
1088            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1089        }
1090    }
1091
1092    // Recordkeeping of restore-after-install operations that are currently in flight
1093    // between the Package Manager and the Backup Manager
1094    static class PostInstallData {
1095        public InstallArgs args;
1096        public PackageInstalledInfo res;
1097
1098        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1099            args = _a;
1100            res = _r;
1101        }
1102    }
1103
1104    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1105    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1106
1107    // XML tags for backup/restore of various bits of state
1108    private static final String TAG_PREFERRED_BACKUP = "pa";
1109    private static final String TAG_DEFAULT_APPS = "da";
1110    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1111
1112    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1113    private static final String TAG_ALL_GRANTS = "rt-grants";
1114    private static final String TAG_GRANT = "grant";
1115    private static final String ATTR_PACKAGE_NAME = "pkg";
1116
1117    private static final String TAG_PERMISSION = "perm";
1118    private static final String ATTR_PERMISSION_NAME = "name";
1119    private static final String ATTR_IS_GRANTED = "g";
1120    private static final String ATTR_USER_SET = "set";
1121    private static final String ATTR_USER_FIXED = "fixed";
1122    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1123
1124    // System/policy permission grants are not backed up
1125    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1126            FLAG_PERMISSION_POLICY_FIXED
1127            | FLAG_PERMISSION_SYSTEM_FIXED
1128            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1129
1130    // And we back up these user-adjusted states
1131    private static final int USER_RUNTIME_GRANT_MASK =
1132            FLAG_PERMISSION_USER_SET
1133            | FLAG_PERMISSION_USER_FIXED
1134            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1135
1136    final @Nullable String mRequiredVerifierPackage;
1137    final @NonNull String mRequiredInstallerPackage;
1138    final @NonNull String mRequiredUninstallerPackage;
1139    final @Nullable String mSetupWizardPackage;
1140    final @Nullable String mStorageManagerPackage;
1141    final @NonNull String mServicesSystemSharedLibraryPackageName;
1142    final @NonNull String mSharedSystemSharedLibraryPackageName;
1143
1144    final boolean mPermissionReviewRequired;
1145
1146    private final PackageUsage mPackageUsage = new PackageUsage();
1147    private final CompilerStats mCompilerStats = new CompilerStats();
1148
1149    class PackageHandler extends Handler {
1150        private boolean mBound = false;
1151        final ArrayList<HandlerParams> mPendingInstalls =
1152            new ArrayList<HandlerParams>();
1153
1154        private boolean connectToService() {
1155            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1156                    " DefaultContainerService");
1157            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1158            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1159            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1160                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1161                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162                mBound = true;
1163                return true;
1164            }
1165            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166            return false;
1167        }
1168
1169        private void disconnectService() {
1170            mContainerService = null;
1171            mBound = false;
1172            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1173            mContext.unbindService(mDefContainerConn);
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175        }
1176
1177        PackageHandler(Looper looper) {
1178            super(looper);
1179        }
1180
1181        public void handleMessage(Message msg) {
1182            try {
1183                doHandleMessage(msg);
1184            } finally {
1185                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186            }
1187        }
1188
1189        void doHandleMessage(Message msg) {
1190            switch (msg.what) {
1191                case INIT_COPY: {
1192                    HandlerParams params = (HandlerParams) msg.obj;
1193                    int idx = mPendingInstalls.size();
1194                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1195                    // If a bind was already initiated we dont really
1196                    // need to do anything. The pending install
1197                    // will be processed later on.
1198                    if (!mBound) {
1199                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                System.identityHashCode(mHandler));
1201                        // If this is the only one pending we might
1202                        // have to bind to the service again.
1203                        if (!connectToService()) {
1204                            Slog.e(TAG, "Failed to bind to media container service");
1205                            params.serviceError();
1206                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                    System.identityHashCode(mHandler));
1208                            if (params.traceMethod != null) {
1209                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1210                                        params.traceCookie);
1211                            }
1212                            return;
1213                        } else {
1214                            // Once we bind to the service, the first
1215                            // pending request will be processed.
1216                            mPendingInstalls.add(idx, params);
1217                        }
1218                    } else {
1219                        mPendingInstalls.add(idx, params);
1220                        // Already bound to the service. Just make
1221                        // sure we trigger off processing the first request.
1222                        if (idx == 0) {
1223                            mHandler.sendEmptyMessage(MCS_BOUND);
1224                        }
1225                    }
1226                    break;
1227                }
1228                case MCS_BOUND: {
1229                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1230                    if (msg.obj != null) {
1231                        mContainerService = (IMediaContainerService) msg.obj;
1232                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233                                System.identityHashCode(mHandler));
1234                    }
1235                    if (mContainerService == null) {
1236                        if (!mBound) {
1237                            // Something seriously wrong since we are not bound and we are not
1238                            // waiting for connection. Bail out.
1239                            Slog.e(TAG, "Cannot bind to media container service");
1240                            for (HandlerParams params : mPendingInstalls) {
1241                                // Indicate service bind error
1242                                params.serviceError();
1243                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244                                        System.identityHashCode(params));
1245                                if (params.traceMethod != null) {
1246                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1247                                            params.traceMethod, params.traceCookie);
1248                                }
1249                                return;
1250                            }
1251                            mPendingInstalls.clear();
1252                        } else {
1253                            Slog.w(TAG, "Waiting to connect to media container service");
1254                        }
1255                    } else if (mPendingInstalls.size() > 0) {
1256                        HandlerParams params = mPendingInstalls.get(0);
1257                        if (params != null) {
1258                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                    System.identityHashCode(params));
1260                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1261                            if (params.startCopy()) {
1262                                // We are done...  look for more work or to
1263                                // go idle.
1264                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1265                                        "Checking for more work or unbind...");
1266                                // Delete pending install
1267                                if (mPendingInstalls.size() > 0) {
1268                                    mPendingInstalls.remove(0);
1269                                }
1270                                if (mPendingInstalls.size() == 0) {
1271                                    if (mBound) {
1272                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                                "Posting delayed MCS_UNBIND");
1274                                        removeMessages(MCS_UNBIND);
1275                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1276                                        // Unbind after a little delay, to avoid
1277                                        // continual thrashing.
1278                                        sendMessageDelayed(ubmsg, 10000);
1279                                    }
1280                                } else {
1281                                    // There are more pending requests in queue.
1282                                    // Just post MCS_BOUND message to trigger processing
1283                                    // of next pending install.
1284                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                            "Posting MCS_BOUND for next work");
1286                                    mHandler.sendEmptyMessage(MCS_BOUND);
1287                                }
1288                            }
1289                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1290                        }
1291                    } else {
1292                        // Should never happen ideally.
1293                        Slog.w(TAG, "Empty queue");
1294                    }
1295                    break;
1296                }
1297                case MCS_RECONNECT: {
1298                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1299                    if (mPendingInstalls.size() > 0) {
1300                        if (mBound) {
1301                            disconnectService();
1302                        }
1303                        if (!connectToService()) {
1304                            Slog.e(TAG, "Failed to bind to media container service");
1305                            for (HandlerParams params : mPendingInstalls) {
1306                                // Indicate service bind error
1307                                params.serviceError();
1308                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1309                                        System.identityHashCode(params));
1310                            }
1311                            mPendingInstalls.clear();
1312                        }
1313                    }
1314                    break;
1315                }
1316                case MCS_UNBIND: {
1317                    // If there is no actual work left, then time to unbind.
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1319
1320                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1321                        if (mBound) {
1322                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1323
1324                            disconnectService();
1325                        }
1326                    } else if (mPendingInstalls.size() > 0) {
1327                        // There are more pending requests in queue.
1328                        // Just post MCS_BOUND message to trigger processing
1329                        // of next pending install.
1330                        mHandler.sendEmptyMessage(MCS_BOUND);
1331                    }
1332
1333                    break;
1334                }
1335                case MCS_GIVE_UP: {
1336                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1337                    HandlerParams params = mPendingInstalls.remove(0);
1338                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                            System.identityHashCode(params));
1340                    break;
1341                }
1342                case SEND_PENDING_BROADCAST: {
1343                    String packages[];
1344                    ArrayList<String> components[];
1345                    int size = 0;
1346                    int uids[];
1347                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1348                    synchronized (mPackages) {
1349                        if (mPendingBroadcasts == null) {
1350                            return;
1351                        }
1352                        size = mPendingBroadcasts.size();
1353                        if (size <= 0) {
1354                            // Nothing to be done. Just return
1355                            return;
1356                        }
1357                        packages = new String[size];
1358                        components = new ArrayList[size];
1359                        uids = new int[size];
1360                        int i = 0;  // filling out the above arrays
1361
1362                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1363                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1364                            Iterator<Map.Entry<String, ArrayList<String>>> it
1365                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1366                                            .entrySet().iterator();
1367                            while (it.hasNext() && i < size) {
1368                                Map.Entry<String, ArrayList<String>> ent = it.next();
1369                                packages[i] = ent.getKey();
1370                                components[i] = ent.getValue();
1371                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1372                                uids[i] = (ps != null)
1373                                        ? UserHandle.getUid(packageUserId, ps.appId)
1374                                        : -1;
1375                                i++;
1376                            }
1377                        }
1378                        size = i;
1379                        mPendingBroadcasts.clear();
1380                    }
1381                    // Send broadcasts
1382                    for (int i = 0; i < size; i++) {
1383                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1384                    }
1385                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1386                    break;
1387                }
1388                case START_CLEANING_PACKAGE: {
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1390                    final String packageName = (String)msg.obj;
1391                    final int userId = msg.arg1;
1392                    final boolean andCode = msg.arg2 != 0;
1393                    synchronized (mPackages) {
1394                        if (userId == UserHandle.USER_ALL) {
1395                            int[] users = sUserManager.getUserIds();
1396                            for (int user : users) {
1397                                mSettings.addPackageToCleanLPw(
1398                                        new PackageCleanItem(user, packageName, andCode));
1399                            }
1400                        } else {
1401                            mSettings.addPackageToCleanLPw(
1402                                    new PackageCleanItem(userId, packageName, andCode));
1403                        }
1404                    }
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406                    startCleaningPackages();
1407                } break;
1408                case POST_INSTALL: {
1409                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1410
1411                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1412                    final boolean didRestore = (msg.arg2 != 0);
1413                    mRunningInstalls.delete(msg.arg1);
1414
1415                    if (data != null) {
1416                        InstallArgs args = data.args;
1417                        PackageInstalledInfo parentRes = data.res;
1418
1419                        final boolean grantPermissions = (args.installFlags
1420                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1421                        final boolean killApp = (args.installFlags
1422                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1423                        final String[] grantedPermissions = args.installGrantPermissions;
1424
1425                        // Handle the parent package
1426                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1427                                grantedPermissions, didRestore, args.installerPackageName,
1428                                args.observer);
1429
1430                        // Handle the child packages
1431                        final int childCount = (parentRes.addedChildPackages != null)
1432                                ? parentRes.addedChildPackages.size() : 0;
1433                        for (int i = 0; i < childCount; i++) {
1434                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1435                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1436                                    grantedPermissions, false, args.installerPackageName,
1437                                    args.observer);
1438                        }
1439
1440                        // Log tracing if needed
1441                        if (args.traceMethod != null) {
1442                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1443                                    args.traceCookie);
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448
1449                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1450                } break;
1451                case UPDATED_MEDIA_STATUS: {
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453                    boolean reportStatus = msg.arg1 == 1;
1454                    boolean doGc = msg.arg2 == 1;
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456                    if (doGc) {
1457                        // Force a gc to clear up stale containers.
1458                        Runtime.getRuntime().gc();
1459                    }
1460                    if (msg.obj != null) {
1461                        @SuppressWarnings("unchecked")
1462                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464                        // Unload containers
1465                        unloadAllContainers(args);
1466                    }
1467                    if (reportStatus) {
1468                        try {
1469                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470                            PackageHelper.getMountService().finishMediaUpdate();
1471                        } catch (RemoteException e) {
1472                            Log.e(TAG, "MountService not running?");
1473                        }
1474                    }
1475                } break;
1476                case WRITE_SETTINGS: {
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                    synchronized (mPackages) {
1479                        removeMessages(WRITE_SETTINGS);
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        mSettings.writeLPr();
1482                        mDirtyUsers.clear();
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case WRITE_PACKAGE_RESTRICTIONS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        for (int userId : mDirtyUsers) {
1491                            mSettings.writePackageRestrictionsLPr(userId);
1492                        }
1493                        mDirtyUsers.clear();
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                } break;
1497                case WRITE_PACKAGE_LIST: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    synchronized (mPackages) {
1500                        removeMessages(WRITE_PACKAGE_LIST);
1501                        mSettings.writePackageListLPr(msg.arg1);
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                } break;
1505                case CHECK_PENDING_VERIFICATION: {
1506                    final int verificationId = msg.arg1;
1507                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                    if ((state != null) && !state.timeoutExtended()) {
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        Slog.i(TAG, "Verification timed out for " + originUri);
1514                        mPendingVerification.remove(verificationId);
1515
1516                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                            Slog.i(TAG, "Continuing with installation of " + originUri);
1520                            state.setVerifierResponse(Binder.getCallingUid(),
1521                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_ALLOW,
1524                                    state.getInstallArgs().getUser());
1525                            try {
1526                                ret = args.copyApk(mContainerService, true);
1527                            } catch (RemoteException e) {
1528                                Slog.e(TAG, "Could not contact the ContainerService");
1529                            }
1530                        } else {
1531                            broadcastPackageVerified(verificationId, originUri,
1532                                    PackageManager.VERIFICATION_REJECT,
1533                                    state.getInstallArgs().getUser());
1534                        }
1535
1536                        Trace.asyncTraceEnd(
1537                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538
1539                        processPendingInstall(args, ret);
1540                        mHandler.sendEmptyMessage(MCS_UNBIND);
1541                    }
1542                    break;
1543                }
1544                case PACKAGE_VERIFIED: {
1545                    final int verificationId = msg.arg1;
1546
1547                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1548                    if (state == null) {
1549                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1550                        break;
1551                    }
1552
1553                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (state.isVerificationComplete()) {
1558                        mPendingVerification.remove(verificationId);
1559
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        int ret;
1564                        if (state.isInstallAllowed()) {
1565                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    response.code, state.getInstallArgs().getUser());
1568                            try {
1569                                ret = args.copyApk(mContainerService, true);
1570                            } catch (RemoteException e) {
1571                                Slog.e(TAG, "Could not contact the ContainerService");
1572                            }
1573                        } else {
1574                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575                        }
1576
1577                        Trace.asyncTraceEnd(
1578                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579
1580                        processPendingInstall(args, ret);
1581                        mHandler.sendEmptyMessage(MCS_UNBIND);
1582                    }
1583
1584                    break;
1585                }
1586                case START_INTENT_FILTER_VERIFICATIONS: {
1587                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1588                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589                            params.replacing, params.pkg);
1590                    break;
1591                }
1592                case INTENT_FILTER_VERIFIED: {
1593                    final int verificationId = msg.arg1;
1594
1595                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596                            verificationId);
1597                    if (state == null) {
1598                        Slog.w(TAG, "Invalid IntentFilter verification token "
1599                                + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final int userId = state.getUserId();
1604
1605                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                            "Processing IntentFilter verification with token:"
1607                            + verificationId + " and userId:" + userId);
1608
1609                    final IntentFilterVerificationResponse response =
1610                            (IntentFilterVerificationResponse) msg.obj;
1611
1612                    state.setVerifierResponse(response.callerUid, response.code);
1613
1614                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                            "IntentFilter verification with token:" + verificationId
1616                            + " and userId:" + userId
1617                            + " is settings verifier response with response code:"
1618                            + response.code);
1619
1620                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622                                + response.getFailedDomainsString());
1623                    }
1624
1625                    if (state.isVerificationComplete()) {
1626                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627                    } else {
1628                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629                                "IntentFilter verification with token:" + verificationId
1630                                + " was not said to be complete");
1631                    }
1632
1633                    break;
1634                }
1635            }
1636        }
1637    }
1638
1639    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640            boolean killApp, String[] grantedPermissions,
1641            boolean launchedForRestore, String installerPackage,
1642            IPackageInstallObserver2 installObserver) {
1643        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644            // Send the removed broadcasts
1645            if (res.removedInfo != null) {
1646                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1647            }
1648
1649            // Now that we successfully installed the package, grant runtime
1650            // permissions if requested before broadcasting the install.
1651            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652                    >= Build.VERSION_CODES.M) {
1653                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1654            }
1655
1656            final boolean update = res.removedInfo != null
1657                    && res.removedInfo.removedPackage != null;
1658
1659            // If this is the first time we have child packages for a disabled privileged
1660            // app that had no children, we grant requested runtime permissions to the new
1661            // children if the parent on the system image had them already granted.
1662            if (res.pkg.parentPackage != null) {
1663                synchronized (mPackages) {
1664                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1665                }
1666            }
1667
1668            synchronized (mPackages) {
1669                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1670            }
1671
1672            final String packageName = res.pkg.applicationInfo.packageName;
1673
1674            // Determine the set of users who are adding this package for
1675            // the first time vs. those who are seeing an update.
1676            int[] firstUsers = EMPTY_INT_ARRAY;
1677            int[] updateUsers = EMPTY_INT_ARRAY;
1678            if (res.origUsers == null || res.origUsers.length == 0) {
1679                firstUsers = res.newUsers;
1680            } else {
1681                for (int newUser : res.newUsers) {
1682                    boolean isNew = true;
1683                    for (int origUser : res.origUsers) {
1684                        if (origUser == newUser) {
1685                            isNew = false;
1686                            break;
1687                        }
1688                    }
1689                    if (isNew) {
1690                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1691                    } else {
1692                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1693                    }
1694                }
1695            }
1696
1697            // Send installed broadcasts if the install/update is not ephemeral
1698            if (!isEphemeral(res.pkg)) {
1699                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1700
1701                // Send added for users that see the package for the first time
1702                // sendPackageAddedForNewUsers also deals with system apps
1703                int appId = UserHandle.getAppId(res.uid);
1704                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1705                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1706
1707                // Send added for users that don't see the package for the first time
1708                Bundle extras = new Bundle(1);
1709                extras.putInt(Intent.EXTRA_UID, res.uid);
1710                if (update) {
1711                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1712                }
1713                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1714                        extras, 0 /*flags*/, null /*targetPackage*/,
1715                        null /*finishedReceiver*/, updateUsers);
1716
1717                // Send replaced for users that don't see the package for the first time
1718                if (update) {
1719                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1720                            packageName, extras, 0 /*flags*/,
1721                            null /*targetPackage*/, null /*finishedReceiver*/,
1722                            updateUsers);
1723                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1724                            null /*package*/, null /*extras*/, 0 /*flags*/,
1725                            packageName /*targetPackage*/,
1726                            null /*finishedReceiver*/, updateUsers);
1727                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1728                    // First-install and we did a restore, so we're responsible for the
1729                    // first-launch broadcast.
1730                    if (DEBUG_BACKUP) {
1731                        Slog.i(TAG, "Post-restore of " + packageName
1732                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1733                    }
1734                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1735                }
1736
1737                // Send broadcast package appeared if forward locked/external for all users
1738                // treat asec-hosted packages like removable media on upgrade
1739                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1740                    if (DEBUG_INSTALL) {
1741                        Slog.i(TAG, "upgrading pkg " + res.pkg
1742                                + " is ASEC-hosted -> AVAILABLE");
1743                    }
1744                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1745                    ArrayList<String> pkgList = new ArrayList<>(1);
1746                    pkgList.add(packageName);
1747                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1748                }
1749            }
1750
1751            // Work that needs to happen on first install within each user
1752            if (firstUsers != null && firstUsers.length > 0) {
1753                synchronized (mPackages) {
1754                    for (int userId : firstUsers) {
1755                        // If this app is a browser and it's newly-installed for some
1756                        // users, clear any default-browser state in those users. The
1757                        // app's nature doesn't depend on the user, so we can just check
1758                        // its browser nature in any user and generalize.
1759                        if (packageIsBrowser(packageName, userId)) {
1760                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1761                        }
1762
1763                        // We may also need to apply pending (restored) runtime
1764                        // permission grants within these users.
1765                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1766                    }
1767                }
1768            }
1769
1770            // Log current value of "unknown sources" setting
1771            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1772                    getUnknownSourcesSettings());
1773
1774            // Force a gc to clear up things
1775            Runtime.getRuntime().gc();
1776
1777            // Remove the replaced package's older resources safely now
1778            // We delete after a gc for applications  on sdcard.
1779            if (res.removedInfo != null && res.removedInfo.args != null) {
1780                synchronized (mInstallLock) {
1781                    res.removedInfo.args.doPostDeleteLI(true);
1782                }
1783            }
1784        }
1785
1786        // If someone is watching installs - notify them
1787        if (installObserver != null) {
1788            try {
1789                Bundle extras = extrasForInstallResult(res);
1790                installObserver.onPackageInstalled(res.name, res.returnCode,
1791                        res.returnMsg, extras);
1792            } catch (RemoteException e) {
1793                Slog.i(TAG, "Observer no longer exists.");
1794            }
1795        }
1796    }
1797
1798    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1799            PackageParser.Package pkg) {
1800        if (pkg.parentPackage == null) {
1801            return;
1802        }
1803        if (pkg.requestedPermissions == null) {
1804            return;
1805        }
1806        final PackageSetting disabledSysParentPs = mSettings
1807                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1808        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1809                || !disabledSysParentPs.isPrivileged()
1810                || (disabledSysParentPs.childPackageNames != null
1811                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1812            return;
1813        }
1814        final int[] allUserIds = sUserManager.getUserIds();
1815        final int permCount = pkg.requestedPermissions.size();
1816        for (int i = 0; i < permCount; i++) {
1817            String permission = pkg.requestedPermissions.get(i);
1818            BasePermission bp = mSettings.mPermissions.get(permission);
1819            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1820                continue;
1821            }
1822            for (int userId : allUserIds) {
1823                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1824                        permission, userId)) {
1825                    grantRuntimePermission(pkg.packageName, permission, userId);
1826                }
1827            }
1828        }
1829    }
1830
1831    private StorageEventListener mStorageListener = new StorageEventListener() {
1832        @Override
1833        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1834            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1835                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836                    final String volumeUuid = vol.getFsUuid();
1837
1838                    // Clean up any users or apps that were removed or recreated
1839                    // while this volume was missing
1840                    reconcileUsers(volumeUuid);
1841                    reconcileApps(volumeUuid);
1842
1843                    // Clean up any install sessions that expired or were
1844                    // cancelled while this volume was missing
1845                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1846
1847                    loadPrivatePackages(vol);
1848
1849                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1850                    unloadPrivatePackages(vol);
1851                }
1852            }
1853
1854            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1855                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1856                    updateExternalMediaStatus(true, false);
1857                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1858                    updateExternalMediaStatus(false, false);
1859                }
1860            }
1861        }
1862
1863        @Override
1864        public void onVolumeForgotten(String fsUuid) {
1865            if (TextUtils.isEmpty(fsUuid)) {
1866                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1867                return;
1868            }
1869
1870            // Remove any apps installed on the forgotten volume
1871            synchronized (mPackages) {
1872                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1873                for (PackageSetting ps : packages) {
1874                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1875                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1876                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1877                }
1878
1879                mSettings.onVolumeForgotten(fsUuid);
1880                mSettings.writeLPr();
1881            }
1882        }
1883    };
1884
1885    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1886            String[] grantedPermissions) {
1887        for (int userId : userIds) {
1888            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1889        }
1890
1891        // We could have touched GID membership, so flush out packages.list
1892        synchronized (mPackages) {
1893            mSettings.writePackageListLPr();
1894        }
1895    }
1896
1897    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1898            String[] grantedPermissions) {
1899        SettingBase sb = (SettingBase) pkg.mExtras;
1900        if (sb == null) {
1901            return;
1902        }
1903
1904        PermissionsState permissionsState = sb.getPermissionsState();
1905
1906        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1907                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1908
1909        for (String permission : pkg.requestedPermissions) {
1910            final BasePermission bp;
1911            synchronized (mPackages) {
1912                bp = mSettings.mPermissions.get(permission);
1913            }
1914            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1915                    && (grantedPermissions == null
1916                           || ArrayUtils.contains(grantedPermissions, permission))) {
1917                final int flags = permissionsState.getPermissionFlags(permission, userId);
1918                // Installer cannot change immutable permissions.
1919                if ((flags & immutableFlags) == 0) {
1920                    grantRuntimePermission(pkg.packageName, permission, userId);
1921                }
1922            }
1923        }
1924    }
1925
1926    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1927        Bundle extras = null;
1928        switch (res.returnCode) {
1929            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1930                extras = new Bundle();
1931                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1932                        res.origPermission);
1933                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1934                        res.origPackage);
1935                break;
1936            }
1937            case PackageManager.INSTALL_SUCCEEDED: {
1938                extras = new Bundle();
1939                extras.putBoolean(Intent.EXTRA_REPLACING,
1940                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1941                break;
1942            }
1943        }
1944        return extras;
1945    }
1946
1947    void scheduleWriteSettingsLocked() {
1948        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1949            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1950        }
1951    }
1952
1953    void scheduleWritePackageListLocked(int userId) {
1954        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1955            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1956            msg.arg1 = userId;
1957            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1958        }
1959    }
1960
1961    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1962        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1963        scheduleWritePackageRestrictionsLocked(userId);
1964    }
1965
1966    void scheduleWritePackageRestrictionsLocked(int userId) {
1967        final int[] userIds = (userId == UserHandle.USER_ALL)
1968                ? sUserManager.getUserIds() : new int[]{userId};
1969        for (int nextUserId : userIds) {
1970            if (!sUserManager.exists(nextUserId)) return;
1971            mDirtyUsers.add(nextUserId);
1972            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1973                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1974            }
1975        }
1976    }
1977
1978    public static PackageManagerService main(Context context, Installer installer,
1979            boolean factoryTest, boolean onlyCore) {
1980        // Self-check for initial settings.
1981        PackageManagerServiceCompilerMapping.checkProperties();
1982
1983        PackageManagerService m = new PackageManagerService(context, installer,
1984                factoryTest, onlyCore);
1985        m.enableSystemUserPackages();
1986        ServiceManager.addService("package", m);
1987        return m;
1988    }
1989
1990    private void enableSystemUserPackages() {
1991        if (!UserManager.isSplitSystemUser()) {
1992            return;
1993        }
1994        // For system user, enable apps based on the following conditions:
1995        // - app is whitelisted or belong to one of these groups:
1996        //   -- system app which has no launcher icons
1997        //   -- system app which has INTERACT_ACROSS_USERS permission
1998        //   -- system IME app
1999        // - app is not in the blacklist
2000        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2001        Set<String> enableApps = new ArraySet<>();
2002        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2003                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2004                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2005        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2006        enableApps.addAll(wlApps);
2007        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2008                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2009        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2010        enableApps.removeAll(blApps);
2011        Log.i(TAG, "Applications installed for system user: " + enableApps);
2012        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2013                UserHandle.SYSTEM);
2014        final int allAppsSize = allAps.size();
2015        synchronized (mPackages) {
2016            for (int i = 0; i < allAppsSize; i++) {
2017                String pName = allAps.get(i);
2018                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2019                // Should not happen, but we shouldn't be failing if it does
2020                if (pkgSetting == null) {
2021                    continue;
2022                }
2023                boolean install = enableApps.contains(pName);
2024                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2025                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2026                            + " for system user");
2027                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2028                }
2029            }
2030        }
2031    }
2032
2033    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2034        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2035                Context.DISPLAY_SERVICE);
2036        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2037    }
2038
2039    /**
2040     * Requests that files preopted on a secondary system partition be copied to the data partition
2041     * if possible.  Note that the actual copying of the files is accomplished by init for security
2042     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2043     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2044     */
2045    private static void requestCopyPreoptedFiles() {
2046        final int WAIT_TIME_MS = 100;
2047        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2048        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2049            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2050            // We will wait for up to 100 seconds.
2051            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2052            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2053                try {
2054                    Thread.sleep(WAIT_TIME_MS);
2055                } catch (InterruptedException e) {
2056                    // Do nothing
2057                }
2058                if (SystemClock.uptimeMillis() > timeEnd) {
2059                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2060                    Slog.wtf(TAG, "cppreopt did not finish!");
2061                    break;
2062                }
2063            }
2064        }
2065    }
2066
2067    public PackageManagerService(Context context, Installer installer,
2068            boolean factoryTest, boolean onlyCore) {
2069        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2070        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2071                SystemClock.uptimeMillis());
2072
2073        if (mSdkVersion <= 0) {
2074            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2075        }
2076
2077        mContext = context;
2078
2079        mPermissionReviewRequired = context.getResources().getBoolean(
2080                R.bool.config_permissionReviewRequired);
2081
2082        mFactoryTest = factoryTest;
2083        mOnlyCore = onlyCore;
2084        mMetrics = new DisplayMetrics();
2085        mSettings = new Settings(mPackages);
2086        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2087                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2088        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2089                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2090        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2091                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2092        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2093                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2095                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2097                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098
2099        String separateProcesses = SystemProperties.get("debug.separate_processes");
2100        if (separateProcesses != null && separateProcesses.length() > 0) {
2101            if ("*".equals(separateProcesses)) {
2102                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2103                mSeparateProcesses = null;
2104                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2105            } else {
2106                mDefParseFlags = 0;
2107                mSeparateProcesses = separateProcesses.split(",");
2108                Slog.w(TAG, "Running with debug.separate_processes: "
2109                        + separateProcesses);
2110            }
2111        } else {
2112            mDefParseFlags = 0;
2113            mSeparateProcesses = null;
2114        }
2115
2116        mInstaller = installer;
2117        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2118                "*dexopt*");
2119        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2120
2121        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2122                FgThread.get().getLooper());
2123
2124        getDefaultDisplayMetrics(context, mMetrics);
2125
2126        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2127        SystemConfig systemConfig = SystemConfig.getInstance();
2128        mGlobalGids = systemConfig.getGlobalGids();
2129        mSystemPermissions = systemConfig.getSystemPermissions();
2130        mAvailableFeatures = systemConfig.getAvailableFeatures();
2131        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2132
2133        mProtectedPackages = new ProtectedPackages(mContext);
2134
2135        synchronized (mInstallLock) {
2136        // writer
2137        synchronized (mPackages) {
2138            mHandlerThread = new ServiceThread(TAG,
2139                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2140            mHandlerThread.start();
2141            mHandler = new PackageHandler(mHandlerThread.getLooper());
2142            mProcessLoggingHandler = new ProcessLoggingHandler();
2143            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2144
2145            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2146
2147            File dataDir = Environment.getDataDirectory();
2148            mAppInstallDir = new File(dataDir, "app");
2149            mAppLib32InstallDir = new File(dataDir, "app-lib");
2150            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2151            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2152            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2153
2154            sUserManager = new UserManagerService(context, this, mPackages);
2155
2156            // Propagate permission configuration in to package manager.
2157            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2158                    = systemConfig.getPermissions();
2159            for (int i=0; i<permConfig.size(); i++) {
2160                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2161                BasePermission bp = mSettings.mPermissions.get(perm.name);
2162                if (bp == null) {
2163                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2164                    mSettings.mPermissions.put(perm.name, bp);
2165                }
2166                if (perm.gids != null) {
2167                    bp.setGids(perm.gids, perm.perUser);
2168                }
2169            }
2170
2171            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2172            for (int i=0; i<libConfig.size(); i++) {
2173                mSharedLibraries.put(libConfig.keyAt(i),
2174                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2175            }
2176
2177            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2178
2179            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2180            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2181            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2182
2183            if (mFirstBoot) {
2184                requestCopyPreoptedFiles();
2185            }
2186
2187            String customResolverActivity = Resources.getSystem().getString(
2188                    R.string.config_customResolverActivity);
2189            if (TextUtils.isEmpty(customResolverActivity)) {
2190                customResolverActivity = null;
2191            } else {
2192                mCustomResolverComponentName = ComponentName.unflattenFromString(
2193                        customResolverActivity);
2194            }
2195
2196            long startTime = SystemClock.uptimeMillis();
2197
2198            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2199                    startTime);
2200
2201            // Set flag to monitor and not change apk file paths when
2202            // scanning install directories.
2203            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2204
2205            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2206            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2207
2208            if (bootClassPath == null) {
2209                Slog.w(TAG, "No BOOTCLASSPATH found!");
2210            }
2211
2212            if (systemServerClassPath == null) {
2213                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2214            }
2215
2216            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2217            final String[] dexCodeInstructionSets =
2218                    getDexCodeInstructionSets(
2219                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2220
2221            /**
2222             * Ensure all external libraries have had dexopt run on them.
2223             */
2224            if (mSharedLibraries.size() > 0) {
2225                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2226                // NOTE: For now, we're compiling these system "shared libraries"
2227                // (and framework jars) into all available architectures. It's possible
2228                // to compile them only when we come across an app that uses them (there's
2229                // already logic for that in scanPackageLI) but that adds some complexity.
2230                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2231                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2232                        final String lib = libEntry.path;
2233                        if (lib == null) {
2234                            continue;
2235                        }
2236
2237                        try {
2238                            // Shared libraries do not have profiles so we perform a full
2239                            // AOT compilation (if needed).
2240                            int dexoptNeeded = DexFile.getDexOptNeeded(
2241                                    lib, dexCodeInstructionSet,
2242                                    getCompilerFilterForReason(REASON_SHARED_APK),
2243                                    false /* newProfile */);
2244                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2245                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2246                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2247                                        getCompilerFilterForReason(REASON_SHARED_APK),
2248                                        StorageManager.UUID_PRIVATE_INTERNAL,
2249                                        SKIP_SHARED_LIBRARY_CHECK);
2250                            }
2251                        } catch (FileNotFoundException e) {
2252                            Slog.w(TAG, "Library not found: " + lib);
2253                        } catch (IOException | InstallerException e) {
2254                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2255                                    + e.getMessage());
2256                        }
2257                    }
2258                }
2259                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2260            }
2261
2262            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2263
2264            final VersionInfo ver = mSettings.getInternalVersion();
2265            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2266
2267            // when upgrading from pre-M, promote system app permissions from install to runtime
2268            mPromoteSystemApps =
2269                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2270
2271            // When upgrading from pre-N, we need to handle package extraction like first boot,
2272            // as there is no profiling data available.
2273            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2274
2275            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2276
2277            // save off the names of pre-existing system packages prior to scanning; we don't
2278            // want to automatically grant runtime permissions for new system apps
2279            if (mPromoteSystemApps) {
2280                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2281                while (pkgSettingIter.hasNext()) {
2282                    PackageSetting ps = pkgSettingIter.next();
2283                    if (isSystemApp(ps)) {
2284                        mExistingSystemPackages.add(ps.name);
2285                    }
2286                }
2287            }
2288
2289            // Collect vendor overlay packages. (Do this before scanning any apps.)
2290            // For security and version matching reason, only consider
2291            // overlay packages if they reside in the right directory.
2292            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2293            if (!overlayThemeDir.isEmpty()) {
2294                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2295                        | PackageParser.PARSE_IS_SYSTEM
2296                        | PackageParser.PARSE_IS_SYSTEM_DIR
2297                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2298            }
2299            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2300                    | PackageParser.PARSE_IS_SYSTEM
2301                    | PackageParser.PARSE_IS_SYSTEM_DIR
2302                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2303
2304            // Find base frameworks (resource packages without code).
2305            scanDirTracedLI(frameworkDir, mDefParseFlags
2306                    | PackageParser.PARSE_IS_SYSTEM
2307                    | PackageParser.PARSE_IS_SYSTEM_DIR
2308                    | PackageParser.PARSE_IS_PRIVILEGED,
2309                    scanFlags | SCAN_NO_DEX, 0);
2310
2311            // Collected privileged system packages.
2312            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2313            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2314                    | PackageParser.PARSE_IS_SYSTEM
2315                    | PackageParser.PARSE_IS_SYSTEM_DIR
2316                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2317
2318            // Collect ordinary system packages.
2319            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2320            scanDirTracedLI(systemAppDir, mDefParseFlags
2321                    | PackageParser.PARSE_IS_SYSTEM
2322                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2323
2324            // Collect all vendor packages.
2325            File vendorAppDir = new File("/vendor/app");
2326            try {
2327                vendorAppDir = vendorAppDir.getCanonicalFile();
2328            } catch (IOException e) {
2329                // failed to look up canonical path, continue with original one
2330            }
2331            scanDirTracedLI(vendorAppDir, mDefParseFlags
2332                    | PackageParser.PARSE_IS_SYSTEM
2333                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2334
2335            // Collect all OEM packages.
2336            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2337            scanDirTracedLI(oemAppDir, mDefParseFlags
2338                    | PackageParser.PARSE_IS_SYSTEM
2339                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2340
2341            // Prune any system packages that no longer exist.
2342            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2343            if (!mOnlyCore) {
2344                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2345                while (psit.hasNext()) {
2346                    PackageSetting ps = psit.next();
2347
2348                    /*
2349                     * If this is not a system app, it can't be a
2350                     * disable system app.
2351                     */
2352                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2353                        continue;
2354                    }
2355
2356                    /*
2357                     * If the package is scanned, it's not erased.
2358                     */
2359                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2360                    if (scannedPkg != null) {
2361                        /*
2362                         * If the system app is both scanned and in the
2363                         * disabled packages list, then it must have been
2364                         * added via OTA. Remove it from the currently
2365                         * scanned package so the previously user-installed
2366                         * application can be scanned.
2367                         */
2368                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2369                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2370                                    + ps.name + "; removing system app.  Last known codePath="
2371                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2372                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2373                                    + scannedPkg.mVersionCode);
2374                            removePackageLI(scannedPkg, true);
2375                            mExpectingBetter.put(ps.name, ps.codePath);
2376                        }
2377
2378                        continue;
2379                    }
2380
2381                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2382                        psit.remove();
2383                        logCriticalInfo(Log.WARN, "System package " + ps.name
2384                                + " no longer exists; it's data will be wiped");
2385                        // Actual deletion of code and data will be handled by later
2386                        // reconciliation step
2387                    } else {
2388                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2389                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2390                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2391                        }
2392                    }
2393                }
2394            }
2395
2396            //look for any incomplete package installations
2397            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2398            for (int i = 0; i < deletePkgsList.size(); i++) {
2399                // Actual deletion of code and data will be handled by later
2400                // reconciliation step
2401                final String packageName = deletePkgsList.get(i).name;
2402                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2403                synchronized (mPackages) {
2404                    mSettings.removePackageLPw(packageName);
2405                }
2406            }
2407
2408            //delete tmp files
2409            deleteTempPackageFiles();
2410
2411            // Remove any shared userIDs that have no associated packages
2412            mSettings.pruneSharedUsersLPw();
2413
2414            if (!mOnlyCore) {
2415                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2416                        SystemClock.uptimeMillis());
2417                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2418
2419                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2420                        | PackageParser.PARSE_FORWARD_LOCK,
2421                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2422
2423                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2424                        | PackageParser.PARSE_IS_EPHEMERAL,
2425                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2426
2427                /**
2428                 * Remove disable package settings for any updated system
2429                 * apps that were removed via an OTA. If they're not a
2430                 * previously-updated app, remove them completely.
2431                 * Otherwise, just revoke their system-level permissions.
2432                 */
2433                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2434                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2435                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2436
2437                    String msg;
2438                    if (deletedPkg == null) {
2439                        msg = "Updated system package " + deletedAppName
2440                                + " no longer exists; it's data will be wiped";
2441                        // Actual deletion of code and data will be handled by later
2442                        // reconciliation step
2443                    } else {
2444                        msg = "Updated system app + " + deletedAppName
2445                                + " no longer present; removing system privileges for "
2446                                + deletedAppName;
2447
2448                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2449
2450                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2451                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2452                    }
2453                    logCriticalInfo(Log.WARN, msg);
2454                }
2455
2456                /**
2457                 * Make sure all system apps that we expected to appear on
2458                 * the userdata partition actually showed up. If they never
2459                 * appeared, crawl back and revive the system version.
2460                 */
2461                for (int i = 0; i < mExpectingBetter.size(); i++) {
2462                    final String packageName = mExpectingBetter.keyAt(i);
2463                    if (!mPackages.containsKey(packageName)) {
2464                        final File scanFile = mExpectingBetter.valueAt(i);
2465
2466                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2467                                + " but never showed up; reverting to system");
2468
2469                        int reparseFlags = mDefParseFlags;
2470                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2471                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2472                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2473                                    | PackageParser.PARSE_IS_PRIVILEGED;
2474                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2475                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2476                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2477                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2478                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2479                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2480                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2481                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2482                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2483                        } else {
2484                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2485                            continue;
2486                        }
2487
2488                        mSettings.enableSystemPackageLPw(packageName);
2489
2490                        try {
2491                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2492                        } catch (PackageManagerException e) {
2493                            Slog.e(TAG, "Failed to parse original system package: "
2494                                    + e.getMessage());
2495                        }
2496                    }
2497                }
2498            }
2499            mExpectingBetter.clear();
2500
2501            // Resolve the storage manager.
2502            mStorageManagerPackage = getStorageManagerPackageName();
2503
2504            // Resolve protected action filters. Only the setup wizard is allowed to
2505            // have a high priority filter for these actions.
2506            mSetupWizardPackage = getSetupWizardPackageName();
2507            if (mProtectedFilters.size() > 0) {
2508                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2509                    Slog.i(TAG, "No setup wizard;"
2510                        + " All protected intents capped to priority 0");
2511                }
2512                for (ActivityIntentInfo filter : mProtectedFilters) {
2513                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2514                        if (DEBUG_FILTERS) {
2515                            Slog.i(TAG, "Found setup wizard;"
2516                                + " allow priority " + filter.getPriority() + ";"
2517                                + " package: " + filter.activity.info.packageName
2518                                + " activity: " + filter.activity.className
2519                                + " priority: " + filter.getPriority());
2520                        }
2521                        // skip setup wizard; allow it to keep the high priority filter
2522                        continue;
2523                    }
2524                    Slog.w(TAG, "Protected action; cap priority to 0;"
2525                            + " package: " + filter.activity.info.packageName
2526                            + " activity: " + filter.activity.className
2527                            + " origPrio: " + filter.getPriority());
2528                    filter.setPriority(0);
2529                }
2530            }
2531            mDeferProtectedFilters = false;
2532            mProtectedFilters.clear();
2533
2534            // Now that we know all of the shared libraries, update all clients to have
2535            // the correct library paths.
2536            updateAllSharedLibrariesLPw();
2537
2538            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2539                // NOTE: We ignore potential failures here during a system scan (like
2540                // the rest of the commands above) because there's precious little we
2541                // can do about it. A settings error is reported, though.
2542                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2543            }
2544
2545            // Now that we know all the packages we are keeping,
2546            // read and update their last usage times.
2547            mPackageUsage.read(mPackages);
2548            mCompilerStats.read();
2549
2550            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2551                    SystemClock.uptimeMillis());
2552            Slog.i(TAG, "Time to scan packages: "
2553                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2554                    + " seconds");
2555
2556            // If the platform SDK has changed since the last time we booted,
2557            // we need to re-grant app permission to catch any new ones that
2558            // appear.  This is really a hack, and means that apps can in some
2559            // cases get permissions that the user didn't initially explicitly
2560            // allow...  it would be nice to have some better way to handle
2561            // this situation.
2562            int updateFlags = UPDATE_PERMISSIONS_ALL;
2563            if (ver.sdkVersion != mSdkVersion) {
2564                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2565                        + mSdkVersion + "; regranting permissions for internal storage");
2566                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2567            }
2568            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2569            ver.sdkVersion = mSdkVersion;
2570
2571            // If this is the first boot or an update from pre-M, and it is a normal
2572            // boot, then we need to initialize the default preferred apps across
2573            // all defined users.
2574            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2575                for (UserInfo user : sUserManager.getUsers(true)) {
2576                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2577                    applyFactoryDefaultBrowserLPw(user.id);
2578                    primeDomainVerificationsLPw(user.id);
2579                }
2580            }
2581
2582            // Prepare storage for system user really early during boot,
2583            // since core system apps like SettingsProvider and SystemUI
2584            // can't wait for user to start
2585            final int storageFlags;
2586            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2587                storageFlags = StorageManager.FLAG_STORAGE_DE;
2588            } else {
2589                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2590            }
2591            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2592                    storageFlags, true /* migrateAppData */);
2593
2594            // If this is first boot after an OTA, and a normal boot, then
2595            // we need to clear code cache directories.
2596            // Note that we do *not* clear the application profiles. These remain valid
2597            // across OTAs and are used to drive profile verification (post OTA) and
2598            // profile compilation (without waiting to collect a fresh set of profiles).
2599            if (mIsUpgrade && !onlyCore) {
2600                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2601                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2602                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2603                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2604                        // No apps are running this early, so no need to freeze
2605                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2606                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2607                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2608                    }
2609                }
2610                ver.fingerprint = Build.FINGERPRINT;
2611            }
2612
2613            checkDefaultBrowser();
2614
2615            // clear only after permissions and other defaults have been updated
2616            mExistingSystemPackages.clear();
2617            mPromoteSystemApps = false;
2618
2619            // All the changes are done during package scanning.
2620            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2621
2622            // can downgrade to reader
2623            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2624            mSettings.writeLPr();
2625            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2626
2627            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2628            // early on (before the package manager declares itself as early) because other
2629            // components in the system server might ask for package contexts for these apps.
2630            //
2631            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2632            // (i.e, that the data partition is unavailable).
2633            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2634                long start = System.nanoTime();
2635                List<PackageParser.Package> coreApps = new ArrayList<>();
2636                for (PackageParser.Package pkg : mPackages.values()) {
2637                    if (pkg.coreApp) {
2638                        coreApps.add(pkg);
2639                    }
2640                }
2641
2642                int[] stats = performDexOptUpgrade(coreApps, false,
2643                        getCompilerFilterForReason(REASON_CORE_APP));
2644
2645                final int elapsedTimeSeconds =
2646                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2647                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2648
2649                if (DEBUG_DEXOPT) {
2650                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2651                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2652                }
2653
2654
2655                // TODO: Should we log these stats to tron too ?
2656                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2657                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2658                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2659                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2660            }
2661
2662            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2663                    SystemClock.uptimeMillis());
2664
2665            if (!mOnlyCore) {
2666                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2667                mRequiredInstallerPackage = getRequiredInstallerLPr();
2668                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2669                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2670                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2671                        mIntentFilterVerifierComponent);
2672                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2673                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2674                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2675                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2676            } else {
2677                mRequiredVerifierPackage = null;
2678                mRequiredInstallerPackage = null;
2679                mRequiredUninstallerPackage = null;
2680                mIntentFilterVerifierComponent = null;
2681                mIntentFilterVerifier = null;
2682                mServicesSystemSharedLibraryPackageName = null;
2683                mSharedSystemSharedLibraryPackageName = null;
2684            }
2685
2686            mInstallerService = new PackageInstallerService(context, this);
2687
2688            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2689            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2690            // both the installer and resolver must be present to enable ephemeral
2691            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2692                if (DEBUG_EPHEMERAL) {
2693                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2694                            + " installer:" + ephemeralInstallerComponent);
2695                }
2696                mEphemeralResolverComponent = ephemeralResolverComponent;
2697                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2698                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2699                mEphemeralResolverConnection =
2700                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2701            } else {
2702                if (DEBUG_EPHEMERAL) {
2703                    final String missingComponent =
2704                            (ephemeralResolverComponent == null)
2705                            ? (ephemeralInstallerComponent == null)
2706                                    ? "resolver and installer"
2707                                    : "resolver"
2708                            : "installer";
2709                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2710                }
2711                mEphemeralResolverComponent = null;
2712                mEphemeralInstallerComponent = null;
2713                mEphemeralResolverConnection = null;
2714            }
2715
2716            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2717        } // synchronized (mPackages)
2718        } // synchronized (mInstallLock)
2719
2720        // Now after opening every single application zip, make sure they
2721        // are all flushed.  Not really needed, but keeps things nice and
2722        // tidy.
2723        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2724        Runtime.getRuntime().gc();
2725        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2726
2727        // The initial scanning above does many calls into installd while
2728        // holding the mPackages lock, but we're mostly interested in yelling
2729        // once we have a booted system.
2730        mInstaller.setWarnIfHeld(mPackages);
2731
2732        // Expose private service for system components to use.
2733        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2734        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2735    }
2736
2737    @Override
2738    public boolean isFirstBoot() {
2739        return mFirstBoot;
2740    }
2741
2742    @Override
2743    public boolean isOnlyCoreApps() {
2744        return mOnlyCore;
2745    }
2746
2747    @Override
2748    public boolean isUpgrade() {
2749        return mIsUpgrade;
2750    }
2751
2752    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2753        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2754
2755        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2756                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2757                UserHandle.USER_SYSTEM);
2758        if (matches.size() == 1) {
2759            return matches.get(0).getComponentInfo().packageName;
2760        } else if (matches.size() == 0) {
2761            Log.e(TAG, "There should probably be a verifier, but, none were found");
2762            return null;
2763        }
2764        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2765    }
2766
2767    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2768        synchronized (mPackages) {
2769            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2770            if (libraryEntry == null) {
2771                throw new IllegalStateException("Missing required shared library:" + libraryName);
2772            }
2773            return libraryEntry.apk;
2774        }
2775    }
2776
2777    private @NonNull String getRequiredInstallerLPr() {
2778        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2779        intent.addCategory(Intent.CATEGORY_DEFAULT);
2780        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2781
2782        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2783                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2784                UserHandle.USER_SYSTEM);
2785        if (matches.size() == 1) {
2786            ResolveInfo resolveInfo = matches.get(0);
2787            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2788                throw new RuntimeException("The installer must be a privileged app");
2789            }
2790            return matches.get(0).getComponentInfo().packageName;
2791        } else {
2792            throw new RuntimeException("There must be exactly one installer; found " + matches);
2793        }
2794    }
2795
2796    private @NonNull String getRequiredUninstallerLPr() {
2797        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2798        intent.addCategory(Intent.CATEGORY_DEFAULT);
2799        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2800
2801        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2802                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2803                UserHandle.USER_SYSTEM);
2804        if (resolveInfo == null ||
2805                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2806            throw new RuntimeException("There must be exactly one uninstaller; found "
2807                    + resolveInfo);
2808        }
2809        return resolveInfo.getComponentInfo().packageName;
2810    }
2811
2812    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2813        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2814
2815        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2816                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2817                UserHandle.USER_SYSTEM);
2818        ResolveInfo best = null;
2819        final int N = matches.size();
2820        for (int i = 0; i < N; i++) {
2821            final ResolveInfo cur = matches.get(i);
2822            final String packageName = cur.getComponentInfo().packageName;
2823            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2824                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2825                continue;
2826            }
2827
2828            if (best == null || cur.priority > best.priority) {
2829                best = cur;
2830            }
2831        }
2832
2833        if (best != null) {
2834            return best.getComponentInfo().getComponentName();
2835        } else {
2836            throw new RuntimeException("There must be at least one intent filter verifier");
2837        }
2838    }
2839
2840    private @Nullable ComponentName getEphemeralResolverLPr() {
2841        final String[] packageArray =
2842                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2843        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2844            if (DEBUG_EPHEMERAL) {
2845                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2846            }
2847            return null;
2848        }
2849
2850        final int resolveFlags =
2851                MATCH_DIRECT_BOOT_AWARE
2852                | MATCH_DIRECT_BOOT_UNAWARE
2853                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2854        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2855        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2856                resolveFlags, UserHandle.USER_SYSTEM);
2857
2858        final int N = resolvers.size();
2859        if (N == 0) {
2860            if (DEBUG_EPHEMERAL) {
2861                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2862            }
2863            return null;
2864        }
2865
2866        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2867        for (int i = 0; i < N; i++) {
2868            final ResolveInfo info = resolvers.get(i);
2869
2870            if (info.serviceInfo == null) {
2871                continue;
2872            }
2873
2874            final String packageName = info.serviceInfo.packageName;
2875            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2876                if (DEBUG_EPHEMERAL) {
2877                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2878                            + " pkg: " + packageName + ", info:" + info);
2879                }
2880                continue;
2881            }
2882
2883            if (DEBUG_EPHEMERAL) {
2884                Slog.v(TAG, "Ephemeral resolver found;"
2885                        + " pkg: " + packageName + ", info:" + info);
2886            }
2887            return new ComponentName(packageName, info.serviceInfo.name);
2888        }
2889        if (DEBUG_EPHEMERAL) {
2890            Slog.v(TAG, "Ephemeral resolver NOT found");
2891        }
2892        return null;
2893    }
2894
2895    private @Nullable ComponentName getEphemeralInstallerLPr() {
2896        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2897        intent.addCategory(Intent.CATEGORY_DEFAULT);
2898        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2899
2900        final int resolveFlags =
2901                MATCH_DIRECT_BOOT_AWARE
2902                | MATCH_DIRECT_BOOT_UNAWARE
2903                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2904        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2905                resolveFlags, UserHandle.USER_SYSTEM);
2906        if (matches.size() == 0) {
2907            return null;
2908        } else if (matches.size() == 1) {
2909            return matches.get(0).getComponentInfo().getComponentName();
2910        } else {
2911            throw new RuntimeException(
2912                    "There must be at most one ephemeral installer; found " + matches);
2913        }
2914    }
2915
2916    private void primeDomainVerificationsLPw(int userId) {
2917        if (DEBUG_DOMAIN_VERIFICATION) {
2918            Slog.d(TAG, "Priming domain verifications in user " + userId);
2919        }
2920
2921        SystemConfig systemConfig = SystemConfig.getInstance();
2922        ArraySet<String> packages = systemConfig.getLinkedApps();
2923
2924        for (String packageName : packages) {
2925            PackageParser.Package pkg = mPackages.get(packageName);
2926            if (pkg != null) {
2927                if (!pkg.isSystemApp()) {
2928                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2929                    continue;
2930                }
2931
2932                ArraySet<String> domains = null;
2933                for (PackageParser.Activity a : pkg.activities) {
2934                    for (ActivityIntentInfo filter : a.intents) {
2935                        if (hasValidDomains(filter)) {
2936                            if (domains == null) {
2937                                domains = new ArraySet<String>();
2938                            }
2939                            domains.addAll(filter.getHostsList());
2940                        }
2941                    }
2942                }
2943
2944                if (domains != null && domains.size() > 0) {
2945                    if (DEBUG_DOMAIN_VERIFICATION) {
2946                        Slog.v(TAG, "      + " + packageName);
2947                    }
2948                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2949                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2950                    // and then 'always' in the per-user state actually used for intent resolution.
2951                    final IntentFilterVerificationInfo ivi;
2952                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
2953                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2954                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2955                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2956                } else {
2957                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2958                            + "' does not handle web links");
2959                }
2960            } else {
2961                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2962            }
2963        }
2964
2965        scheduleWritePackageRestrictionsLocked(userId);
2966        scheduleWriteSettingsLocked();
2967    }
2968
2969    private void applyFactoryDefaultBrowserLPw(int userId) {
2970        // The default browser app's package name is stored in a string resource,
2971        // with a product-specific overlay used for vendor customization.
2972        String browserPkg = mContext.getResources().getString(
2973                com.android.internal.R.string.default_browser);
2974        if (!TextUtils.isEmpty(browserPkg)) {
2975            // non-empty string => required to be a known package
2976            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2977            if (ps == null) {
2978                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2979                browserPkg = null;
2980            } else {
2981                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2982            }
2983        }
2984
2985        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2986        // default.  If there's more than one, just leave everything alone.
2987        if (browserPkg == null) {
2988            calculateDefaultBrowserLPw(userId);
2989        }
2990    }
2991
2992    private void calculateDefaultBrowserLPw(int userId) {
2993        List<String> allBrowsers = resolveAllBrowserApps(userId);
2994        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2995        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2996    }
2997
2998    private List<String> resolveAllBrowserApps(int userId) {
2999        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3000        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3001                PackageManager.MATCH_ALL, userId);
3002
3003        final int count = list.size();
3004        List<String> result = new ArrayList<String>(count);
3005        for (int i=0; i<count; i++) {
3006            ResolveInfo info = list.get(i);
3007            if (info.activityInfo == null
3008                    || !info.handleAllWebDataURI
3009                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3010                    || result.contains(info.activityInfo.packageName)) {
3011                continue;
3012            }
3013            result.add(info.activityInfo.packageName);
3014        }
3015
3016        return result;
3017    }
3018
3019    private boolean packageIsBrowser(String packageName, int userId) {
3020        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3021                PackageManager.MATCH_ALL, userId);
3022        final int N = list.size();
3023        for (int i = 0; i < N; i++) {
3024            ResolveInfo info = list.get(i);
3025            if (packageName.equals(info.activityInfo.packageName)) {
3026                return true;
3027            }
3028        }
3029        return false;
3030    }
3031
3032    private void checkDefaultBrowser() {
3033        final int myUserId = UserHandle.myUserId();
3034        final String packageName = getDefaultBrowserPackageName(myUserId);
3035        if (packageName != null) {
3036            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3037            if (info == null) {
3038                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3039                synchronized (mPackages) {
3040                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3041                }
3042            }
3043        }
3044    }
3045
3046    @Override
3047    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3048            throws RemoteException {
3049        try {
3050            return super.onTransact(code, data, reply, flags);
3051        } catch (RuntimeException e) {
3052            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3053                Slog.wtf(TAG, "Package Manager Crash", e);
3054            }
3055            throw e;
3056        }
3057    }
3058
3059    static int[] appendInts(int[] cur, int[] add) {
3060        if (add == null) return cur;
3061        if (cur == null) return add;
3062        final int N = add.length;
3063        for (int i=0; i<N; i++) {
3064            cur = appendInt(cur, add[i]);
3065        }
3066        return cur;
3067    }
3068
3069    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3070        if (!sUserManager.exists(userId)) return null;
3071        if (ps == null) {
3072            return null;
3073        }
3074        final PackageParser.Package p = ps.pkg;
3075        if (p == null) {
3076            return null;
3077        }
3078
3079        final PermissionsState permissionsState = ps.getPermissionsState();
3080
3081        // Compute GIDs only if requested
3082        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3083                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3084        // Compute granted permissions only if package has requested permissions
3085        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3086                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3087        final PackageUserState state = ps.readUserState(userId);
3088
3089        return PackageParser.generatePackageInfo(p, gids, flags,
3090                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3091    }
3092
3093    @Override
3094    public void checkPackageStartable(String packageName, int userId) {
3095        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3096
3097        synchronized (mPackages) {
3098            final PackageSetting ps = mSettings.mPackages.get(packageName);
3099            if (ps == null) {
3100                throw new SecurityException("Package " + packageName + " was not found!");
3101            }
3102
3103            if (!ps.getInstalled(userId)) {
3104                throw new SecurityException(
3105                        "Package " + packageName + " was not installed for user " + userId + "!");
3106            }
3107
3108            if (mSafeMode && !ps.isSystem()) {
3109                throw new SecurityException("Package " + packageName + " not a system app!");
3110            }
3111
3112            if (mFrozenPackages.contains(packageName)) {
3113                throw new SecurityException("Package " + packageName + " is currently frozen!");
3114            }
3115
3116            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3117                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3118                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3119            }
3120        }
3121    }
3122
3123    @Override
3124    public boolean isPackageAvailable(String packageName, int userId) {
3125        if (!sUserManager.exists(userId)) return false;
3126        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3127                false /* requireFullPermission */, false /* checkShell */, "is package available");
3128        synchronized (mPackages) {
3129            PackageParser.Package p = mPackages.get(packageName);
3130            if (p != null) {
3131                final PackageSetting ps = (PackageSetting) p.mExtras;
3132                if (ps != null) {
3133                    final PackageUserState state = ps.readUserState(userId);
3134                    if (state != null) {
3135                        return PackageParser.isAvailable(state);
3136                    }
3137                }
3138            }
3139        }
3140        return false;
3141    }
3142
3143    @Override
3144    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3145        if (!sUserManager.exists(userId)) return null;
3146        flags = updateFlagsForPackage(flags, userId, packageName);
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3148                false /* requireFullPermission */, false /* checkShell */, "get package info");
3149        // reader
3150        synchronized (mPackages) {
3151            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3152            PackageParser.Package p = null;
3153            if (matchFactoryOnly) {
3154                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3155                if (ps != null) {
3156                    return generatePackageInfo(ps, flags, userId);
3157                }
3158            }
3159            if (p == null) {
3160                p = mPackages.get(packageName);
3161                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3162                    return null;
3163                }
3164            }
3165            if (DEBUG_PACKAGE_INFO)
3166                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3167            if (p != null) {
3168                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3169            }
3170            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3171                final PackageSetting ps = mSettings.mPackages.get(packageName);
3172                return generatePackageInfo(ps, flags, userId);
3173            }
3174        }
3175        return null;
3176    }
3177
3178    @Override
3179    public String[] currentToCanonicalPackageNames(String[] names) {
3180        String[] out = new String[names.length];
3181        // reader
3182        synchronized (mPackages) {
3183            for (int i=names.length-1; i>=0; i--) {
3184                PackageSetting ps = mSettings.mPackages.get(names[i]);
3185                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3186            }
3187        }
3188        return out;
3189    }
3190
3191    @Override
3192    public String[] canonicalToCurrentPackageNames(String[] names) {
3193        String[] out = new String[names.length];
3194        // reader
3195        synchronized (mPackages) {
3196            for (int i=names.length-1; i>=0; i--) {
3197                String cur = mSettings.getRenamedPackageLPr(names[i]);
3198                out[i] = cur != null ? cur : names[i];
3199            }
3200        }
3201        return out;
3202    }
3203
3204    @Override
3205    public int getPackageUid(String packageName, int flags, int userId) {
3206        if (!sUserManager.exists(userId)) return -1;
3207        flags = updateFlagsForPackage(flags, userId, packageName);
3208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3209                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3210
3211        // reader
3212        synchronized (mPackages) {
3213            final PackageParser.Package p = mPackages.get(packageName);
3214            if (p != null && p.isMatch(flags)) {
3215                return UserHandle.getUid(userId, p.applicationInfo.uid);
3216            }
3217            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3218                final PackageSetting ps = mSettings.mPackages.get(packageName);
3219                if (ps != null && ps.isMatch(flags)) {
3220                    return UserHandle.getUid(userId, ps.appId);
3221                }
3222            }
3223        }
3224
3225        return -1;
3226    }
3227
3228    @Override
3229    public int[] getPackageGids(String packageName, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return null;
3231        flags = updateFlagsForPackage(flags, userId, packageName);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3233                false /* requireFullPermission */, false /* checkShell */,
3234                "getPackageGids");
3235
3236        // reader
3237        synchronized (mPackages) {
3238            final PackageParser.Package p = mPackages.get(packageName);
3239            if (p != null && p.isMatch(flags)) {
3240                PackageSetting ps = (PackageSetting) p.mExtras;
3241                return ps.getPermissionsState().computeGids(userId);
3242            }
3243            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3244                final PackageSetting ps = mSettings.mPackages.get(packageName);
3245                if (ps != null && ps.isMatch(flags)) {
3246                    return ps.getPermissionsState().computeGids(userId);
3247                }
3248            }
3249        }
3250
3251        return null;
3252    }
3253
3254    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3255        if (bp.perm != null) {
3256            return PackageParser.generatePermissionInfo(bp.perm, flags);
3257        }
3258        PermissionInfo pi = new PermissionInfo();
3259        pi.name = bp.name;
3260        pi.packageName = bp.sourcePackage;
3261        pi.nonLocalizedLabel = bp.name;
3262        pi.protectionLevel = bp.protectionLevel;
3263        return pi;
3264    }
3265
3266    @Override
3267    public PermissionInfo getPermissionInfo(String name, int flags) {
3268        // reader
3269        synchronized (mPackages) {
3270            final BasePermission p = mSettings.mPermissions.get(name);
3271            if (p != null) {
3272                return generatePermissionInfo(p, flags);
3273            }
3274            return null;
3275        }
3276    }
3277
3278    @Override
3279    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3280            int flags) {
3281        // reader
3282        synchronized (mPackages) {
3283            if (group != null && !mPermissionGroups.containsKey(group)) {
3284                // This is thrown as NameNotFoundException
3285                return null;
3286            }
3287
3288            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3289            for (BasePermission p : mSettings.mPermissions.values()) {
3290                if (group == null) {
3291                    if (p.perm == null || p.perm.info.group == null) {
3292                        out.add(generatePermissionInfo(p, flags));
3293                    }
3294                } else {
3295                    if (p.perm != null && group.equals(p.perm.info.group)) {
3296                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3297                    }
3298                }
3299            }
3300            return new ParceledListSlice<>(out);
3301        }
3302    }
3303
3304    @Override
3305    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3306        // reader
3307        synchronized (mPackages) {
3308            return PackageParser.generatePermissionGroupInfo(
3309                    mPermissionGroups.get(name), flags);
3310        }
3311    }
3312
3313    @Override
3314    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3315        // reader
3316        synchronized (mPackages) {
3317            final int N = mPermissionGroups.size();
3318            ArrayList<PermissionGroupInfo> out
3319                    = new ArrayList<PermissionGroupInfo>(N);
3320            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3321                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3322            }
3323            return new ParceledListSlice<>(out);
3324        }
3325    }
3326
3327    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3328            int userId) {
3329        if (!sUserManager.exists(userId)) return null;
3330        PackageSetting ps = mSettings.mPackages.get(packageName);
3331        if (ps != null) {
3332            if (ps.pkg == null) {
3333                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3334                if (pInfo != null) {
3335                    return pInfo.applicationInfo;
3336                }
3337                return null;
3338            }
3339            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3340                    ps.readUserState(userId), userId);
3341        }
3342        return null;
3343    }
3344
3345    @Override
3346    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3347        if (!sUserManager.exists(userId)) return null;
3348        flags = updateFlagsForApplication(flags, userId, packageName);
3349        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3350                false /* requireFullPermission */, false /* checkShell */, "get application info");
3351        // writer
3352        synchronized (mPackages) {
3353            PackageParser.Package p = mPackages.get(packageName);
3354            if (DEBUG_PACKAGE_INFO) Log.v(
3355                    TAG, "getApplicationInfo " + packageName
3356                    + ": " + p);
3357            if (p != null) {
3358                PackageSetting ps = mSettings.mPackages.get(packageName);
3359                if (ps == null) return null;
3360                // Note: isEnabledLP() does not apply here - always return info
3361                return PackageParser.generateApplicationInfo(
3362                        p, flags, ps.readUserState(userId), userId);
3363            }
3364            if ("android".equals(packageName)||"system".equals(packageName)) {
3365                return mAndroidApplication;
3366            }
3367            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3368                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3369            }
3370        }
3371        return null;
3372    }
3373
3374    @Override
3375    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3376            final IPackageDataObserver observer) {
3377        mContext.enforceCallingOrSelfPermission(
3378                android.Manifest.permission.CLEAR_APP_CACHE, null);
3379        // Queue up an async operation since clearing cache may take a little while.
3380        mHandler.post(new Runnable() {
3381            public void run() {
3382                mHandler.removeCallbacks(this);
3383                boolean success = true;
3384                synchronized (mInstallLock) {
3385                    try {
3386                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3387                    } catch (InstallerException e) {
3388                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3389                        success = false;
3390                    }
3391                }
3392                if (observer != null) {
3393                    try {
3394                        observer.onRemoveCompleted(null, success);
3395                    } catch (RemoteException e) {
3396                        Slog.w(TAG, "RemoveException when invoking call back");
3397                    }
3398                }
3399            }
3400        });
3401    }
3402
3403    @Override
3404    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3405            final IntentSender pi) {
3406        mContext.enforceCallingOrSelfPermission(
3407                android.Manifest.permission.CLEAR_APP_CACHE, null);
3408        // Queue up an async operation since clearing cache may take a little while.
3409        mHandler.post(new Runnable() {
3410            public void run() {
3411                mHandler.removeCallbacks(this);
3412                boolean success = true;
3413                synchronized (mInstallLock) {
3414                    try {
3415                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3416                    } catch (InstallerException e) {
3417                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3418                        success = false;
3419                    }
3420                }
3421                if(pi != null) {
3422                    try {
3423                        // Callback via pending intent
3424                        int code = success ? 1 : 0;
3425                        pi.sendIntent(null, code, null,
3426                                null, null);
3427                    } catch (SendIntentException e1) {
3428                        Slog.i(TAG, "Failed to send pending intent");
3429                    }
3430                }
3431            }
3432        });
3433    }
3434
3435    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3436        synchronized (mInstallLock) {
3437            try {
3438                mInstaller.freeCache(volumeUuid, freeStorageSize);
3439            } catch (InstallerException e) {
3440                throw new IOException("Failed to free enough space", e);
3441            }
3442        }
3443    }
3444
3445    /**
3446     * Update given flags based on encryption status of current user.
3447     */
3448    private int updateFlags(int flags, int userId) {
3449        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3450                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3451            // Caller expressed an explicit opinion about what encryption
3452            // aware/unaware components they want to see, so fall through and
3453            // give them what they want
3454        } else {
3455            // Caller expressed no opinion, so match based on user state
3456            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3457                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3458            } else {
3459                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3460            }
3461        }
3462        return flags;
3463    }
3464
3465    private UserManagerInternal getUserManagerInternal() {
3466        if (mUserManagerInternal == null) {
3467            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3468        }
3469        return mUserManagerInternal;
3470    }
3471
3472    /**
3473     * Update given flags when being used to request {@link PackageInfo}.
3474     */
3475    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3476        boolean triaged = true;
3477        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3478                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3479            // Caller is asking for component details, so they'd better be
3480            // asking for specific encryption matching behavior, or be triaged
3481            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3482                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3483                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3484                triaged = false;
3485            }
3486        }
3487        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3488                | PackageManager.MATCH_SYSTEM_ONLY
3489                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3490            triaged = false;
3491        }
3492        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3493            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3494                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3495        }
3496        return updateFlags(flags, userId);
3497    }
3498
3499    /**
3500     * Update given flags when being used to request {@link ApplicationInfo}.
3501     */
3502    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3503        return updateFlagsForPackage(flags, userId, cookie);
3504    }
3505
3506    /**
3507     * Update given flags when being used to request {@link ComponentInfo}.
3508     */
3509    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3510        if (cookie instanceof Intent) {
3511            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3512                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3513            }
3514        }
3515
3516        boolean triaged = true;
3517        // Caller is asking for component details, so they'd better be
3518        // asking for specific encryption matching behavior, or be triaged
3519        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3520                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3521                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3522            triaged = false;
3523        }
3524        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3525            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3526                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3527        }
3528
3529        return updateFlags(flags, userId);
3530    }
3531
3532    /**
3533     * Update given flags when being used to request {@link ResolveInfo}.
3534     */
3535    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3536        // Safe mode means we shouldn't match any third-party components
3537        if (mSafeMode) {
3538            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3539        }
3540
3541        return updateFlagsForComponent(flags, userId, cookie);
3542    }
3543
3544    @Override
3545    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        flags = updateFlagsForComponent(flags, userId, component);
3548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3549                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3550        synchronized (mPackages) {
3551            PackageParser.Activity a = mActivities.mActivities.get(component);
3552
3553            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3554            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3555                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3556                if (ps == null) return null;
3557                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3558                        userId);
3559            }
3560            if (mResolveComponentName.equals(component)) {
3561                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3562                        new PackageUserState(), userId);
3563            }
3564        }
3565        return null;
3566    }
3567
3568    @Override
3569    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3570            String resolvedType) {
3571        synchronized (mPackages) {
3572            if (component.equals(mResolveComponentName)) {
3573                // The resolver supports EVERYTHING!
3574                return true;
3575            }
3576            PackageParser.Activity a = mActivities.mActivities.get(component);
3577            if (a == null) {
3578                return false;
3579            }
3580            for (int i=0; i<a.intents.size(); i++) {
3581                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3582                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3583                    return true;
3584                }
3585            }
3586            return false;
3587        }
3588    }
3589
3590    @Override
3591    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3592        if (!sUserManager.exists(userId)) return null;
3593        flags = updateFlagsForComponent(flags, userId, component);
3594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3595                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3596        synchronized (mPackages) {
3597            PackageParser.Activity a = mReceivers.mActivities.get(component);
3598            if (DEBUG_PACKAGE_INFO) Log.v(
3599                TAG, "getReceiverInfo " + component + ": " + a);
3600            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3601                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3602                if (ps == null) return null;
3603                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3604                        userId);
3605            }
3606        }
3607        return null;
3608    }
3609
3610    @Override
3611    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3612        if (!sUserManager.exists(userId)) return null;
3613        flags = updateFlagsForComponent(flags, userId, component);
3614        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3615                false /* requireFullPermission */, false /* checkShell */, "get service info");
3616        synchronized (mPackages) {
3617            PackageParser.Service s = mServices.mServices.get(component);
3618            if (DEBUG_PACKAGE_INFO) Log.v(
3619                TAG, "getServiceInfo " + component + ": " + s);
3620            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3622                if (ps == null) return null;
3623                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3624                        userId);
3625            }
3626        }
3627        return null;
3628    }
3629
3630    @Override
3631    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3632        if (!sUserManager.exists(userId)) return null;
3633        flags = updateFlagsForComponent(flags, userId, component);
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3636        synchronized (mPackages) {
3637            PackageParser.Provider p = mProviders.mProviders.get(component);
3638            if (DEBUG_PACKAGE_INFO) Log.v(
3639                TAG, "getProviderInfo " + component + ": " + p);
3640            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3641                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3642                if (ps == null) return null;
3643                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3644                        userId);
3645            }
3646        }
3647        return null;
3648    }
3649
3650    @Override
3651    public String[] getSystemSharedLibraryNames() {
3652        Set<String> libSet;
3653        synchronized (mPackages) {
3654            libSet = mSharedLibraries.keySet();
3655            int size = libSet.size();
3656            if (size > 0) {
3657                String[] libs = new String[size];
3658                libSet.toArray(libs);
3659                return libs;
3660            }
3661        }
3662        return null;
3663    }
3664
3665    @Override
3666    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3667        synchronized (mPackages) {
3668            return mServicesSystemSharedLibraryPackageName;
3669        }
3670    }
3671
3672    @Override
3673    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3674        synchronized (mPackages) {
3675            return mSharedSystemSharedLibraryPackageName;
3676        }
3677    }
3678
3679    @Override
3680    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3681        synchronized (mPackages) {
3682            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3683
3684            final FeatureInfo fi = new FeatureInfo();
3685            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3686                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3687            res.add(fi);
3688
3689            return new ParceledListSlice<>(res);
3690        }
3691    }
3692
3693    @Override
3694    public boolean hasSystemFeature(String name, int version) {
3695        synchronized (mPackages) {
3696            final FeatureInfo feat = mAvailableFeatures.get(name);
3697            if (feat == null) {
3698                return false;
3699            } else {
3700                return feat.version >= version;
3701            }
3702        }
3703    }
3704
3705    @Override
3706    public int checkPermission(String permName, String pkgName, int userId) {
3707        if (!sUserManager.exists(userId)) {
3708            return PackageManager.PERMISSION_DENIED;
3709        }
3710
3711        synchronized (mPackages) {
3712            final PackageParser.Package p = mPackages.get(pkgName);
3713            if (p != null && p.mExtras != null) {
3714                final PackageSetting ps = (PackageSetting) p.mExtras;
3715                final PermissionsState permissionsState = ps.getPermissionsState();
3716                if (permissionsState.hasPermission(permName, userId)) {
3717                    return PackageManager.PERMISSION_GRANTED;
3718                }
3719                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3720                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3721                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3722                    return PackageManager.PERMISSION_GRANTED;
3723                }
3724            }
3725        }
3726
3727        return PackageManager.PERMISSION_DENIED;
3728    }
3729
3730    @Override
3731    public int checkUidPermission(String permName, int uid) {
3732        final int userId = UserHandle.getUserId(uid);
3733
3734        if (!sUserManager.exists(userId)) {
3735            return PackageManager.PERMISSION_DENIED;
3736        }
3737
3738        synchronized (mPackages) {
3739            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3740            if (obj != null) {
3741                final SettingBase ps = (SettingBase) obj;
3742                final PermissionsState permissionsState = ps.getPermissionsState();
3743                if (permissionsState.hasPermission(permName, userId)) {
3744                    return PackageManager.PERMISSION_GRANTED;
3745                }
3746                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3747                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3748                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3749                    return PackageManager.PERMISSION_GRANTED;
3750                }
3751            } else {
3752                ArraySet<String> perms = mSystemPermissions.get(uid);
3753                if (perms != null) {
3754                    if (perms.contains(permName)) {
3755                        return PackageManager.PERMISSION_GRANTED;
3756                    }
3757                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3758                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3759                        return PackageManager.PERMISSION_GRANTED;
3760                    }
3761                }
3762            }
3763        }
3764
3765        return PackageManager.PERMISSION_DENIED;
3766    }
3767
3768    @Override
3769    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3770        if (UserHandle.getCallingUserId() != userId) {
3771            mContext.enforceCallingPermission(
3772                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3773                    "isPermissionRevokedByPolicy for user " + userId);
3774        }
3775
3776        if (checkPermission(permission, packageName, userId)
3777                == PackageManager.PERMISSION_GRANTED) {
3778            return false;
3779        }
3780
3781        final long identity = Binder.clearCallingIdentity();
3782        try {
3783            final int flags = getPermissionFlags(permission, packageName, userId);
3784            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3785        } finally {
3786            Binder.restoreCallingIdentity(identity);
3787        }
3788    }
3789
3790    @Override
3791    public String getPermissionControllerPackageName() {
3792        synchronized (mPackages) {
3793            return mRequiredInstallerPackage;
3794        }
3795    }
3796
3797    /**
3798     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3799     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3800     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3801     * @param message the message to log on security exception
3802     */
3803    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3804            boolean checkShell, String message) {
3805        if (userId < 0) {
3806            throw new IllegalArgumentException("Invalid userId " + userId);
3807        }
3808        if (checkShell) {
3809            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3810        }
3811        if (userId == UserHandle.getUserId(callingUid)) return;
3812        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3813            if (requireFullPermission) {
3814                mContext.enforceCallingOrSelfPermission(
3815                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3816            } else {
3817                try {
3818                    mContext.enforceCallingOrSelfPermission(
3819                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3820                } catch (SecurityException se) {
3821                    mContext.enforceCallingOrSelfPermission(
3822                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3823                }
3824            }
3825        }
3826    }
3827
3828    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3829        if (callingUid == Process.SHELL_UID) {
3830            if (userHandle >= 0
3831                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3832                throw new SecurityException("Shell does not have permission to access user "
3833                        + userHandle);
3834            } else if (userHandle < 0) {
3835                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3836                        + Debug.getCallers(3));
3837            }
3838        }
3839    }
3840
3841    private BasePermission findPermissionTreeLP(String permName) {
3842        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3843            if (permName.startsWith(bp.name) &&
3844                    permName.length() > bp.name.length() &&
3845                    permName.charAt(bp.name.length()) == '.') {
3846                return bp;
3847            }
3848        }
3849        return null;
3850    }
3851
3852    private BasePermission checkPermissionTreeLP(String permName) {
3853        if (permName != null) {
3854            BasePermission bp = findPermissionTreeLP(permName);
3855            if (bp != null) {
3856                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3857                    return bp;
3858                }
3859                throw new SecurityException("Calling uid "
3860                        + Binder.getCallingUid()
3861                        + " is not allowed to add to permission tree "
3862                        + bp.name + " owned by uid " + bp.uid);
3863            }
3864        }
3865        throw new SecurityException("No permission tree found for " + permName);
3866    }
3867
3868    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3869        if (s1 == null) {
3870            return s2 == null;
3871        }
3872        if (s2 == null) {
3873            return false;
3874        }
3875        if (s1.getClass() != s2.getClass()) {
3876            return false;
3877        }
3878        return s1.equals(s2);
3879    }
3880
3881    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3882        if (pi1.icon != pi2.icon) return false;
3883        if (pi1.logo != pi2.logo) return false;
3884        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3885        if (!compareStrings(pi1.name, pi2.name)) return false;
3886        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3887        // We'll take care of setting this one.
3888        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3889        // These are not currently stored in settings.
3890        //if (!compareStrings(pi1.group, pi2.group)) return false;
3891        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3892        //if (pi1.labelRes != pi2.labelRes) return false;
3893        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3894        return true;
3895    }
3896
3897    int permissionInfoFootprint(PermissionInfo info) {
3898        int size = info.name.length();
3899        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3900        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3901        return size;
3902    }
3903
3904    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3905        int size = 0;
3906        for (BasePermission perm : mSettings.mPermissions.values()) {
3907            if (perm.uid == tree.uid) {
3908                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3909            }
3910        }
3911        return size;
3912    }
3913
3914    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3915        // We calculate the max size of permissions defined by this uid and throw
3916        // if that plus the size of 'info' would exceed our stated maximum.
3917        if (tree.uid != Process.SYSTEM_UID) {
3918            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3919            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3920                throw new SecurityException("Permission tree size cap exceeded");
3921            }
3922        }
3923    }
3924
3925    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3926        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3927            throw new SecurityException("Label must be specified in permission");
3928        }
3929        BasePermission tree = checkPermissionTreeLP(info.name);
3930        BasePermission bp = mSettings.mPermissions.get(info.name);
3931        boolean added = bp == null;
3932        boolean changed = true;
3933        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3934        if (added) {
3935            enforcePermissionCapLocked(info, tree);
3936            bp = new BasePermission(info.name, tree.sourcePackage,
3937                    BasePermission.TYPE_DYNAMIC);
3938        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3939            throw new SecurityException(
3940                    "Not allowed to modify non-dynamic permission "
3941                    + info.name);
3942        } else {
3943            if (bp.protectionLevel == fixedLevel
3944                    && bp.perm.owner.equals(tree.perm.owner)
3945                    && bp.uid == tree.uid
3946                    && comparePermissionInfos(bp.perm.info, info)) {
3947                changed = false;
3948            }
3949        }
3950        bp.protectionLevel = fixedLevel;
3951        info = new PermissionInfo(info);
3952        info.protectionLevel = fixedLevel;
3953        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3954        bp.perm.info.packageName = tree.perm.info.packageName;
3955        bp.uid = tree.uid;
3956        if (added) {
3957            mSettings.mPermissions.put(info.name, bp);
3958        }
3959        if (changed) {
3960            if (!async) {
3961                mSettings.writeLPr();
3962            } else {
3963                scheduleWriteSettingsLocked();
3964            }
3965        }
3966        return added;
3967    }
3968
3969    @Override
3970    public boolean addPermission(PermissionInfo info) {
3971        synchronized (mPackages) {
3972            return addPermissionLocked(info, false);
3973        }
3974    }
3975
3976    @Override
3977    public boolean addPermissionAsync(PermissionInfo info) {
3978        synchronized (mPackages) {
3979            return addPermissionLocked(info, true);
3980        }
3981    }
3982
3983    @Override
3984    public void removePermission(String name) {
3985        synchronized (mPackages) {
3986            checkPermissionTreeLP(name);
3987            BasePermission bp = mSettings.mPermissions.get(name);
3988            if (bp != null) {
3989                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3990                    throw new SecurityException(
3991                            "Not allowed to modify non-dynamic permission "
3992                            + name);
3993                }
3994                mSettings.mPermissions.remove(name);
3995                mSettings.writeLPr();
3996            }
3997        }
3998    }
3999
4000    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4001            BasePermission bp) {
4002        int index = pkg.requestedPermissions.indexOf(bp.name);
4003        if (index == -1) {
4004            throw new SecurityException("Package " + pkg.packageName
4005                    + " has not requested permission " + bp.name);
4006        }
4007        if (!bp.isRuntime() && !bp.isDevelopment()) {
4008            throw new SecurityException("Permission " + bp.name
4009                    + " is not a changeable permission type");
4010        }
4011    }
4012
4013    @Override
4014    public void grantRuntimePermission(String packageName, String name, final int userId) {
4015        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4016    }
4017
4018    private void grantRuntimePermission(String packageName, String name, final int userId,
4019            boolean overridePolicy) {
4020        if (!sUserManager.exists(userId)) {
4021            Log.e(TAG, "No such user:" + userId);
4022            return;
4023        }
4024
4025        mContext.enforceCallingOrSelfPermission(
4026                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4027                "grantRuntimePermission");
4028
4029        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4030                true /* requireFullPermission */, true /* checkShell */,
4031                "grantRuntimePermission");
4032
4033        final int uid;
4034        final SettingBase sb;
4035
4036        synchronized (mPackages) {
4037            final PackageParser.Package pkg = mPackages.get(packageName);
4038            if (pkg == null) {
4039                throw new IllegalArgumentException("Unknown package: " + packageName);
4040            }
4041
4042            final BasePermission bp = mSettings.mPermissions.get(name);
4043            if (bp == null) {
4044                throw new IllegalArgumentException("Unknown permission: " + name);
4045            }
4046
4047            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4048
4049            // If a permission review is required for legacy apps we represent
4050            // their permissions as always granted runtime ones since we need
4051            // to keep the review required permission flag per user while an
4052            // install permission's state is shared across all users.
4053            if (mPermissionReviewRequired
4054                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4055                    && bp.isRuntime()) {
4056                return;
4057            }
4058
4059            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4060            sb = (SettingBase) pkg.mExtras;
4061            if (sb == null) {
4062                throw new IllegalArgumentException("Unknown package: " + packageName);
4063            }
4064
4065            final PermissionsState permissionsState = sb.getPermissionsState();
4066
4067            final int flags = permissionsState.getPermissionFlags(name, userId);
4068            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4069                throw new SecurityException("Cannot grant system fixed permission "
4070                        + name + " for package " + packageName);
4071            }
4072            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4073                throw new SecurityException("Cannot grant policy fixed permission "
4074                        + name + " for package " + packageName);
4075            }
4076
4077            if (bp.isDevelopment()) {
4078                // Development permissions must be handled specially, since they are not
4079                // normal runtime permissions.  For now they apply to all users.
4080                if (permissionsState.grantInstallPermission(bp) !=
4081                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4082                    scheduleWriteSettingsLocked();
4083                }
4084                return;
4085            }
4086
4087            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4088                throw new SecurityException("Cannot grant non-ephemeral permission"
4089                        + name + " for package " + packageName);
4090            }
4091
4092            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4093                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4094                return;
4095            }
4096
4097            final int result = permissionsState.grantRuntimePermission(bp, userId);
4098            switch (result) {
4099                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4100                    return;
4101                }
4102
4103                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4104                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4105                    mHandler.post(new Runnable() {
4106                        @Override
4107                        public void run() {
4108                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4109                        }
4110                    });
4111                }
4112                break;
4113            }
4114
4115            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4116
4117            // Not critical if that is lost - app has to request again.
4118            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4119        }
4120
4121        // Only need to do this if user is initialized. Otherwise it's a new user
4122        // and there are no processes running as the user yet and there's no need
4123        // to make an expensive call to remount processes for the changed permissions.
4124        if (READ_EXTERNAL_STORAGE.equals(name)
4125                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4126            final long token = Binder.clearCallingIdentity();
4127            try {
4128                if (sUserManager.isInitialized(userId)) {
4129                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4130                            MountServiceInternal.class);
4131                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4132                }
4133            } finally {
4134                Binder.restoreCallingIdentity(token);
4135            }
4136        }
4137    }
4138
4139    @Override
4140    public void revokeRuntimePermission(String packageName, String name, int userId) {
4141        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4142    }
4143
4144    private void revokeRuntimePermission(String packageName, String name, int userId,
4145            boolean overridePolicy) {
4146        if (!sUserManager.exists(userId)) {
4147            Log.e(TAG, "No such user:" + userId);
4148            return;
4149        }
4150
4151        mContext.enforceCallingOrSelfPermission(
4152                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4153                "revokeRuntimePermission");
4154
4155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4156                true /* requireFullPermission */, true /* checkShell */,
4157                "revokeRuntimePermission");
4158
4159        final int appId;
4160
4161        synchronized (mPackages) {
4162            final PackageParser.Package pkg = mPackages.get(packageName);
4163            if (pkg == null) {
4164                throw new IllegalArgumentException("Unknown package: " + packageName);
4165            }
4166
4167            final BasePermission bp = mSettings.mPermissions.get(name);
4168            if (bp == null) {
4169                throw new IllegalArgumentException("Unknown permission: " + name);
4170            }
4171
4172            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4173
4174            // If a permission review is required for legacy apps we represent
4175            // their permissions as always granted runtime ones since we need
4176            // to keep the review required permission flag per user while an
4177            // install permission's state is shared across all users.
4178            if (mPermissionReviewRequired
4179                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4180                    && bp.isRuntime()) {
4181                return;
4182            }
4183
4184            SettingBase sb = (SettingBase) pkg.mExtras;
4185            if (sb == null) {
4186                throw new IllegalArgumentException("Unknown package: " + packageName);
4187            }
4188
4189            final PermissionsState permissionsState = sb.getPermissionsState();
4190
4191            final int flags = permissionsState.getPermissionFlags(name, userId);
4192            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4193                throw new SecurityException("Cannot revoke system fixed permission "
4194                        + name + " for package " + packageName);
4195            }
4196            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4197                throw new SecurityException("Cannot revoke policy fixed permission "
4198                        + name + " for package " + packageName);
4199            }
4200
4201            if (bp.isDevelopment()) {
4202                // Development permissions must be handled specially, since they are not
4203                // normal runtime permissions.  For now they apply to all users.
4204                if (permissionsState.revokeInstallPermission(bp) !=
4205                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4206                    scheduleWriteSettingsLocked();
4207                }
4208                return;
4209            }
4210
4211            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4212                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4213                return;
4214            }
4215
4216            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4217
4218            // Critical, after this call app should never have the permission.
4219            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4220
4221            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4222        }
4223
4224        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4225    }
4226
4227    @Override
4228    public void resetRuntimePermissions() {
4229        mContext.enforceCallingOrSelfPermission(
4230                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4231                "revokeRuntimePermission");
4232
4233        int callingUid = Binder.getCallingUid();
4234        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4235            mContext.enforceCallingOrSelfPermission(
4236                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4237                    "resetRuntimePermissions");
4238        }
4239
4240        synchronized (mPackages) {
4241            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4242            for (int userId : UserManagerService.getInstance().getUserIds()) {
4243                final int packageCount = mPackages.size();
4244                for (int i = 0; i < packageCount; i++) {
4245                    PackageParser.Package pkg = mPackages.valueAt(i);
4246                    if (!(pkg.mExtras instanceof PackageSetting)) {
4247                        continue;
4248                    }
4249                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4250                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4251                }
4252            }
4253        }
4254    }
4255
4256    @Override
4257    public int getPermissionFlags(String name, String packageName, int userId) {
4258        if (!sUserManager.exists(userId)) {
4259            return 0;
4260        }
4261
4262        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4263
4264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4265                true /* requireFullPermission */, false /* checkShell */,
4266                "getPermissionFlags");
4267
4268        synchronized (mPackages) {
4269            final PackageParser.Package pkg = mPackages.get(packageName);
4270            if (pkg == null) {
4271                return 0;
4272            }
4273
4274            final BasePermission bp = mSettings.mPermissions.get(name);
4275            if (bp == null) {
4276                return 0;
4277            }
4278
4279            SettingBase sb = (SettingBase) pkg.mExtras;
4280            if (sb == null) {
4281                return 0;
4282            }
4283
4284            PermissionsState permissionsState = sb.getPermissionsState();
4285            return permissionsState.getPermissionFlags(name, userId);
4286        }
4287    }
4288
4289    @Override
4290    public void updatePermissionFlags(String name, String packageName, int flagMask,
4291            int flagValues, int userId) {
4292        if (!sUserManager.exists(userId)) {
4293            return;
4294        }
4295
4296        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4297
4298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4299                true /* requireFullPermission */, true /* checkShell */,
4300                "updatePermissionFlags");
4301
4302        // Only the system can change these flags and nothing else.
4303        if (getCallingUid() != Process.SYSTEM_UID) {
4304            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4305            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4306            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4307            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4308            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4309        }
4310
4311        synchronized (mPackages) {
4312            final PackageParser.Package pkg = mPackages.get(packageName);
4313            if (pkg == null) {
4314                throw new IllegalArgumentException("Unknown package: " + packageName);
4315            }
4316
4317            final BasePermission bp = mSettings.mPermissions.get(name);
4318            if (bp == null) {
4319                throw new IllegalArgumentException("Unknown permission: " + name);
4320            }
4321
4322            SettingBase sb = (SettingBase) pkg.mExtras;
4323            if (sb == null) {
4324                throw new IllegalArgumentException("Unknown package: " + packageName);
4325            }
4326
4327            PermissionsState permissionsState = sb.getPermissionsState();
4328
4329            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4330
4331            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4332                // Install and runtime permissions are stored in different places,
4333                // so figure out what permission changed and persist the change.
4334                if (permissionsState.getInstallPermissionState(name) != null) {
4335                    scheduleWriteSettingsLocked();
4336                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4337                        || hadState) {
4338                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4339                }
4340            }
4341        }
4342    }
4343
4344    /**
4345     * Update the permission flags for all packages and runtime permissions of a user in order
4346     * to allow device or profile owner to remove POLICY_FIXED.
4347     */
4348    @Override
4349    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4350        if (!sUserManager.exists(userId)) {
4351            return;
4352        }
4353
4354        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4355
4356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4357                true /* requireFullPermission */, true /* checkShell */,
4358                "updatePermissionFlagsForAllApps");
4359
4360        // Only the system can change system fixed flags.
4361        if (getCallingUid() != Process.SYSTEM_UID) {
4362            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4363            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4364        }
4365
4366        synchronized (mPackages) {
4367            boolean changed = false;
4368            final int packageCount = mPackages.size();
4369            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4370                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4371                SettingBase sb = (SettingBase) pkg.mExtras;
4372                if (sb == null) {
4373                    continue;
4374                }
4375                PermissionsState permissionsState = sb.getPermissionsState();
4376                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4377                        userId, flagMask, flagValues);
4378            }
4379            if (changed) {
4380                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4381            }
4382        }
4383    }
4384
4385    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4386        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4387                != PackageManager.PERMISSION_GRANTED
4388            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4389                != PackageManager.PERMISSION_GRANTED) {
4390            throw new SecurityException(message + " requires "
4391                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4392                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4393        }
4394    }
4395
4396    @Override
4397    public boolean shouldShowRequestPermissionRationale(String permissionName,
4398            String packageName, int userId) {
4399        if (UserHandle.getCallingUserId() != userId) {
4400            mContext.enforceCallingPermission(
4401                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4402                    "canShowRequestPermissionRationale for user " + userId);
4403        }
4404
4405        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4406        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4407            return false;
4408        }
4409
4410        if (checkPermission(permissionName, packageName, userId)
4411                == PackageManager.PERMISSION_GRANTED) {
4412            return false;
4413        }
4414
4415        final int flags;
4416
4417        final long identity = Binder.clearCallingIdentity();
4418        try {
4419            flags = getPermissionFlags(permissionName,
4420                    packageName, userId);
4421        } finally {
4422            Binder.restoreCallingIdentity(identity);
4423        }
4424
4425        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4426                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4427                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4428
4429        if ((flags & fixedFlags) != 0) {
4430            return false;
4431        }
4432
4433        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4434    }
4435
4436    @Override
4437    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4438        mContext.enforceCallingOrSelfPermission(
4439                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4440                "addOnPermissionsChangeListener");
4441
4442        synchronized (mPackages) {
4443            mOnPermissionChangeListeners.addListenerLocked(listener);
4444        }
4445    }
4446
4447    @Override
4448    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4449        synchronized (mPackages) {
4450            mOnPermissionChangeListeners.removeListenerLocked(listener);
4451        }
4452    }
4453
4454    @Override
4455    public boolean isProtectedBroadcast(String actionName) {
4456        synchronized (mPackages) {
4457            if (mProtectedBroadcasts.contains(actionName)) {
4458                return true;
4459            } else if (actionName != null) {
4460                // TODO: remove these terrible hacks
4461                if (actionName.startsWith("android.net.netmon.lingerExpired")
4462                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4463                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4464                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4465                    return true;
4466                }
4467            }
4468        }
4469        return false;
4470    }
4471
4472    @Override
4473    public int checkSignatures(String pkg1, String pkg2) {
4474        synchronized (mPackages) {
4475            final PackageParser.Package p1 = mPackages.get(pkg1);
4476            final PackageParser.Package p2 = mPackages.get(pkg2);
4477            if (p1 == null || p1.mExtras == null
4478                    || p2 == null || p2.mExtras == null) {
4479                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4480            }
4481            return compareSignatures(p1.mSignatures, p2.mSignatures);
4482        }
4483    }
4484
4485    @Override
4486    public int checkUidSignatures(int uid1, int uid2) {
4487        // Map to base uids.
4488        uid1 = UserHandle.getAppId(uid1);
4489        uid2 = UserHandle.getAppId(uid2);
4490        // reader
4491        synchronized (mPackages) {
4492            Signature[] s1;
4493            Signature[] s2;
4494            Object obj = mSettings.getUserIdLPr(uid1);
4495            if (obj != null) {
4496                if (obj instanceof SharedUserSetting) {
4497                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4498                } else if (obj instanceof PackageSetting) {
4499                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4500                } else {
4501                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4502                }
4503            } else {
4504                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4505            }
4506            obj = mSettings.getUserIdLPr(uid2);
4507            if (obj != null) {
4508                if (obj instanceof SharedUserSetting) {
4509                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4510                } else if (obj instanceof PackageSetting) {
4511                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4512                } else {
4513                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4514                }
4515            } else {
4516                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4517            }
4518            return compareSignatures(s1, s2);
4519        }
4520    }
4521
4522    /**
4523     * This method should typically only be used when granting or revoking
4524     * permissions, since the app may immediately restart after this call.
4525     * <p>
4526     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4527     * guard your work against the app being relaunched.
4528     */
4529    private void killUid(int appId, int userId, String reason) {
4530        final long identity = Binder.clearCallingIdentity();
4531        try {
4532            IActivityManager am = ActivityManagerNative.getDefault();
4533            if (am != null) {
4534                try {
4535                    am.killUid(appId, userId, reason);
4536                } catch (RemoteException e) {
4537                    /* ignore - same process */
4538                }
4539            }
4540        } finally {
4541            Binder.restoreCallingIdentity(identity);
4542        }
4543    }
4544
4545    /**
4546     * Compares two sets of signatures. Returns:
4547     * <br />
4548     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4549     * <br />
4550     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4551     * <br />
4552     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4555     * <br />
4556     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4557     */
4558    static int compareSignatures(Signature[] s1, Signature[] s2) {
4559        if (s1 == null) {
4560            return s2 == null
4561                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4562                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4563        }
4564
4565        if (s2 == null) {
4566            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4567        }
4568
4569        if (s1.length != s2.length) {
4570            return PackageManager.SIGNATURE_NO_MATCH;
4571        }
4572
4573        // Since both signature sets are of size 1, we can compare without HashSets.
4574        if (s1.length == 1) {
4575            return s1[0].equals(s2[0]) ?
4576                    PackageManager.SIGNATURE_MATCH :
4577                    PackageManager.SIGNATURE_NO_MATCH;
4578        }
4579
4580        ArraySet<Signature> set1 = new ArraySet<Signature>();
4581        for (Signature sig : s1) {
4582            set1.add(sig);
4583        }
4584        ArraySet<Signature> set2 = new ArraySet<Signature>();
4585        for (Signature sig : s2) {
4586            set2.add(sig);
4587        }
4588        // Make sure s2 contains all signatures in s1.
4589        if (set1.equals(set2)) {
4590            return PackageManager.SIGNATURE_MATCH;
4591        }
4592        return PackageManager.SIGNATURE_NO_MATCH;
4593    }
4594
4595    /**
4596     * If the database version for this type of package (internal storage or
4597     * external storage) is less than the version where package signatures
4598     * were updated, return true.
4599     */
4600    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4601        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4602        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4603    }
4604
4605    /**
4606     * Used for backward compatibility to make sure any packages with
4607     * certificate chains get upgraded to the new style. {@code existingSigs}
4608     * will be in the old format (since they were stored on disk from before the
4609     * system upgrade) and {@code scannedSigs} will be in the newer format.
4610     */
4611    private int compareSignaturesCompat(PackageSignatures existingSigs,
4612            PackageParser.Package scannedPkg) {
4613        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4614            return PackageManager.SIGNATURE_NO_MATCH;
4615        }
4616
4617        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4618        for (Signature sig : existingSigs.mSignatures) {
4619            existingSet.add(sig);
4620        }
4621        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4622        for (Signature sig : scannedPkg.mSignatures) {
4623            try {
4624                Signature[] chainSignatures = sig.getChainSignatures();
4625                for (Signature chainSig : chainSignatures) {
4626                    scannedCompatSet.add(chainSig);
4627                }
4628            } catch (CertificateEncodingException e) {
4629                scannedCompatSet.add(sig);
4630            }
4631        }
4632        /*
4633         * Make sure the expanded scanned set contains all signatures in the
4634         * existing one.
4635         */
4636        if (scannedCompatSet.equals(existingSet)) {
4637            // Migrate the old signatures to the new scheme.
4638            existingSigs.assignSignatures(scannedPkg.mSignatures);
4639            // The new KeySets will be re-added later in the scanning process.
4640            synchronized (mPackages) {
4641                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4642            }
4643            return PackageManager.SIGNATURE_MATCH;
4644        }
4645        return PackageManager.SIGNATURE_NO_MATCH;
4646    }
4647
4648    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4649        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4650        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4651    }
4652
4653    private int compareSignaturesRecover(PackageSignatures existingSigs,
4654            PackageParser.Package scannedPkg) {
4655        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4656            return PackageManager.SIGNATURE_NO_MATCH;
4657        }
4658
4659        String msg = null;
4660        try {
4661            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4662                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4663                        + scannedPkg.packageName);
4664                return PackageManager.SIGNATURE_MATCH;
4665            }
4666        } catch (CertificateException e) {
4667            msg = e.getMessage();
4668        }
4669
4670        logCriticalInfo(Log.INFO,
4671                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4672        return PackageManager.SIGNATURE_NO_MATCH;
4673    }
4674
4675    @Override
4676    public List<String> getAllPackages() {
4677        synchronized (mPackages) {
4678            return new ArrayList<String>(mPackages.keySet());
4679        }
4680    }
4681
4682    @Override
4683    public String[] getPackagesForUid(int uid) {
4684        final int userId = UserHandle.getUserId(uid);
4685        uid = UserHandle.getAppId(uid);
4686        // reader
4687        synchronized (mPackages) {
4688            Object obj = mSettings.getUserIdLPr(uid);
4689            if (obj instanceof SharedUserSetting) {
4690                final SharedUserSetting sus = (SharedUserSetting) obj;
4691                final int N = sus.packages.size();
4692                String[] res = new String[N];
4693                final Iterator<PackageSetting> it = sus.packages.iterator();
4694                int i = 0;
4695                while (it.hasNext()) {
4696                    PackageSetting ps = it.next();
4697                    if (ps.getInstalled(userId)) {
4698                        res[i++] = ps.name;
4699                    } else {
4700                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4701                    }
4702                }
4703                return res;
4704            } else if (obj instanceof PackageSetting) {
4705                final PackageSetting ps = (PackageSetting) obj;
4706                return new String[] { ps.name };
4707            }
4708        }
4709        return null;
4710    }
4711
4712    @Override
4713    public String getNameForUid(int uid) {
4714        // reader
4715        synchronized (mPackages) {
4716            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4717            if (obj instanceof SharedUserSetting) {
4718                final SharedUserSetting sus = (SharedUserSetting) obj;
4719                return sus.name + ":" + sus.userId;
4720            } else if (obj instanceof PackageSetting) {
4721                final PackageSetting ps = (PackageSetting) obj;
4722                return ps.name;
4723            }
4724        }
4725        return null;
4726    }
4727
4728    @Override
4729    public int getUidForSharedUser(String sharedUserName) {
4730        if(sharedUserName == null) {
4731            return -1;
4732        }
4733        // reader
4734        synchronized (mPackages) {
4735            SharedUserSetting suid;
4736            try {
4737                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4738                if (suid != null) {
4739                    return suid.userId;
4740                }
4741            } catch (PackageManagerException ignore) {
4742                // can't happen, but, still need to catch it
4743            }
4744            return -1;
4745        }
4746    }
4747
4748    @Override
4749    public int getFlagsForUid(int uid) {
4750        synchronized (mPackages) {
4751            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4752            if (obj instanceof SharedUserSetting) {
4753                final SharedUserSetting sus = (SharedUserSetting) obj;
4754                return sus.pkgFlags;
4755            } else if (obj instanceof PackageSetting) {
4756                final PackageSetting ps = (PackageSetting) obj;
4757                return ps.pkgFlags;
4758            }
4759        }
4760        return 0;
4761    }
4762
4763    @Override
4764    public int getPrivateFlagsForUid(int uid) {
4765        synchronized (mPackages) {
4766            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4767            if (obj instanceof SharedUserSetting) {
4768                final SharedUserSetting sus = (SharedUserSetting) obj;
4769                return sus.pkgPrivateFlags;
4770            } else if (obj instanceof PackageSetting) {
4771                final PackageSetting ps = (PackageSetting) obj;
4772                return ps.pkgPrivateFlags;
4773            }
4774        }
4775        return 0;
4776    }
4777
4778    @Override
4779    public boolean isUidPrivileged(int uid) {
4780        uid = UserHandle.getAppId(uid);
4781        // reader
4782        synchronized (mPackages) {
4783            Object obj = mSettings.getUserIdLPr(uid);
4784            if (obj instanceof SharedUserSetting) {
4785                final SharedUserSetting sus = (SharedUserSetting) obj;
4786                final Iterator<PackageSetting> it = sus.packages.iterator();
4787                while (it.hasNext()) {
4788                    if (it.next().isPrivileged()) {
4789                        return true;
4790                    }
4791                }
4792            } else if (obj instanceof PackageSetting) {
4793                final PackageSetting ps = (PackageSetting) obj;
4794                return ps.isPrivileged();
4795            }
4796        }
4797        return false;
4798    }
4799
4800    @Override
4801    public String[] getAppOpPermissionPackages(String permissionName) {
4802        synchronized (mPackages) {
4803            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4804            if (pkgs == null) {
4805                return null;
4806            }
4807            return pkgs.toArray(new String[pkgs.size()]);
4808        }
4809    }
4810
4811    @Override
4812    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4813            int flags, int userId) {
4814        try {
4815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4816
4817            if (!sUserManager.exists(userId)) return null;
4818            flags = updateFlagsForResolve(flags, userId, intent);
4819            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4820                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4821
4822            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4823            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4824                    flags, userId);
4825            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4826
4827            final ResolveInfo bestChoice =
4828                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4829            return bestChoice;
4830        } finally {
4831            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4832        }
4833    }
4834
4835    @Override
4836    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4837            IntentFilter filter, int match, ComponentName activity) {
4838        final int userId = UserHandle.getCallingUserId();
4839        if (DEBUG_PREFERRED) {
4840            Log.v(TAG, "setLastChosenActivity intent=" + intent
4841                + " resolvedType=" + resolvedType
4842                + " flags=" + flags
4843                + " filter=" + filter
4844                + " match=" + match
4845                + " activity=" + activity);
4846            filter.dump(new PrintStreamPrinter(System.out), "    ");
4847        }
4848        intent.setComponent(null);
4849        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4850                userId);
4851        // Find any earlier preferred or last chosen entries and nuke them
4852        findPreferredActivity(intent, resolvedType,
4853                flags, query, 0, false, true, false, userId);
4854        // Add the new activity as the last chosen for this filter
4855        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4856                "Setting last chosen");
4857    }
4858
4859    @Override
4860    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4861        final int userId = UserHandle.getCallingUserId();
4862        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4863        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4864                userId);
4865        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4866                false, false, false, userId);
4867    }
4868
4869    private boolean isEphemeralDisabled() {
4870        // ephemeral apps have been disabled across the board
4871        if (DISABLE_EPHEMERAL_APPS) {
4872            return true;
4873        }
4874        // system isn't up yet; can't read settings, so, assume no ephemeral apps
4875        if (!mSystemReady) {
4876            return true;
4877        }
4878        // we can't get a content resolver until the system is ready; these checks must happen last
4879        final ContentResolver resolver = mContext.getContentResolver();
4880        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4881            return true;
4882        }
4883        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4884    }
4885
4886    private boolean isEphemeralAllowed(
4887            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4888            boolean skipPackageCheck) {
4889        // Short circuit and return early if possible.
4890        if (isEphemeralDisabled()) {
4891            return false;
4892        }
4893        final int callingUser = UserHandle.getCallingUserId();
4894        if (callingUser != UserHandle.USER_SYSTEM) {
4895            return false;
4896        }
4897        if (mEphemeralResolverConnection == null) {
4898            return false;
4899        }
4900        if (intent.getComponent() != null) {
4901            return false;
4902        }
4903        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4904            return false;
4905        }
4906        if (!skipPackageCheck && intent.getPackage() != null) {
4907            return false;
4908        }
4909        final boolean isWebUri = hasWebURI(intent);
4910        if (!isWebUri || intent.getData().getHost() == null) {
4911            return false;
4912        }
4913        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4914        synchronized (mPackages) {
4915            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4916            for (int n = 0; n < count; n++) {
4917                ResolveInfo info = resolvedActivities.get(n);
4918                String packageName = info.activityInfo.packageName;
4919                PackageSetting ps = mSettings.mPackages.get(packageName);
4920                if (ps != null) {
4921                    // Try to get the status from User settings first
4922                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4923                    int status = (int) (packedStatus >> 32);
4924                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4925                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4926                        if (DEBUG_EPHEMERAL) {
4927                            Slog.v(TAG, "DENY ephemeral apps;"
4928                                + " pkg: " + packageName + ", status: " + status);
4929                        }
4930                        return false;
4931                    }
4932                }
4933            }
4934        }
4935        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4936        return true;
4937    }
4938
4939    private static EphemeralResolveInfo getEphemeralResolveInfo(
4940            Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4941            String resolvedType, int userId, String packageName) {
4942        final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4943                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4944        final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4945                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4946        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4947                ephemeralPrefixCount);
4948        final int[] shaPrefix = digest.getDigestPrefix();
4949        final byte[][] digestBytes = digest.getDigestBytes();
4950        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4951                resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4952        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4953            // No hash prefix match; there are no ephemeral apps for this domain.
4954            return null;
4955        }
4956
4957        // Go in reverse order so we match the narrowest scope first.
4958        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4959            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4960                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4961                    continue;
4962                }
4963                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4964                // No filters; this should never happen.
4965                if (filters.isEmpty()) {
4966                    continue;
4967                }
4968                if (packageName != null
4969                        && !packageName.equals(ephemeralApplication.getPackageName())) {
4970                    continue;
4971                }
4972                // We have a domain match; resolve the filters to see if anything matches.
4973                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4974                for (int j = filters.size() - 1; j >= 0; --j) {
4975                    final EphemeralResolveIntentInfo intentInfo =
4976                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4977                    ephemeralResolver.addFilter(intentInfo);
4978                }
4979                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4980                        intent, resolvedType, false /*defaultOnly*/, userId);
4981                if (!matchedResolveInfoList.isEmpty()) {
4982                    return matchedResolveInfoList.get(0);
4983                }
4984            }
4985        }
4986        // Hash or filter mis-match; no ephemeral apps for this domain.
4987        return null;
4988    }
4989
4990    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4991            int flags, List<ResolveInfo> query, int userId) {
4992        if (query != null) {
4993            final int N = query.size();
4994            if (N == 1) {
4995                return query.get(0);
4996            } else if (N > 1) {
4997                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4998                // If there is more than one activity with the same priority,
4999                // then let the user decide between them.
5000                ResolveInfo r0 = query.get(0);
5001                ResolveInfo r1 = query.get(1);
5002                if (DEBUG_INTENT_MATCHING || debug) {
5003                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5004                            + r1.activityInfo.name + "=" + r1.priority);
5005                }
5006                // If the first activity has a higher priority, or a different
5007                // default, then it is always desirable to pick it.
5008                if (r0.priority != r1.priority
5009                        || r0.preferredOrder != r1.preferredOrder
5010                        || r0.isDefault != r1.isDefault) {
5011                    return query.get(0);
5012                }
5013                // If we have saved a preference for a preferred activity for
5014                // this Intent, use that.
5015                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5016                        flags, query, r0.priority, true, false, debug, userId);
5017                if (ri != null) {
5018                    return ri;
5019                }
5020                ri = new ResolveInfo(mResolveInfo);
5021                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5022                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5023                // If all of the options come from the same package, show the application's
5024                // label and icon instead of the generic resolver's.
5025                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5026                // and then throw away the ResolveInfo itself, meaning that the caller loses
5027                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5028                // a fallback for this case; we only set the target package's resources on
5029                // the ResolveInfo, not the ActivityInfo.
5030                final String intentPackage = intent.getPackage();
5031                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5032                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5033                    ri.resolvePackageName = intentPackage;
5034                    if (userNeedsBadging(userId)) {
5035                        ri.noResourceId = true;
5036                    } else {
5037                        ri.icon = appi.icon;
5038                    }
5039                    ri.iconResourceId = appi.icon;
5040                    ri.labelRes = appi.labelRes;
5041                }
5042                ri.activityInfo.applicationInfo = new ApplicationInfo(
5043                        ri.activityInfo.applicationInfo);
5044                if (userId != 0) {
5045                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5046                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5047                }
5048                // Make sure that the resolver is displayable in car mode
5049                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5050                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5051                return ri;
5052            }
5053        }
5054        return null;
5055    }
5056
5057    /**
5058     * Return true if the given list is not empty and all of its contents have
5059     * an activityInfo with the given package name.
5060     */
5061    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5062        if (ArrayUtils.isEmpty(list)) {
5063            return false;
5064        }
5065        for (int i = 0, N = list.size(); i < N; i++) {
5066            final ResolveInfo ri = list.get(i);
5067            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5068            if (ai == null || !packageName.equals(ai.packageName)) {
5069                return false;
5070            }
5071        }
5072        return true;
5073    }
5074
5075    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5076            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5077        final int N = query.size();
5078        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5079                .get(userId);
5080        // Get the list of persistent preferred activities that handle the intent
5081        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5082        List<PersistentPreferredActivity> pprefs = ppir != null
5083                ? ppir.queryIntent(intent, resolvedType,
5084                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5085                : null;
5086        if (pprefs != null && pprefs.size() > 0) {
5087            final int M = pprefs.size();
5088            for (int i=0; i<M; i++) {
5089                final PersistentPreferredActivity ppa = pprefs.get(i);
5090                if (DEBUG_PREFERRED || debug) {
5091                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5092                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5093                            + "\n  component=" + ppa.mComponent);
5094                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5095                }
5096                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5097                        flags | MATCH_DISABLED_COMPONENTS, userId);
5098                if (DEBUG_PREFERRED || debug) {
5099                    Slog.v(TAG, "Found persistent preferred activity:");
5100                    if (ai != null) {
5101                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5102                    } else {
5103                        Slog.v(TAG, "  null");
5104                    }
5105                }
5106                if (ai == null) {
5107                    // This previously registered persistent preferred activity
5108                    // component is no longer known. Ignore it and do NOT remove it.
5109                    continue;
5110                }
5111                for (int j=0; j<N; j++) {
5112                    final ResolveInfo ri = query.get(j);
5113                    if (!ri.activityInfo.applicationInfo.packageName
5114                            .equals(ai.applicationInfo.packageName)) {
5115                        continue;
5116                    }
5117                    if (!ri.activityInfo.name.equals(ai.name)) {
5118                        continue;
5119                    }
5120                    //  Found a persistent preference that can handle the intent.
5121                    if (DEBUG_PREFERRED || debug) {
5122                        Slog.v(TAG, "Returning persistent preferred activity: " +
5123                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5124                    }
5125                    return ri;
5126                }
5127            }
5128        }
5129        return null;
5130    }
5131
5132    // TODO: handle preferred activities missing while user has amnesia
5133    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5134            List<ResolveInfo> query, int priority, boolean always,
5135            boolean removeMatches, boolean debug, int userId) {
5136        if (!sUserManager.exists(userId)) return null;
5137        flags = updateFlagsForResolve(flags, userId, intent);
5138        // writer
5139        synchronized (mPackages) {
5140            if (intent.getSelector() != null) {
5141                intent = intent.getSelector();
5142            }
5143            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5144
5145            // Try to find a matching persistent preferred activity.
5146            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5147                    debug, userId);
5148
5149            // If a persistent preferred activity matched, use it.
5150            if (pri != null) {
5151                return pri;
5152            }
5153
5154            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5155            // Get the list of preferred activities that handle the intent
5156            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5157            List<PreferredActivity> prefs = pir != null
5158                    ? pir.queryIntent(intent, resolvedType,
5159                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5160                    : null;
5161            if (prefs != null && prefs.size() > 0) {
5162                boolean changed = false;
5163                try {
5164                    // First figure out how good the original match set is.
5165                    // We will only allow preferred activities that came
5166                    // from the same match quality.
5167                    int match = 0;
5168
5169                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5170
5171                    final int N = query.size();
5172                    for (int j=0; j<N; j++) {
5173                        final ResolveInfo ri = query.get(j);
5174                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5175                                + ": 0x" + Integer.toHexString(match));
5176                        if (ri.match > match) {
5177                            match = ri.match;
5178                        }
5179                    }
5180
5181                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5182                            + Integer.toHexString(match));
5183
5184                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5185                    final int M = prefs.size();
5186                    for (int i=0; i<M; i++) {
5187                        final PreferredActivity pa = prefs.get(i);
5188                        if (DEBUG_PREFERRED || debug) {
5189                            Slog.v(TAG, "Checking PreferredActivity ds="
5190                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5191                                    + "\n  component=" + pa.mPref.mComponent);
5192                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5193                        }
5194                        if (pa.mPref.mMatch != match) {
5195                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5196                                    + Integer.toHexString(pa.mPref.mMatch));
5197                            continue;
5198                        }
5199                        // If it's not an "always" type preferred activity and that's what we're
5200                        // looking for, skip it.
5201                        if (always && !pa.mPref.mAlways) {
5202                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5203                            continue;
5204                        }
5205                        final ActivityInfo ai = getActivityInfo(
5206                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5207                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5208                                userId);
5209                        if (DEBUG_PREFERRED || debug) {
5210                            Slog.v(TAG, "Found preferred activity:");
5211                            if (ai != null) {
5212                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5213                            } else {
5214                                Slog.v(TAG, "  null");
5215                            }
5216                        }
5217                        if (ai == null) {
5218                            // This previously registered preferred activity
5219                            // component is no longer known.  Most likely an update
5220                            // to the app was installed and in the new version this
5221                            // component no longer exists.  Clean it up by removing
5222                            // it from the preferred activities list, and skip it.
5223                            Slog.w(TAG, "Removing dangling preferred activity: "
5224                                    + pa.mPref.mComponent);
5225                            pir.removeFilter(pa);
5226                            changed = true;
5227                            continue;
5228                        }
5229                        for (int j=0; j<N; j++) {
5230                            final ResolveInfo ri = query.get(j);
5231                            if (!ri.activityInfo.applicationInfo.packageName
5232                                    .equals(ai.applicationInfo.packageName)) {
5233                                continue;
5234                            }
5235                            if (!ri.activityInfo.name.equals(ai.name)) {
5236                                continue;
5237                            }
5238
5239                            if (removeMatches) {
5240                                pir.removeFilter(pa);
5241                                changed = true;
5242                                if (DEBUG_PREFERRED) {
5243                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5244                                }
5245                                break;
5246                            }
5247
5248                            // Okay we found a previously set preferred or last chosen app.
5249                            // If the result set is different from when this
5250                            // was created, we need to clear it and re-ask the
5251                            // user their preference, if we're looking for an "always" type entry.
5252                            if (always && !pa.mPref.sameSet(query)) {
5253                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5254                                        + intent + " type " + resolvedType);
5255                                if (DEBUG_PREFERRED) {
5256                                    Slog.v(TAG, "Removing preferred activity since set changed "
5257                                            + pa.mPref.mComponent);
5258                                }
5259                                pir.removeFilter(pa);
5260                                // Re-add the filter as a "last chosen" entry (!always)
5261                                PreferredActivity lastChosen = new PreferredActivity(
5262                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5263                                pir.addFilter(lastChosen);
5264                                changed = true;
5265                                return null;
5266                            }
5267
5268                            // Yay! Either the set matched or we're looking for the last chosen
5269                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5270                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5271                            return ri;
5272                        }
5273                    }
5274                } finally {
5275                    if (changed) {
5276                        if (DEBUG_PREFERRED) {
5277                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5278                        }
5279                        scheduleWritePackageRestrictionsLocked(userId);
5280                    }
5281                }
5282            }
5283        }
5284        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5285        return null;
5286    }
5287
5288    /*
5289     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5290     */
5291    @Override
5292    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5293            int targetUserId) {
5294        mContext.enforceCallingOrSelfPermission(
5295                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5296        List<CrossProfileIntentFilter> matches =
5297                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5298        if (matches != null) {
5299            int size = matches.size();
5300            for (int i = 0; i < size; i++) {
5301                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5302            }
5303        }
5304        if (hasWebURI(intent)) {
5305            // cross-profile app linking works only towards the parent.
5306            final UserInfo parent = getProfileParent(sourceUserId);
5307            synchronized(mPackages) {
5308                int flags = updateFlagsForResolve(0, parent.id, intent);
5309                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5310                        intent, resolvedType, flags, sourceUserId, parent.id);
5311                return xpDomainInfo != null;
5312            }
5313        }
5314        return false;
5315    }
5316
5317    private UserInfo getProfileParent(int userId) {
5318        final long identity = Binder.clearCallingIdentity();
5319        try {
5320            return sUserManager.getProfileParent(userId);
5321        } finally {
5322            Binder.restoreCallingIdentity(identity);
5323        }
5324    }
5325
5326    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5327            String resolvedType, int userId) {
5328        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5329        if (resolver != null) {
5330            return resolver.queryIntent(intent, resolvedType, false, userId);
5331        }
5332        return null;
5333    }
5334
5335    @Override
5336    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5337            String resolvedType, int flags, int userId) {
5338        try {
5339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5340
5341            return new ParceledListSlice<>(
5342                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5343        } finally {
5344            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5345        }
5346    }
5347
5348    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5349            String resolvedType, int flags, int userId) {
5350        if (!sUserManager.exists(userId)) return Collections.emptyList();
5351        flags = updateFlagsForResolve(flags, userId, intent);
5352        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5353                false /* requireFullPermission */, false /* checkShell */,
5354                "query intent activities");
5355        ComponentName comp = intent.getComponent();
5356        if (comp == null) {
5357            if (intent.getSelector() != null) {
5358                intent = intent.getSelector();
5359                comp = intent.getComponent();
5360            }
5361        }
5362
5363        if (comp != null) {
5364            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5365            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5366            if (ai != null) {
5367                final ResolveInfo ri = new ResolveInfo();
5368                ri.activityInfo = ai;
5369                list.add(ri);
5370            }
5371            return list;
5372        }
5373
5374        // reader
5375        boolean sortResult = false;
5376        boolean addEphemeral = false;
5377        boolean matchEphemeralPackage = false;
5378        List<ResolveInfo> result;
5379        final String pkgName = intent.getPackage();
5380        synchronized (mPackages) {
5381            if (pkgName == null) {
5382                List<CrossProfileIntentFilter> matchingFilters =
5383                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5384                // Check for results that need to skip the current profile.
5385                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5386                        resolvedType, flags, userId);
5387                if (xpResolveInfo != null) {
5388                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5389                    xpResult.add(xpResolveInfo);
5390                    return filterIfNotSystemUser(xpResult, userId);
5391                }
5392
5393                // Check for results in the current profile.
5394                result = filterIfNotSystemUser(mActivities.queryIntent(
5395                        intent, resolvedType, flags, userId), userId);
5396                addEphemeral =
5397                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5398
5399                // Check for cross profile results.
5400                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5401                xpResolveInfo = queryCrossProfileIntents(
5402                        matchingFilters, intent, resolvedType, flags, userId,
5403                        hasNonNegativePriorityResult);
5404                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5405                    boolean isVisibleToUser = filterIfNotSystemUser(
5406                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5407                    if (isVisibleToUser) {
5408                        result.add(xpResolveInfo);
5409                        sortResult = true;
5410                    }
5411                }
5412                if (hasWebURI(intent)) {
5413                    CrossProfileDomainInfo xpDomainInfo = null;
5414                    final UserInfo parent = getProfileParent(userId);
5415                    if (parent != null) {
5416                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5417                                flags, userId, parent.id);
5418                    }
5419                    if (xpDomainInfo != null) {
5420                        if (xpResolveInfo != null) {
5421                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5422                            // in the result.
5423                            result.remove(xpResolveInfo);
5424                        }
5425                        if (result.size() == 0 && !addEphemeral) {
5426                            result.add(xpDomainInfo.resolveInfo);
5427                            return result;
5428                        }
5429                    }
5430                    if (result.size() > 1 || addEphemeral) {
5431                        result = filterCandidatesWithDomainPreferredActivitiesLPr(
5432                                intent, flags, result, xpDomainInfo, userId);
5433                        sortResult = true;
5434                    }
5435                }
5436            } else {
5437                final PackageParser.Package pkg = mPackages.get(pkgName);
5438                if (pkg != null) {
5439                    result = filterIfNotSystemUser(
5440                            mActivities.queryIntentForPackage(
5441                                    intent, resolvedType, flags, pkg.activities, userId),
5442                            userId);
5443                } else {
5444                    // the caller wants to resolve for a particular package; however, there
5445                    // were no installed results, so, try to find an ephemeral result
5446                    addEphemeral = isEphemeralAllowed(
5447                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5448                    matchEphemeralPackage = true;
5449                    result = new ArrayList<ResolveInfo>();
5450                }
5451            }
5452        }
5453        if (addEphemeral) {
5454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5455            final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5456                    mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5457                    matchEphemeralPackage ? pkgName : null);
5458            if (ai != null) {
5459                if (DEBUG_EPHEMERAL) {
5460                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5461                }
5462                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5463                ephemeralInstaller.ephemeralResolveInfo = ai;
5464                // make sure this resolver is the default
5465                ephemeralInstaller.isDefault = true;
5466                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5467                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5468                // add a non-generic filter
5469                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5470                ephemeralInstaller.filter.addDataPath(
5471                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5472                result.add(ephemeralInstaller);
5473            }
5474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5475        }
5476        if (sortResult) {
5477            Collections.sort(result, mResolvePrioritySorter);
5478        }
5479        return result;
5480    }
5481
5482    private static class CrossProfileDomainInfo {
5483        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5484        ResolveInfo resolveInfo;
5485        /* Best domain verification status of the activities found in the other profile */
5486        int bestDomainVerificationStatus;
5487    }
5488
5489    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5490            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5491        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5492                sourceUserId)) {
5493            return null;
5494        }
5495        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5496                resolvedType, flags, parentUserId);
5497
5498        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5499            return null;
5500        }
5501        CrossProfileDomainInfo result = null;
5502        int size = resultTargetUser.size();
5503        for (int i = 0; i < size; i++) {
5504            ResolveInfo riTargetUser = resultTargetUser.get(i);
5505            // Intent filter verification is only for filters that specify a host. So don't return
5506            // those that handle all web uris.
5507            if (riTargetUser.handleAllWebDataURI) {
5508                continue;
5509            }
5510            String packageName = riTargetUser.activityInfo.packageName;
5511            PackageSetting ps = mSettings.mPackages.get(packageName);
5512            if (ps == null) {
5513                continue;
5514            }
5515            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5516            int status = (int)(verificationState >> 32);
5517            if (result == null) {
5518                result = new CrossProfileDomainInfo();
5519                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5520                        sourceUserId, parentUserId);
5521                result.bestDomainVerificationStatus = status;
5522            } else {
5523                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5524                        result.bestDomainVerificationStatus);
5525            }
5526        }
5527        // Don't consider matches with status NEVER across profiles.
5528        if (result != null && result.bestDomainVerificationStatus
5529                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5530            return null;
5531        }
5532        return result;
5533    }
5534
5535    /**
5536     * Verification statuses are ordered from the worse to the best, except for
5537     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5538     */
5539    private int bestDomainVerificationStatus(int status1, int status2) {
5540        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5541            return status2;
5542        }
5543        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5544            return status1;
5545        }
5546        return (int) MathUtils.max(status1, status2);
5547    }
5548
5549    private boolean isUserEnabled(int userId) {
5550        long callingId = Binder.clearCallingIdentity();
5551        try {
5552            UserInfo userInfo = sUserManager.getUserInfo(userId);
5553            return userInfo != null && userInfo.isEnabled();
5554        } finally {
5555            Binder.restoreCallingIdentity(callingId);
5556        }
5557    }
5558
5559    /**
5560     * Filter out activities with systemUserOnly flag set, when current user is not System.
5561     *
5562     * @return filtered list
5563     */
5564    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5565        if (userId == UserHandle.USER_SYSTEM) {
5566            return resolveInfos;
5567        }
5568        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5569            ResolveInfo info = resolveInfos.get(i);
5570            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5571                resolveInfos.remove(i);
5572            }
5573        }
5574        return resolveInfos;
5575    }
5576
5577    /**
5578     * @param resolveInfos list of resolve infos in descending priority order
5579     * @return if the list contains a resolve info with non-negative priority
5580     */
5581    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5582        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5583    }
5584
5585    private static boolean hasWebURI(Intent intent) {
5586        if (intent.getData() == null) {
5587            return false;
5588        }
5589        final String scheme = intent.getScheme();
5590        if (TextUtils.isEmpty(scheme)) {
5591            return false;
5592        }
5593        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5594    }
5595
5596    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5597            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5598            int userId) {
5599        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5600
5601        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5602            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5603                    candidates.size());
5604        }
5605
5606        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5607        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5608        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5609        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5610        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5611        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5612
5613        synchronized (mPackages) {
5614            final int count = candidates.size();
5615            // First, try to use linked apps. Partition the candidates into four lists:
5616            // one for the final results, one for the "do not use ever", one for "undefined status"
5617            // and finally one for "browser app type".
5618            for (int n=0; n<count; n++) {
5619                ResolveInfo info = candidates.get(n);
5620                String packageName = info.activityInfo.packageName;
5621                PackageSetting ps = mSettings.mPackages.get(packageName);
5622                if (ps != null) {
5623                    // Add to the special match all list (Browser use case)
5624                    if (info.handleAllWebDataURI) {
5625                        matchAllList.add(info);
5626                        continue;
5627                    }
5628                    // Try to get the status from User settings first
5629                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5630                    int status = (int)(packedStatus >> 32);
5631                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5632                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5633                        if (DEBUG_DOMAIN_VERIFICATION) {
5634                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5635                                    + " : linkgen=" + linkGeneration);
5636                        }
5637                        // Use link-enabled generation as preferredOrder, i.e.
5638                        // prefer newly-enabled over earlier-enabled.
5639                        info.preferredOrder = linkGeneration;
5640                        alwaysList.add(info);
5641                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5642                        if (DEBUG_DOMAIN_VERIFICATION) {
5643                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5644                        }
5645                        neverList.add(info);
5646                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5647                        if (DEBUG_DOMAIN_VERIFICATION) {
5648                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5649                        }
5650                        alwaysAskList.add(info);
5651                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5652                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5653                        if (DEBUG_DOMAIN_VERIFICATION) {
5654                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5655                        }
5656                        undefinedList.add(info);
5657                    }
5658                }
5659            }
5660
5661            // We'll want to include browser possibilities in a few cases
5662            boolean includeBrowser = false;
5663
5664            // First try to add the "always" resolution(s) for the current user, if any
5665            if (alwaysList.size() > 0) {
5666                result.addAll(alwaysList);
5667            } else {
5668                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5669                result.addAll(undefinedList);
5670                // Maybe add one for the other profile.
5671                if (xpDomainInfo != null && (
5672                        xpDomainInfo.bestDomainVerificationStatus
5673                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5674                    result.add(xpDomainInfo.resolveInfo);
5675                }
5676                includeBrowser = true;
5677            }
5678
5679            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5680            // If there were 'always' entries their preferred order has been set, so we also
5681            // back that off to make the alternatives equivalent
5682            if (alwaysAskList.size() > 0) {
5683                for (ResolveInfo i : result) {
5684                    i.preferredOrder = 0;
5685                }
5686                result.addAll(alwaysAskList);
5687                includeBrowser = true;
5688            }
5689
5690            if (includeBrowser) {
5691                // Also add browsers (all of them or only the default one)
5692                if (DEBUG_DOMAIN_VERIFICATION) {
5693                    Slog.v(TAG, "   ...including browsers in candidate set");
5694                }
5695                if ((matchFlags & MATCH_ALL) != 0) {
5696                    result.addAll(matchAllList);
5697                } else {
5698                    // Browser/generic handling case.  If there's a default browser, go straight
5699                    // to that (but only if there is no other higher-priority match).
5700                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5701                    int maxMatchPrio = 0;
5702                    ResolveInfo defaultBrowserMatch = null;
5703                    final int numCandidates = matchAllList.size();
5704                    for (int n = 0; n < numCandidates; n++) {
5705                        ResolveInfo info = matchAllList.get(n);
5706                        // track the highest overall match priority...
5707                        if (info.priority > maxMatchPrio) {
5708                            maxMatchPrio = info.priority;
5709                        }
5710                        // ...and the highest-priority default browser match
5711                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5712                            if (defaultBrowserMatch == null
5713                                    || (defaultBrowserMatch.priority < info.priority)) {
5714                                if (debug) {
5715                                    Slog.v(TAG, "Considering default browser match " + info);
5716                                }
5717                                defaultBrowserMatch = info;
5718                            }
5719                        }
5720                    }
5721                    if (defaultBrowserMatch != null
5722                            && defaultBrowserMatch.priority >= maxMatchPrio
5723                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5724                    {
5725                        if (debug) {
5726                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5727                        }
5728                        result.add(defaultBrowserMatch);
5729                    } else {
5730                        result.addAll(matchAllList);
5731                    }
5732                }
5733
5734                // If there is nothing selected, add all candidates and remove the ones that the user
5735                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5736                if (result.size() == 0) {
5737                    result.addAll(candidates);
5738                    result.removeAll(neverList);
5739                }
5740            }
5741        }
5742        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5743            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5744                    result.size());
5745            for (ResolveInfo info : result) {
5746                Slog.v(TAG, "  + " + info.activityInfo);
5747            }
5748        }
5749        return result;
5750    }
5751
5752    // Returns a packed value as a long:
5753    //
5754    // high 'int'-sized word: link status: undefined/ask/never/always.
5755    // low 'int'-sized word: relative priority among 'always' results.
5756    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5757        long result = ps.getDomainVerificationStatusForUser(userId);
5758        // if none available, get the master status
5759        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5760            if (ps.getIntentFilterVerificationInfo() != null) {
5761                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5762            }
5763        }
5764        return result;
5765    }
5766
5767    private ResolveInfo querySkipCurrentProfileIntents(
5768            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5769            int flags, int sourceUserId) {
5770        if (matchingFilters != null) {
5771            int size = matchingFilters.size();
5772            for (int i = 0; i < size; i ++) {
5773                CrossProfileIntentFilter filter = matchingFilters.get(i);
5774                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5775                    // Checking if there are activities in the target user that can handle the
5776                    // intent.
5777                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5778                            resolvedType, flags, sourceUserId);
5779                    if (resolveInfo != null) {
5780                        return resolveInfo;
5781                    }
5782                }
5783            }
5784        }
5785        return null;
5786    }
5787
5788    // Return matching ResolveInfo in target user if any.
5789    private ResolveInfo queryCrossProfileIntents(
5790            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5791            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5792        if (matchingFilters != null) {
5793            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5794            // match the same intent. For performance reasons, it is better not to
5795            // run queryIntent twice for the same userId
5796            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5797            int size = matchingFilters.size();
5798            for (int i = 0; i < size; i++) {
5799                CrossProfileIntentFilter filter = matchingFilters.get(i);
5800                int targetUserId = filter.getTargetUserId();
5801                boolean skipCurrentProfile =
5802                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5803                boolean skipCurrentProfileIfNoMatchFound =
5804                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5805                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5806                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5807                    // Checking if there are activities in the target user that can handle the
5808                    // intent.
5809                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5810                            resolvedType, flags, sourceUserId);
5811                    if (resolveInfo != null) return resolveInfo;
5812                    alreadyTriedUserIds.put(targetUserId, true);
5813                }
5814            }
5815        }
5816        return null;
5817    }
5818
5819    /**
5820     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5821     * will forward the intent to the filter's target user.
5822     * Otherwise, returns null.
5823     */
5824    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5825            String resolvedType, int flags, int sourceUserId) {
5826        int targetUserId = filter.getTargetUserId();
5827        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5828                resolvedType, flags, targetUserId);
5829        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5830            // If all the matches in the target profile are suspended, return null.
5831            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5832                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5833                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5834                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5835                            targetUserId);
5836                }
5837            }
5838        }
5839        return null;
5840    }
5841
5842    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5843            int sourceUserId, int targetUserId) {
5844        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5845        long ident = Binder.clearCallingIdentity();
5846        boolean targetIsProfile;
5847        try {
5848            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5849        } finally {
5850            Binder.restoreCallingIdentity(ident);
5851        }
5852        String className;
5853        if (targetIsProfile) {
5854            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5855        } else {
5856            className = FORWARD_INTENT_TO_PARENT;
5857        }
5858        ComponentName forwardingActivityComponentName = new ComponentName(
5859                mAndroidApplication.packageName, className);
5860        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5861                sourceUserId);
5862        if (!targetIsProfile) {
5863            forwardingActivityInfo.showUserIcon = targetUserId;
5864            forwardingResolveInfo.noResourceId = true;
5865        }
5866        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5867        forwardingResolveInfo.priority = 0;
5868        forwardingResolveInfo.preferredOrder = 0;
5869        forwardingResolveInfo.match = 0;
5870        forwardingResolveInfo.isDefault = true;
5871        forwardingResolveInfo.filter = filter;
5872        forwardingResolveInfo.targetUserId = targetUserId;
5873        return forwardingResolveInfo;
5874    }
5875
5876    @Override
5877    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5878            Intent[] specifics, String[] specificTypes, Intent intent,
5879            String resolvedType, int flags, int userId) {
5880        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5881                specificTypes, intent, resolvedType, flags, userId));
5882    }
5883
5884    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5885            Intent[] specifics, String[] specificTypes, Intent intent,
5886            String resolvedType, int flags, int userId) {
5887        if (!sUserManager.exists(userId)) return Collections.emptyList();
5888        flags = updateFlagsForResolve(flags, userId, intent);
5889        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5890                false /* requireFullPermission */, false /* checkShell */,
5891                "query intent activity options");
5892        final String resultsAction = intent.getAction();
5893
5894        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5895                | PackageManager.GET_RESOLVED_FILTER, userId);
5896
5897        if (DEBUG_INTENT_MATCHING) {
5898            Log.v(TAG, "Query " + intent + ": " + results);
5899        }
5900
5901        int specificsPos = 0;
5902        int N;
5903
5904        // todo: note that the algorithm used here is O(N^2).  This
5905        // isn't a problem in our current environment, but if we start running
5906        // into situations where we have more than 5 or 10 matches then this
5907        // should probably be changed to something smarter...
5908
5909        // First we go through and resolve each of the specific items
5910        // that were supplied, taking care of removing any corresponding
5911        // duplicate items in the generic resolve list.
5912        if (specifics != null) {
5913            for (int i=0; i<specifics.length; i++) {
5914                final Intent sintent = specifics[i];
5915                if (sintent == null) {
5916                    continue;
5917                }
5918
5919                if (DEBUG_INTENT_MATCHING) {
5920                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5921                }
5922
5923                String action = sintent.getAction();
5924                if (resultsAction != null && resultsAction.equals(action)) {
5925                    // If this action was explicitly requested, then don't
5926                    // remove things that have it.
5927                    action = null;
5928                }
5929
5930                ResolveInfo ri = null;
5931                ActivityInfo ai = null;
5932
5933                ComponentName comp = sintent.getComponent();
5934                if (comp == null) {
5935                    ri = resolveIntent(
5936                        sintent,
5937                        specificTypes != null ? specificTypes[i] : null,
5938                            flags, userId);
5939                    if (ri == null) {
5940                        continue;
5941                    }
5942                    if (ri == mResolveInfo) {
5943                        // ACK!  Must do something better with this.
5944                    }
5945                    ai = ri.activityInfo;
5946                    comp = new ComponentName(ai.applicationInfo.packageName,
5947                            ai.name);
5948                } else {
5949                    ai = getActivityInfo(comp, flags, userId);
5950                    if (ai == null) {
5951                        continue;
5952                    }
5953                }
5954
5955                // Look for any generic query activities that are duplicates
5956                // of this specific one, and remove them from the results.
5957                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5958                N = results.size();
5959                int j;
5960                for (j=specificsPos; j<N; j++) {
5961                    ResolveInfo sri = results.get(j);
5962                    if ((sri.activityInfo.name.equals(comp.getClassName())
5963                            && sri.activityInfo.applicationInfo.packageName.equals(
5964                                    comp.getPackageName()))
5965                        || (action != null && sri.filter.matchAction(action))) {
5966                        results.remove(j);
5967                        if (DEBUG_INTENT_MATCHING) Log.v(
5968                            TAG, "Removing duplicate item from " + j
5969                            + " due to specific " + specificsPos);
5970                        if (ri == null) {
5971                            ri = sri;
5972                        }
5973                        j--;
5974                        N--;
5975                    }
5976                }
5977
5978                // Add this specific item to its proper place.
5979                if (ri == null) {
5980                    ri = new ResolveInfo();
5981                    ri.activityInfo = ai;
5982                }
5983                results.add(specificsPos, ri);
5984                ri.specificIndex = i;
5985                specificsPos++;
5986            }
5987        }
5988
5989        // Now we go through the remaining generic results and remove any
5990        // duplicate actions that are found here.
5991        N = results.size();
5992        for (int i=specificsPos; i<N-1; i++) {
5993            final ResolveInfo rii = results.get(i);
5994            if (rii.filter == null) {
5995                continue;
5996            }
5997
5998            // Iterate over all of the actions of this result's intent
5999            // filter...  typically this should be just one.
6000            final Iterator<String> it = rii.filter.actionsIterator();
6001            if (it == null) {
6002                continue;
6003            }
6004            while (it.hasNext()) {
6005                final String action = it.next();
6006                if (resultsAction != null && resultsAction.equals(action)) {
6007                    // If this action was explicitly requested, then don't
6008                    // remove things that have it.
6009                    continue;
6010                }
6011                for (int j=i+1; j<N; j++) {
6012                    final ResolveInfo rij = results.get(j);
6013                    if (rij.filter != null && rij.filter.hasAction(action)) {
6014                        results.remove(j);
6015                        if (DEBUG_INTENT_MATCHING) Log.v(
6016                            TAG, "Removing duplicate item from " + j
6017                            + " due to action " + action + " at " + i);
6018                        j--;
6019                        N--;
6020                    }
6021                }
6022            }
6023
6024            // If the caller didn't request filter information, drop it now
6025            // so we don't have to marshall/unmarshall it.
6026            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6027                rii.filter = null;
6028            }
6029        }
6030
6031        // Filter out the caller activity if so requested.
6032        if (caller != null) {
6033            N = results.size();
6034            for (int i=0; i<N; i++) {
6035                ActivityInfo ainfo = results.get(i).activityInfo;
6036                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6037                        && caller.getClassName().equals(ainfo.name)) {
6038                    results.remove(i);
6039                    break;
6040                }
6041            }
6042        }
6043
6044        // If the caller didn't request filter information,
6045        // drop them now so we don't have to
6046        // marshall/unmarshall it.
6047        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6048            N = results.size();
6049            for (int i=0; i<N; i++) {
6050                results.get(i).filter = null;
6051            }
6052        }
6053
6054        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6055        return results;
6056    }
6057
6058    @Override
6059    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6060            String resolvedType, int flags, int userId) {
6061        return new ParceledListSlice<>(
6062                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6063    }
6064
6065    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        if (!sUserManager.exists(userId)) return Collections.emptyList();
6068        flags = updateFlagsForResolve(flags, userId, intent);
6069        ComponentName comp = intent.getComponent();
6070        if (comp == null) {
6071            if (intent.getSelector() != null) {
6072                intent = intent.getSelector();
6073                comp = intent.getComponent();
6074            }
6075        }
6076        if (comp != null) {
6077            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6078            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6079            if (ai != null) {
6080                ResolveInfo ri = new ResolveInfo();
6081                ri.activityInfo = ai;
6082                list.add(ri);
6083            }
6084            return list;
6085        }
6086
6087        // reader
6088        synchronized (mPackages) {
6089            String pkgName = intent.getPackage();
6090            if (pkgName == null) {
6091                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6092            }
6093            final PackageParser.Package pkg = mPackages.get(pkgName);
6094            if (pkg != null) {
6095                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6096                        userId);
6097            }
6098            return Collections.emptyList();
6099        }
6100    }
6101
6102    @Override
6103    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6104        if (!sUserManager.exists(userId)) return null;
6105        flags = updateFlagsForResolve(flags, userId, intent);
6106        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6107        if (query != null) {
6108            if (query.size() >= 1) {
6109                // If there is more than one service with the same priority,
6110                // just arbitrarily pick the first one.
6111                return query.get(0);
6112            }
6113        }
6114        return null;
6115    }
6116
6117    @Override
6118    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6119            String resolvedType, int flags, int userId) {
6120        return new ParceledListSlice<>(
6121                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6122    }
6123
6124    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        if (!sUserManager.exists(userId)) return Collections.emptyList();
6127        flags = updateFlagsForResolve(flags, userId, intent);
6128        ComponentName comp = intent.getComponent();
6129        if (comp == null) {
6130            if (intent.getSelector() != null) {
6131                intent = intent.getSelector();
6132                comp = intent.getComponent();
6133            }
6134        }
6135        if (comp != null) {
6136            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6137            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6138            if (si != null) {
6139                final ResolveInfo ri = new ResolveInfo();
6140                ri.serviceInfo = si;
6141                list.add(ri);
6142            }
6143            return list;
6144        }
6145
6146        // reader
6147        synchronized (mPackages) {
6148            String pkgName = intent.getPackage();
6149            if (pkgName == null) {
6150                return mServices.queryIntent(intent, resolvedType, flags, userId);
6151            }
6152            final PackageParser.Package pkg = mPackages.get(pkgName);
6153            if (pkg != null) {
6154                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6155                        userId);
6156            }
6157            return Collections.emptyList();
6158        }
6159    }
6160
6161    @Override
6162    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6163            String resolvedType, int flags, int userId) {
6164        return new ParceledListSlice<>(
6165                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6166    }
6167
6168    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6169            Intent intent, String resolvedType, int flags, int userId) {
6170        if (!sUserManager.exists(userId)) return Collections.emptyList();
6171        flags = updateFlagsForResolve(flags, userId, intent);
6172        ComponentName comp = intent.getComponent();
6173        if (comp == null) {
6174            if (intent.getSelector() != null) {
6175                intent = intent.getSelector();
6176                comp = intent.getComponent();
6177            }
6178        }
6179        if (comp != null) {
6180            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6181            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6182            if (pi != null) {
6183                final ResolveInfo ri = new ResolveInfo();
6184                ri.providerInfo = pi;
6185                list.add(ri);
6186            }
6187            return list;
6188        }
6189
6190        // reader
6191        synchronized (mPackages) {
6192            String pkgName = intent.getPackage();
6193            if (pkgName == null) {
6194                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6195            }
6196            final PackageParser.Package pkg = mPackages.get(pkgName);
6197            if (pkg != null) {
6198                return mProviders.queryIntentForPackage(
6199                        intent, resolvedType, flags, pkg.providers, userId);
6200            }
6201            return Collections.emptyList();
6202        }
6203    }
6204
6205    @Override
6206    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6207        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6208        flags = updateFlagsForPackage(flags, userId, null);
6209        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6210        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6211                true /* requireFullPermission */, false /* checkShell */,
6212                "get installed packages");
6213
6214        // writer
6215        synchronized (mPackages) {
6216            ArrayList<PackageInfo> list;
6217            if (listUninstalled) {
6218                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6219                for (PackageSetting ps : mSettings.mPackages.values()) {
6220                    final PackageInfo pi;
6221                    if (ps.pkg != null) {
6222                        pi = generatePackageInfo(ps, flags, userId);
6223                    } else {
6224                        pi = generatePackageInfo(ps, flags, userId);
6225                    }
6226                    if (pi != null) {
6227                        list.add(pi);
6228                    }
6229                }
6230            } else {
6231                list = new ArrayList<PackageInfo>(mPackages.size());
6232                for (PackageParser.Package p : mPackages.values()) {
6233                    final PackageInfo pi =
6234                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6235                    if (pi != null) {
6236                        list.add(pi);
6237                    }
6238                }
6239            }
6240
6241            return new ParceledListSlice<PackageInfo>(list);
6242        }
6243    }
6244
6245    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6246            String[] permissions, boolean[] tmp, int flags, int userId) {
6247        int numMatch = 0;
6248        final PermissionsState permissionsState = ps.getPermissionsState();
6249        for (int i=0; i<permissions.length; i++) {
6250            final String permission = permissions[i];
6251            if (permissionsState.hasPermission(permission, userId)) {
6252                tmp[i] = true;
6253                numMatch++;
6254            } else {
6255                tmp[i] = false;
6256            }
6257        }
6258        if (numMatch == 0) {
6259            return;
6260        }
6261        final PackageInfo pi;
6262        if (ps.pkg != null) {
6263            pi = generatePackageInfo(ps, flags, userId);
6264        } else {
6265            pi = generatePackageInfo(ps, flags, userId);
6266        }
6267        // The above might return null in cases of uninstalled apps or install-state
6268        // skew across users/profiles.
6269        if (pi != null) {
6270            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6271                if (numMatch == permissions.length) {
6272                    pi.requestedPermissions = permissions;
6273                } else {
6274                    pi.requestedPermissions = new String[numMatch];
6275                    numMatch = 0;
6276                    for (int i=0; i<permissions.length; i++) {
6277                        if (tmp[i]) {
6278                            pi.requestedPermissions[numMatch] = permissions[i];
6279                            numMatch++;
6280                        }
6281                    }
6282                }
6283            }
6284            list.add(pi);
6285        }
6286    }
6287
6288    @Override
6289    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6290            String[] permissions, int flags, int userId) {
6291        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6292        flags = updateFlagsForPackage(flags, userId, permissions);
6293        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6294
6295        // writer
6296        synchronized (mPackages) {
6297            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6298            boolean[] tmpBools = new boolean[permissions.length];
6299            if (listUninstalled) {
6300                for (PackageSetting ps : mSettings.mPackages.values()) {
6301                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6302                }
6303            } else {
6304                for (PackageParser.Package pkg : mPackages.values()) {
6305                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6306                    if (ps != null) {
6307                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6308                                userId);
6309                    }
6310                }
6311            }
6312
6313            return new ParceledListSlice<PackageInfo>(list);
6314        }
6315    }
6316
6317    @Override
6318    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6319        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6320        flags = updateFlagsForApplication(flags, userId, null);
6321        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6322
6323        // writer
6324        synchronized (mPackages) {
6325            ArrayList<ApplicationInfo> list;
6326            if (listUninstalled) {
6327                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6328                for (PackageSetting ps : mSettings.mPackages.values()) {
6329                    ApplicationInfo ai;
6330                    if (ps.pkg != null) {
6331                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6332                                ps.readUserState(userId), userId);
6333                    } else {
6334                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6335                    }
6336                    if (ai != null) {
6337                        list.add(ai);
6338                    }
6339                }
6340            } else {
6341                list = new ArrayList<ApplicationInfo>(mPackages.size());
6342                for (PackageParser.Package p : mPackages.values()) {
6343                    if (p.mExtras != null) {
6344                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6345                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6346                        if (ai != null) {
6347                            list.add(ai);
6348                        }
6349                    }
6350                }
6351            }
6352
6353            return new ParceledListSlice<ApplicationInfo>(list);
6354        }
6355    }
6356
6357    @Override
6358    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6359        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6360            return null;
6361        }
6362
6363        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6364                "getEphemeralApplications");
6365        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6366                true /* requireFullPermission */, false /* checkShell */,
6367                "getEphemeralApplications");
6368        synchronized (mPackages) {
6369            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6370                    .getEphemeralApplicationsLPw(userId);
6371            if (ephemeralApps != null) {
6372                return new ParceledListSlice<>(ephemeralApps);
6373            }
6374        }
6375        return null;
6376    }
6377
6378    @Override
6379    public boolean isEphemeralApplication(String packageName, int userId) {
6380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6381                true /* requireFullPermission */, false /* checkShell */,
6382                "isEphemeral");
6383        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6384            return false;
6385        }
6386
6387        if (!isCallerSameApp(packageName)) {
6388            return false;
6389        }
6390        synchronized (mPackages) {
6391            PackageParser.Package pkg = mPackages.get(packageName);
6392            if (pkg != null) {
6393                return pkg.applicationInfo.isEphemeralApp();
6394            }
6395        }
6396        return false;
6397    }
6398
6399    @Override
6400    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6401        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6402            return null;
6403        }
6404
6405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6406                true /* requireFullPermission */, false /* checkShell */,
6407                "getCookie");
6408        if (!isCallerSameApp(packageName)) {
6409            return null;
6410        }
6411        synchronized (mPackages) {
6412            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6413                    packageName, userId);
6414        }
6415    }
6416
6417    @Override
6418    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6419        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6420            return true;
6421        }
6422
6423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6424                true /* requireFullPermission */, true /* checkShell */,
6425                "setCookie");
6426        if (!isCallerSameApp(packageName)) {
6427            return false;
6428        }
6429        synchronized (mPackages) {
6430            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6431                    packageName, cookie, userId);
6432        }
6433    }
6434
6435    @Override
6436    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6437        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6438            return null;
6439        }
6440
6441        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6442                "getEphemeralApplicationIcon");
6443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6444                true /* requireFullPermission */, false /* checkShell */,
6445                "getEphemeralApplicationIcon");
6446        synchronized (mPackages) {
6447            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6448                    packageName, userId);
6449        }
6450    }
6451
6452    private boolean isCallerSameApp(String packageName) {
6453        PackageParser.Package pkg = mPackages.get(packageName);
6454        return pkg != null
6455                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6456    }
6457
6458    @Override
6459    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6460        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6461    }
6462
6463    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6464        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6465
6466        // reader
6467        synchronized (mPackages) {
6468            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6469            final int userId = UserHandle.getCallingUserId();
6470            while (i.hasNext()) {
6471                final PackageParser.Package p = i.next();
6472                if (p.applicationInfo == null) continue;
6473
6474                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6475                        && !p.applicationInfo.isDirectBootAware();
6476                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6477                        && p.applicationInfo.isDirectBootAware();
6478
6479                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6480                        && (!mSafeMode || isSystemApp(p))
6481                        && (matchesUnaware || matchesAware)) {
6482                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6483                    if (ps != null) {
6484                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6485                                ps.readUserState(userId), userId);
6486                        if (ai != null) {
6487                            finalList.add(ai);
6488                        }
6489                    }
6490                }
6491            }
6492        }
6493
6494        return finalList;
6495    }
6496
6497    @Override
6498    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6499        if (!sUserManager.exists(userId)) return null;
6500        flags = updateFlagsForComponent(flags, userId, name);
6501        // reader
6502        synchronized (mPackages) {
6503            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6504            PackageSetting ps = provider != null
6505                    ? mSettings.mPackages.get(provider.owner.packageName)
6506                    : null;
6507            return ps != null
6508                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6509                    ? PackageParser.generateProviderInfo(provider, flags,
6510                            ps.readUserState(userId), userId)
6511                    : null;
6512        }
6513    }
6514
6515    /**
6516     * @deprecated
6517     */
6518    @Deprecated
6519    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6520        // reader
6521        synchronized (mPackages) {
6522            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6523                    .entrySet().iterator();
6524            final int userId = UserHandle.getCallingUserId();
6525            while (i.hasNext()) {
6526                Map.Entry<String, PackageParser.Provider> entry = i.next();
6527                PackageParser.Provider p = entry.getValue();
6528                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6529
6530                if (ps != null && p.syncable
6531                        && (!mSafeMode || (p.info.applicationInfo.flags
6532                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6533                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6534                            ps.readUserState(userId), userId);
6535                    if (info != null) {
6536                        outNames.add(entry.getKey());
6537                        outInfo.add(info);
6538                    }
6539                }
6540            }
6541        }
6542    }
6543
6544    @Override
6545    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6546            int uid, int flags) {
6547        final int userId = processName != null ? UserHandle.getUserId(uid)
6548                : UserHandle.getCallingUserId();
6549        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6550        flags = updateFlagsForComponent(flags, userId, processName);
6551
6552        ArrayList<ProviderInfo> finalList = null;
6553        // reader
6554        synchronized (mPackages) {
6555            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6556            while (i.hasNext()) {
6557                final PackageParser.Provider p = i.next();
6558                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6559                if (ps != null && p.info.authority != null
6560                        && (processName == null
6561                                || (p.info.processName.equals(processName)
6562                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6563                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6564                    if (finalList == null) {
6565                        finalList = new ArrayList<ProviderInfo>(3);
6566                    }
6567                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6568                            ps.readUserState(userId), userId);
6569                    if (info != null) {
6570                        finalList.add(info);
6571                    }
6572                }
6573            }
6574        }
6575
6576        if (finalList != null) {
6577            Collections.sort(finalList, mProviderInitOrderSorter);
6578            return new ParceledListSlice<ProviderInfo>(finalList);
6579        }
6580
6581        return ParceledListSlice.emptyList();
6582    }
6583
6584    @Override
6585    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6586        // reader
6587        synchronized (mPackages) {
6588            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6589            return PackageParser.generateInstrumentationInfo(i, flags);
6590        }
6591    }
6592
6593    @Override
6594    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6595            String targetPackage, int flags) {
6596        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6597    }
6598
6599    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6600            int flags) {
6601        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6602
6603        // reader
6604        synchronized (mPackages) {
6605            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6606            while (i.hasNext()) {
6607                final PackageParser.Instrumentation p = i.next();
6608                if (targetPackage == null
6609                        || targetPackage.equals(p.info.targetPackage)) {
6610                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6611                            flags);
6612                    if (ii != null) {
6613                        finalList.add(ii);
6614                    }
6615                }
6616            }
6617        }
6618
6619        return finalList;
6620    }
6621
6622    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6623        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6624        if (overlays == null) {
6625            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6626            return;
6627        }
6628        for (PackageParser.Package opkg : overlays.values()) {
6629            // Not much to do if idmap fails: we already logged the error
6630            // and we certainly don't want to abort installation of pkg simply
6631            // because an overlay didn't fit properly. For these reasons,
6632            // ignore the return value of createIdmapForPackagePairLI.
6633            createIdmapForPackagePairLI(pkg, opkg);
6634        }
6635    }
6636
6637    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6638            PackageParser.Package opkg) {
6639        if (!opkg.mTrustedOverlay) {
6640            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6641                    opkg.baseCodePath + ": overlay not trusted");
6642            return false;
6643        }
6644        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6645        if (overlaySet == null) {
6646            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6647                    opkg.baseCodePath + " but target package has no known overlays");
6648            return false;
6649        }
6650        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6651        // TODO: generate idmap for split APKs
6652        try {
6653            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6654        } catch (InstallerException e) {
6655            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6656                    + opkg.baseCodePath);
6657            return false;
6658        }
6659        PackageParser.Package[] overlayArray =
6660            overlaySet.values().toArray(new PackageParser.Package[0]);
6661        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6662            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6663                return p1.mOverlayPriority - p2.mOverlayPriority;
6664            }
6665        };
6666        Arrays.sort(overlayArray, cmp);
6667
6668        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6669        int i = 0;
6670        for (PackageParser.Package p : overlayArray) {
6671            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6672        }
6673        return true;
6674    }
6675
6676    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6677        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6678        try {
6679            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6680        } finally {
6681            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6682        }
6683    }
6684
6685    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6686        final File[] files = dir.listFiles();
6687        if (ArrayUtils.isEmpty(files)) {
6688            Log.d(TAG, "No files in app dir " + dir);
6689            return;
6690        }
6691
6692        if (DEBUG_PACKAGE_SCANNING) {
6693            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6694                    + " flags=0x" + Integer.toHexString(parseFlags));
6695        }
6696
6697        for (File file : files) {
6698            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6699                    && !PackageInstallerService.isStageName(file.getName());
6700            if (!isPackage) {
6701                // Ignore entries which are not packages
6702                continue;
6703            }
6704            try {
6705                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6706                        scanFlags, currentTime, null);
6707            } catch (PackageManagerException e) {
6708                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6709
6710                // Delete invalid userdata apps
6711                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6712                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6713                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6714                    removeCodePathLI(file);
6715                }
6716            }
6717        }
6718    }
6719
6720    private static File getSettingsProblemFile() {
6721        File dataDir = Environment.getDataDirectory();
6722        File systemDir = new File(dataDir, "system");
6723        File fname = new File(systemDir, "uiderrors.txt");
6724        return fname;
6725    }
6726
6727    static void reportSettingsProblem(int priority, String msg) {
6728        logCriticalInfo(priority, msg);
6729    }
6730
6731    static void logCriticalInfo(int priority, String msg) {
6732        Slog.println(priority, TAG, msg);
6733        EventLogTags.writePmCriticalInfo(msg);
6734        try {
6735            File fname = getSettingsProblemFile();
6736            FileOutputStream out = new FileOutputStream(fname, true);
6737            PrintWriter pw = new FastPrintWriter(out);
6738            SimpleDateFormat formatter = new SimpleDateFormat();
6739            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6740            pw.println(dateString + ": " + msg);
6741            pw.close();
6742            FileUtils.setPermissions(
6743                    fname.toString(),
6744                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6745                    -1, -1);
6746        } catch (java.io.IOException e) {
6747        }
6748    }
6749
6750    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6751        if (srcFile.isDirectory()) {
6752            final File baseFile = new File(pkg.baseCodePath);
6753            long maxModifiedTime = baseFile.lastModified();
6754            if (pkg.splitCodePaths != null) {
6755                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6756                    final File splitFile = new File(pkg.splitCodePaths[i]);
6757                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6758                }
6759            }
6760            return maxModifiedTime;
6761        }
6762        return srcFile.lastModified();
6763    }
6764
6765    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6766            final int policyFlags) throws PackageManagerException {
6767        // When upgrading from pre-N MR1, verify the package time stamp using the package
6768        // directory and not the APK file.
6769        final long lastModifiedTime = mIsPreNMR1Upgrade
6770                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6771        if (ps != null
6772                && ps.codePath.equals(srcFile)
6773                && ps.timeStamp == lastModifiedTime
6774                && !isCompatSignatureUpdateNeeded(pkg)
6775                && !isRecoverSignatureUpdateNeeded(pkg)) {
6776            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6777            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6778            ArraySet<PublicKey> signingKs;
6779            synchronized (mPackages) {
6780                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6781            }
6782            if (ps.signatures.mSignatures != null
6783                    && ps.signatures.mSignatures.length != 0
6784                    && signingKs != null) {
6785                // Optimization: reuse the existing cached certificates
6786                // if the package appears to be unchanged.
6787                pkg.mSignatures = ps.signatures.mSignatures;
6788                pkg.mSigningKeys = signingKs;
6789                return;
6790            }
6791
6792            Slog.w(TAG, "PackageSetting for " + ps.name
6793                    + " is missing signatures.  Collecting certs again to recover them.");
6794        } else {
6795            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6796        }
6797
6798        try {
6799            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6800            PackageParser.collectCertificates(pkg, policyFlags);
6801        } catch (PackageParserException e) {
6802            throw PackageManagerException.from(e);
6803        } finally {
6804            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6805        }
6806    }
6807
6808    /**
6809     *  Traces a package scan.
6810     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6811     */
6812    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6813            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6814        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6815        try {
6816            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6817        } finally {
6818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6819        }
6820    }
6821
6822    /**
6823     *  Scans a package and returns the newly parsed package.
6824     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6825     */
6826    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6827            long currentTime, UserHandle user) throws PackageManagerException {
6828        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6829        PackageParser pp = new PackageParser();
6830        pp.setSeparateProcesses(mSeparateProcesses);
6831        pp.setOnlyCoreApps(mOnlyCore);
6832        pp.setDisplayMetrics(mMetrics);
6833
6834        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6835            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6836        }
6837
6838        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6839        final PackageParser.Package pkg;
6840        try {
6841            pkg = pp.parsePackage(scanFile, parseFlags);
6842        } catch (PackageParserException e) {
6843            throw PackageManagerException.from(e);
6844        } finally {
6845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6846        }
6847
6848        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6849    }
6850
6851    /**
6852     *  Scans a package and returns the newly parsed package.
6853     *  @throws PackageManagerException on a parse error.
6854     */
6855    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6856            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6857            throws PackageManagerException {
6858        // If the package has children and this is the first dive in the function
6859        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6860        // packages (parent and children) would be successfully scanned before the
6861        // actual scan since scanning mutates internal state and we want to atomically
6862        // install the package and its children.
6863        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6864            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6865                scanFlags |= SCAN_CHECK_ONLY;
6866            }
6867        } else {
6868            scanFlags &= ~SCAN_CHECK_ONLY;
6869        }
6870
6871        // Scan the parent
6872        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6873                scanFlags, currentTime, user);
6874
6875        // Scan the children
6876        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6877        for (int i = 0; i < childCount; i++) {
6878            PackageParser.Package childPackage = pkg.childPackages.get(i);
6879            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6880                    currentTime, user);
6881        }
6882
6883
6884        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6885            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6886        }
6887
6888        return scannedPkg;
6889    }
6890
6891    /**
6892     *  Scans a package and returns the newly parsed package.
6893     *  @throws PackageManagerException on a parse error.
6894     */
6895    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6896            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6897            throws PackageManagerException {
6898        PackageSetting ps = null;
6899        PackageSetting updatedPkg;
6900        // reader
6901        synchronized (mPackages) {
6902            // Look to see if we already know about this package.
6903            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
6904            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6905                // This package has been renamed to its original name.  Let's
6906                // use that.
6907                ps = mSettings.getPackageLPr(oldName);
6908            }
6909            // If there was no original package, see one for the real package name.
6910            if (ps == null) {
6911                ps = mSettings.getPackageLPr(pkg.packageName);
6912            }
6913            // Check to see if this package could be hiding/updating a system
6914            // package.  Must look for it either under the original or real
6915            // package name depending on our state.
6916            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6917            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6918
6919            // If this is a package we don't know about on the system partition, we
6920            // may need to remove disabled child packages on the system partition
6921            // or may need to not add child packages if the parent apk is updated
6922            // on the data partition and no longer defines this child package.
6923            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6924                // If this is a parent package for an updated system app and this system
6925                // app got an OTA update which no longer defines some of the child packages
6926                // we have to prune them from the disabled system packages.
6927                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6928                if (disabledPs != null) {
6929                    final int scannedChildCount = (pkg.childPackages != null)
6930                            ? pkg.childPackages.size() : 0;
6931                    final int disabledChildCount = disabledPs.childPackageNames != null
6932                            ? disabledPs.childPackageNames.size() : 0;
6933                    for (int i = 0; i < disabledChildCount; i++) {
6934                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6935                        boolean disabledPackageAvailable = false;
6936                        for (int j = 0; j < scannedChildCount; j++) {
6937                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6938                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6939                                disabledPackageAvailable = true;
6940                                break;
6941                            }
6942                         }
6943                         if (!disabledPackageAvailable) {
6944                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6945                         }
6946                    }
6947                }
6948            }
6949        }
6950
6951        boolean updatedPkgBetter = false;
6952        // First check if this is a system package that may involve an update
6953        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6954            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6955            // it needs to drop FLAG_PRIVILEGED.
6956            if (locationIsPrivileged(scanFile)) {
6957                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6958            } else {
6959                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6960            }
6961
6962            if (ps != null && !ps.codePath.equals(scanFile)) {
6963                // The path has changed from what was last scanned...  check the
6964                // version of the new path against what we have stored to determine
6965                // what to do.
6966                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6967                if (pkg.mVersionCode <= ps.versionCode) {
6968                    // The system package has been updated and the code path does not match
6969                    // Ignore entry. Skip it.
6970                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6971                            + " ignored: updated version " + ps.versionCode
6972                            + " better than this " + pkg.mVersionCode);
6973                    if (!updatedPkg.codePath.equals(scanFile)) {
6974                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6975                                + ps.name + " changing from " + updatedPkg.codePathString
6976                                + " to " + scanFile);
6977                        updatedPkg.codePath = scanFile;
6978                        updatedPkg.codePathString = scanFile.toString();
6979                        updatedPkg.resourcePath = scanFile;
6980                        updatedPkg.resourcePathString = scanFile.toString();
6981                    }
6982                    updatedPkg.pkg = pkg;
6983                    updatedPkg.versionCode = pkg.mVersionCode;
6984
6985                    // Update the disabled system child packages to point to the package too.
6986                    final int childCount = updatedPkg.childPackageNames != null
6987                            ? updatedPkg.childPackageNames.size() : 0;
6988                    for (int i = 0; i < childCount; i++) {
6989                        String childPackageName = updatedPkg.childPackageNames.get(i);
6990                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6991                                childPackageName);
6992                        if (updatedChildPkg != null) {
6993                            updatedChildPkg.pkg = pkg;
6994                            updatedChildPkg.versionCode = pkg.mVersionCode;
6995                        }
6996                    }
6997
6998                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6999                            + scanFile + " ignored: updated version " + ps.versionCode
7000                            + " better than this " + pkg.mVersionCode);
7001                } else {
7002                    // The current app on the system partition is better than
7003                    // what we have updated to on the data partition; switch
7004                    // back to the system partition version.
7005                    // At this point, its safely assumed that package installation for
7006                    // apps in system partition will go through. If not there won't be a working
7007                    // version of the app
7008                    // writer
7009                    synchronized (mPackages) {
7010                        // Just remove the loaded entries from package lists.
7011                        mPackages.remove(ps.name);
7012                    }
7013
7014                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7015                            + " reverting from " + ps.codePathString
7016                            + ": new version " + pkg.mVersionCode
7017                            + " better than installed " + ps.versionCode);
7018
7019                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7020                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7021                    synchronized (mInstallLock) {
7022                        args.cleanUpResourcesLI();
7023                    }
7024                    synchronized (mPackages) {
7025                        mSettings.enableSystemPackageLPw(ps.name);
7026                    }
7027                    updatedPkgBetter = true;
7028                }
7029            }
7030        }
7031
7032        if (updatedPkg != null) {
7033            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7034            // initially
7035            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7036
7037            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7038            // flag set initially
7039            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7040                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7041            }
7042        }
7043
7044        // Verify certificates against what was last scanned
7045        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7046
7047        /*
7048         * A new system app appeared, but we already had a non-system one of the
7049         * same name installed earlier.
7050         */
7051        boolean shouldHideSystemApp = false;
7052        if (updatedPkg == null && ps != null
7053                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7054            /*
7055             * Check to make sure the signatures match first. If they don't,
7056             * wipe the installed application and its data.
7057             */
7058            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7059                    != PackageManager.SIGNATURE_MATCH) {
7060                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7061                        + " signatures don't match existing userdata copy; removing");
7062                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7063                        "scanPackageInternalLI")) {
7064                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7065                }
7066                ps = null;
7067            } else {
7068                /*
7069                 * If the newly-added system app is an older version than the
7070                 * already installed version, hide it. It will be scanned later
7071                 * and re-added like an update.
7072                 */
7073                if (pkg.mVersionCode <= ps.versionCode) {
7074                    shouldHideSystemApp = true;
7075                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7076                            + " but new version " + pkg.mVersionCode + " better than installed "
7077                            + ps.versionCode + "; hiding system");
7078                } else {
7079                    /*
7080                     * The newly found system app is a newer version that the
7081                     * one previously installed. Simply remove the
7082                     * already-installed application and replace it with our own
7083                     * while keeping the application data.
7084                     */
7085                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7086                            + " reverting from " + ps.codePathString + ": new version "
7087                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7088                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7089                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7090                    synchronized (mInstallLock) {
7091                        args.cleanUpResourcesLI();
7092                    }
7093                }
7094            }
7095        }
7096
7097        // The apk is forward locked (not public) if its code and resources
7098        // are kept in different files. (except for app in either system or
7099        // vendor path).
7100        // TODO grab this value from PackageSettings
7101        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7102            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7103                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7104            }
7105        }
7106
7107        // TODO: extend to support forward-locked splits
7108        String resourcePath = null;
7109        String baseResourcePath = null;
7110        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7111            if (ps != null && ps.resourcePathString != null) {
7112                resourcePath = ps.resourcePathString;
7113                baseResourcePath = ps.resourcePathString;
7114            } else {
7115                // Should not happen at all. Just log an error.
7116                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7117            }
7118        } else {
7119            resourcePath = pkg.codePath;
7120            baseResourcePath = pkg.baseCodePath;
7121        }
7122
7123        // Set application objects path explicitly.
7124        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7125        pkg.setApplicationInfoCodePath(pkg.codePath);
7126        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7127        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7128        pkg.setApplicationInfoResourcePath(resourcePath);
7129        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7130        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7131
7132        // Note that we invoke the following method only if we are about to unpack an application
7133        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7134                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7135
7136        /*
7137         * If the system app should be overridden by a previously installed
7138         * data, hide the system app now and let the /data/app scan pick it up
7139         * again.
7140         */
7141        if (shouldHideSystemApp) {
7142            synchronized (mPackages) {
7143                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7144            }
7145        }
7146
7147        return scannedPkg;
7148    }
7149
7150    private static String fixProcessName(String defProcessName,
7151            String processName) {
7152        if (processName == null) {
7153            return defProcessName;
7154        }
7155        return processName;
7156    }
7157
7158    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7159            throws PackageManagerException {
7160        if (pkgSetting.signatures.mSignatures != null) {
7161            // Already existing package. Make sure signatures match
7162            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7163                    == PackageManager.SIGNATURE_MATCH;
7164            if (!match) {
7165                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7166                        == PackageManager.SIGNATURE_MATCH;
7167            }
7168            if (!match) {
7169                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7170                        == PackageManager.SIGNATURE_MATCH;
7171            }
7172            if (!match) {
7173                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7174                        + pkg.packageName + " signatures do not match the "
7175                        + "previously installed version; ignoring!");
7176            }
7177        }
7178
7179        // Check for shared user signatures
7180        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7181            // Already existing package. Make sure signatures match
7182            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7183                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7184            if (!match) {
7185                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7186                        == PackageManager.SIGNATURE_MATCH;
7187            }
7188            if (!match) {
7189                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7190                        == PackageManager.SIGNATURE_MATCH;
7191            }
7192            if (!match) {
7193                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7194                        "Package " + pkg.packageName
7195                        + " has no signatures that match those in shared user "
7196                        + pkgSetting.sharedUser.name + "; ignoring!");
7197            }
7198        }
7199    }
7200
7201    /**
7202     * Enforces that only the system UID or root's UID can call a method exposed
7203     * via Binder.
7204     *
7205     * @param message used as message if SecurityException is thrown
7206     * @throws SecurityException if the caller is not system or root
7207     */
7208    private static final void enforceSystemOrRoot(String message) {
7209        final int uid = Binder.getCallingUid();
7210        if (uid != Process.SYSTEM_UID && uid != 0) {
7211            throw new SecurityException(message);
7212        }
7213    }
7214
7215    @Override
7216    public void performFstrimIfNeeded() {
7217        enforceSystemOrRoot("Only the system can request fstrim");
7218
7219        // Before everything else, see whether we need to fstrim.
7220        try {
7221            IMountService ms = PackageHelper.getMountService();
7222            if (ms != null) {
7223                boolean doTrim = false;
7224                final long interval = android.provider.Settings.Global.getLong(
7225                        mContext.getContentResolver(),
7226                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7227                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7228                if (interval > 0) {
7229                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7230                    if (timeSinceLast > interval) {
7231                        doTrim = true;
7232                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7233                                + "; running immediately");
7234                    }
7235                }
7236                if (doTrim) {
7237                    final boolean dexOptDialogShown;
7238                    synchronized (mPackages) {
7239                        dexOptDialogShown = mDexOptDialogShown;
7240                    }
7241                    if (!isFirstBoot() && dexOptDialogShown) {
7242                        try {
7243                            ActivityManagerNative.getDefault().showBootMessage(
7244                                    mContext.getResources().getString(
7245                                            R.string.android_upgrading_fstrim), true);
7246                        } catch (RemoteException e) {
7247                        }
7248                    }
7249                    ms.runMaintenance();
7250                }
7251            } else {
7252                Slog.e(TAG, "Mount service unavailable!");
7253            }
7254        } catch (RemoteException e) {
7255            // Can't happen; MountService is local
7256        }
7257    }
7258
7259    @Override
7260    public void updatePackagesIfNeeded() {
7261        enforceSystemOrRoot("Only the system can request package update");
7262
7263        // We need to re-extract after an OTA.
7264        boolean causeUpgrade = isUpgrade();
7265
7266        // First boot or factory reset.
7267        // Note: we also handle devices that are upgrading to N right now as if it is their
7268        //       first boot, as they do not have profile data.
7269        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7270
7271        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7272        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7273
7274        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7275            return;
7276        }
7277
7278        List<PackageParser.Package> pkgs;
7279        synchronized (mPackages) {
7280            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7281        }
7282
7283        final long startTime = System.nanoTime();
7284        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7285                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7286
7287        final int elapsedTimeSeconds =
7288                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7289
7290        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7291        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7292        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7293        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7294        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7295    }
7296
7297    /**
7298     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7299     * containing statistics about the invocation. The array consists of three elements,
7300     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7301     * and {@code numberOfPackagesFailed}.
7302     */
7303    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7304            String compilerFilter) {
7305
7306        int numberOfPackagesVisited = 0;
7307        int numberOfPackagesOptimized = 0;
7308        int numberOfPackagesSkipped = 0;
7309        int numberOfPackagesFailed = 0;
7310        final int numberOfPackagesToDexopt = pkgs.size();
7311
7312        for (PackageParser.Package pkg : pkgs) {
7313            numberOfPackagesVisited++;
7314
7315            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7316                if (DEBUG_DEXOPT) {
7317                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7318                }
7319                numberOfPackagesSkipped++;
7320                continue;
7321            }
7322
7323            if (DEBUG_DEXOPT) {
7324                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7325                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7326            }
7327
7328            if (showDialog) {
7329                try {
7330                    ActivityManagerNative.getDefault().showBootMessage(
7331                            mContext.getResources().getString(R.string.android_upgrading_apk,
7332                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7333                } catch (RemoteException e) {
7334                }
7335                synchronized (mPackages) {
7336                    mDexOptDialogShown = true;
7337                }
7338            }
7339
7340            // If the OTA updates a system app which was previously preopted to a non-preopted state
7341            // the app might end up being verified at runtime. That's because by default the apps
7342            // are verify-profile but for preopted apps there's no profile.
7343            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7344            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7345            // filter (by default interpret-only).
7346            // Note that at this stage unused apps are already filtered.
7347            if (isSystemApp(pkg) &&
7348                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7349                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7350                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7351            }
7352
7353            // If the OTA updates a system app which was previously preopted to a non-preopted state
7354            // the app might end up being verified at runtime. That's because by default the apps
7355            // are verify-profile but for preopted apps there's no profile.
7356            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7357            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7358            // filter (by default interpret-only).
7359            // Note that at this stage unused apps are already filtered.
7360            if (isSystemApp(pkg) &&
7361                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7362                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7363                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7364            }
7365
7366            // checkProfiles is false to avoid merging profiles during boot which
7367            // might interfere with background compilation (b/28612421).
7368            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7369            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7370            // trade-off worth doing to save boot time work.
7371            int dexOptStatus = performDexOptTraced(pkg.packageName,
7372                    false /* checkProfiles */,
7373                    compilerFilter,
7374                    false /* force */);
7375            switch (dexOptStatus) {
7376                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7377                    numberOfPackagesOptimized++;
7378                    break;
7379                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7380                    numberOfPackagesSkipped++;
7381                    break;
7382                case PackageDexOptimizer.DEX_OPT_FAILED:
7383                    numberOfPackagesFailed++;
7384                    break;
7385                default:
7386                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7387                    break;
7388            }
7389        }
7390
7391        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7392                numberOfPackagesFailed };
7393    }
7394
7395    @Override
7396    public void notifyPackageUse(String packageName, int reason) {
7397        synchronized (mPackages) {
7398            PackageParser.Package p = mPackages.get(packageName);
7399            if (p == null) {
7400                return;
7401            }
7402            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7403        }
7404    }
7405
7406    // TODO: this is not used nor needed. Delete it.
7407    @Override
7408    public boolean performDexOptIfNeeded(String packageName) {
7409        int dexOptStatus = performDexOptTraced(packageName,
7410                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7411        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7412    }
7413
7414    @Override
7415    public boolean performDexOpt(String packageName,
7416            boolean checkProfiles, int compileReason, boolean force) {
7417        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7418                getCompilerFilterForReason(compileReason), force);
7419        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7420    }
7421
7422    @Override
7423    public boolean performDexOptMode(String packageName,
7424            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7425        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7426                targetCompilerFilter, force);
7427        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7428    }
7429
7430    private int performDexOptTraced(String packageName,
7431                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7432        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7433        try {
7434            return performDexOptInternal(packageName, checkProfiles,
7435                    targetCompilerFilter, force);
7436        } finally {
7437            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7438        }
7439    }
7440
7441    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7442    // if the package can now be considered up to date for the given filter.
7443    private int performDexOptInternal(String packageName,
7444                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7445        PackageParser.Package p;
7446        synchronized (mPackages) {
7447            p = mPackages.get(packageName);
7448            if (p == null) {
7449                // Package could not be found. Report failure.
7450                return PackageDexOptimizer.DEX_OPT_FAILED;
7451            }
7452            mPackageUsage.maybeWriteAsync(mPackages);
7453            mCompilerStats.maybeWriteAsync();
7454        }
7455        long callingId = Binder.clearCallingIdentity();
7456        try {
7457            synchronized (mInstallLock) {
7458                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7459                        targetCompilerFilter, force);
7460            }
7461        } finally {
7462            Binder.restoreCallingIdentity(callingId);
7463        }
7464    }
7465
7466    public ArraySet<String> getOptimizablePackages() {
7467        ArraySet<String> pkgs = new ArraySet<String>();
7468        synchronized (mPackages) {
7469            for (PackageParser.Package p : mPackages.values()) {
7470                if (PackageDexOptimizer.canOptimizePackage(p)) {
7471                    pkgs.add(p.packageName);
7472                }
7473            }
7474        }
7475        return pkgs;
7476    }
7477
7478    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7479            boolean checkProfiles, String targetCompilerFilter,
7480            boolean force) {
7481        // Select the dex optimizer based on the force parameter.
7482        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7483        //       allocate an object here.
7484        PackageDexOptimizer pdo = force
7485                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7486                : mPackageDexOptimizer;
7487
7488        // Optimize all dependencies first. Note: we ignore the return value and march on
7489        // on errors.
7490        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7491        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7492        if (!deps.isEmpty()) {
7493            for (PackageParser.Package depPackage : deps) {
7494                // TODO: Analyze and investigate if we (should) profile libraries.
7495                // Currently this will do a full compilation of the library by default.
7496                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7497                        false /* checkProfiles */,
7498                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7499                        getOrCreateCompilerPackageStats(depPackage));
7500            }
7501        }
7502        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7503                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7504    }
7505
7506    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7507        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7508            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7509            Set<String> collectedNames = new HashSet<>();
7510            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7511
7512            retValue.remove(p);
7513
7514            return retValue;
7515        } else {
7516            return Collections.emptyList();
7517        }
7518    }
7519
7520    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7521            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7522        if (!collectedNames.contains(p.packageName)) {
7523            collectedNames.add(p.packageName);
7524            collected.add(p);
7525
7526            if (p.usesLibraries != null) {
7527                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7528            }
7529            if (p.usesOptionalLibraries != null) {
7530                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7531                        collectedNames);
7532            }
7533        }
7534    }
7535
7536    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7537            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7538        for (String libName : libs) {
7539            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7540            if (libPkg != null) {
7541                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7542            }
7543        }
7544    }
7545
7546    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7547        synchronized (mPackages) {
7548            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7549            if (lib != null && lib.apk != null) {
7550                return mPackages.get(lib.apk);
7551            }
7552        }
7553        return null;
7554    }
7555
7556    public void shutdown() {
7557        mPackageUsage.writeNow(mPackages);
7558        mCompilerStats.writeNow();
7559    }
7560
7561    @Override
7562    public void dumpProfiles(String packageName) {
7563        PackageParser.Package pkg;
7564        synchronized (mPackages) {
7565            pkg = mPackages.get(packageName);
7566            if (pkg == null) {
7567                throw new IllegalArgumentException("Unknown package: " + packageName);
7568            }
7569        }
7570        /* Only the shell, root, or the app user should be able to dump profiles. */
7571        int callingUid = Binder.getCallingUid();
7572        if (callingUid != Process.SHELL_UID &&
7573            callingUid != Process.ROOT_UID &&
7574            callingUid != pkg.applicationInfo.uid) {
7575            throw new SecurityException("dumpProfiles");
7576        }
7577
7578        synchronized (mInstallLock) {
7579            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7580            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7581            try {
7582                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7583                String gid = Integer.toString(sharedGid);
7584                String codePaths = TextUtils.join(";", allCodePaths);
7585                mInstaller.dumpProfiles(gid, packageName, codePaths);
7586            } catch (InstallerException e) {
7587                Slog.w(TAG, "Failed to dump profiles", e);
7588            }
7589            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7590        }
7591    }
7592
7593    @Override
7594    public void forceDexOpt(String packageName) {
7595        enforceSystemOrRoot("forceDexOpt");
7596
7597        PackageParser.Package pkg;
7598        synchronized (mPackages) {
7599            pkg = mPackages.get(packageName);
7600            if (pkg == null) {
7601                throw new IllegalArgumentException("Unknown package: " + packageName);
7602            }
7603        }
7604
7605        synchronized (mInstallLock) {
7606            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7607
7608            // Whoever is calling forceDexOpt wants a fully compiled package.
7609            // Don't use profiles since that may cause compilation to be skipped.
7610            final int res = performDexOptInternalWithDependenciesLI(pkg,
7611                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7612                    true /* force */);
7613
7614            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7615            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7616                throw new IllegalStateException("Failed to dexopt: " + res);
7617            }
7618        }
7619    }
7620
7621    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7622        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7623            Slog.w(TAG, "Unable to update from " + oldPkg.name
7624                    + " to " + newPkg.packageName
7625                    + ": old package not in system partition");
7626            return false;
7627        } else if (mPackages.get(oldPkg.name) != null) {
7628            Slog.w(TAG, "Unable to update from " + oldPkg.name
7629                    + " to " + newPkg.packageName
7630                    + ": old package still exists");
7631            return false;
7632        }
7633        return true;
7634    }
7635
7636    void removeCodePathLI(File codePath) {
7637        if (codePath.isDirectory()) {
7638            try {
7639                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7640            } catch (InstallerException e) {
7641                Slog.w(TAG, "Failed to remove code path", e);
7642            }
7643        } else {
7644            codePath.delete();
7645        }
7646    }
7647
7648    private int[] resolveUserIds(int userId) {
7649        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7650    }
7651
7652    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7653        if (pkg == null) {
7654            Slog.wtf(TAG, "Package was null!", new Throwable());
7655            return;
7656        }
7657        clearAppDataLeafLIF(pkg, userId, flags);
7658        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7659        for (int i = 0; i < childCount; i++) {
7660            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7661        }
7662    }
7663
7664    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7665        final PackageSetting ps;
7666        synchronized (mPackages) {
7667            ps = mSettings.mPackages.get(pkg.packageName);
7668        }
7669        for (int realUserId : resolveUserIds(userId)) {
7670            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7671            try {
7672                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7673                        ceDataInode);
7674            } catch (InstallerException e) {
7675                Slog.w(TAG, String.valueOf(e));
7676            }
7677        }
7678    }
7679
7680    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7681        if (pkg == null) {
7682            Slog.wtf(TAG, "Package was null!", new Throwable());
7683            return;
7684        }
7685        destroyAppDataLeafLIF(pkg, userId, flags);
7686        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7687        for (int i = 0; i < childCount; i++) {
7688            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7689        }
7690    }
7691
7692    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7693        final PackageSetting ps;
7694        synchronized (mPackages) {
7695            ps = mSettings.mPackages.get(pkg.packageName);
7696        }
7697        for (int realUserId : resolveUserIds(userId)) {
7698            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7699            try {
7700                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7701                        ceDataInode);
7702            } catch (InstallerException e) {
7703                Slog.w(TAG, String.valueOf(e));
7704            }
7705        }
7706    }
7707
7708    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7709        if (pkg == null) {
7710            Slog.wtf(TAG, "Package was null!", new Throwable());
7711            return;
7712        }
7713        destroyAppProfilesLeafLIF(pkg);
7714        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7715        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7716        for (int i = 0; i < childCount; i++) {
7717            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7718            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7719                    true /* removeBaseMarker */);
7720        }
7721    }
7722
7723    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7724            boolean removeBaseMarker) {
7725        if (pkg.isForwardLocked()) {
7726            return;
7727        }
7728
7729        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7730            try {
7731                path = PackageManagerServiceUtils.realpath(new File(path));
7732            } catch (IOException e) {
7733                // TODO: Should we return early here ?
7734                Slog.w(TAG, "Failed to get canonical path", e);
7735                continue;
7736            }
7737
7738            final String useMarker = path.replace('/', '@');
7739            for (int realUserId : resolveUserIds(userId)) {
7740                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7741                if (removeBaseMarker) {
7742                    File foreignUseMark = new File(profileDir, useMarker);
7743                    if (foreignUseMark.exists()) {
7744                        if (!foreignUseMark.delete()) {
7745                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7746                                    + pkg.packageName);
7747                        }
7748                    }
7749                }
7750
7751                File[] markers = profileDir.listFiles();
7752                if (markers != null) {
7753                    final String searchString = "@" + pkg.packageName + "@";
7754                    // We also delete all markers that contain the package name we're
7755                    // uninstalling. These are associated with secondary dex-files belonging
7756                    // to the package. Reconstructing the path of these dex files is messy
7757                    // in general.
7758                    for (File marker : markers) {
7759                        if (marker.getName().indexOf(searchString) > 0) {
7760                            if (!marker.delete()) {
7761                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7762                                    + pkg.packageName);
7763                            }
7764                        }
7765                    }
7766                }
7767            }
7768        }
7769    }
7770
7771    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7772        try {
7773            mInstaller.destroyAppProfiles(pkg.packageName);
7774        } catch (InstallerException e) {
7775            Slog.w(TAG, String.valueOf(e));
7776        }
7777    }
7778
7779    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7780        if (pkg == null) {
7781            Slog.wtf(TAG, "Package was null!", new Throwable());
7782            return;
7783        }
7784        clearAppProfilesLeafLIF(pkg);
7785        // We don't remove the base foreign use marker when clearing profiles because
7786        // we will rename it when the app is updated. Unlike the actual profile contents,
7787        // the foreign use marker is good across installs.
7788        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7789        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7790        for (int i = 0; i < childCount; i++) {
7791            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7792        }
7793    }
7794
7795    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7796        try {
7797            mInstaller.clearAppProfiles(pkg.packageName);
7798        } catch (InstallerException e) {
7799            Slog.w(TAG, String.valueOf(e));
7800        }
7801    }
7802
7803    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7804            long lastUpdateTime) {
7805        // Set parent install/update time
7806        PackageSetting ps = (PackageSetting) pkg.mExtras;
7807        if (ps != null) {
7808            ps.firstInstallTime = firstInstallTime;
7809            ps.lastUpdateTime = lastUpdateTime;
7810        }
7811        // Set children install/update time
7812        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7813        for (int i = 0; i < childCount; i++) {
7814            PackageParser.Package childPkg = pkg.childPackages.get(i);
7815            ps = (PackageSetting) childPkg.mExtras;
7816            if (ps != null) {
7817                ps.firstInstallTime = firstInstallTime;
7818                ps.lastUpdateTime = lastUpdateTime;
7819            }
7820        }
7821    }
7822
7823    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7824            PackageParser.Package changingLib) {
7825        if (file.path != null) {
7826            usesLibraryFiles.add(file.path);
7827            return;
7828        }
7829        PackageParser.Package p = mPackages.get(file.apk);
7830        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7831            // If we are doing this while in the middle of updating a library apk,
7832            // then we need to make sure to use that new apk for determining the
7833            // dependencies here.  (We haven't yet finished committing the new apk
7834            // to the package manager state.)
7835            if (p == null || p.packageName.equals(changingLib.packageName)) {
7836                p = changingLib;
7837            }
7838        }
7839        if (p != null) {
7840            usesLibraryFiles.addAll(p.getAllCodePaths());
7841        }
7842    }
7843
7844    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7845            PackageParser.Package changingLib) throws PackageManagerException {
7846        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7847            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7848            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7849            for (int i=0; i<N; i++) {
7850                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7851                if (file == null) {
7852                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7853                            "Package " + pkg.packageName + " requires unavailable shared library "
7854                            + pkg.usesLibraries.get(i) + "; failing!");
7855                }
7856                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7857            }
7858            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7859            for (int i=0; i<N; i++) {
7860                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7861                if (file == null) {
7862                    Slog.w(TAG, "Package " + pkg.packageName
7863                            + " desires unavailable shared library "
7864                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7865                } else {
7866                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
7867                }
7868            }
7869            N = usesLibraryFiles.size();
7870            if (N > 0) {
7871                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7872            } else {
7873                pkg.usesLibraryFiles = null;
7874            }
7875        }
7876    }
7877
7878    private static boolean hasString(List<String> list, List<String> which) {
7879        if (list == null) {
7880            return false;
7881        }
7882        for (int i=list.size()-1; i>=0; i--) {
7883            for (int j=which.size()-1; j>=0; j--) {
7884                if (which.get(j).equals(list.get(i))) {
7885                    return true;
7886                }
7887            }
7888        }
7889        return false;
7890    }
7891
7892    private void updateAllSharedLibrariesLPw() {
7893        for (PackageParser.Package pkg : mPackages.values()) {
7894            try {
7895                updateSharedLibrariesLPr(pkg, null);
7896            } catch (PackageManagerException e) {
7897                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7898            }
7899        }
7900    }
7901
7902    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7903            PackageParser.Package changingPkg) {
7904        ArrayList<PackageParser.Package> res = null;
7905        for (PackageParser.Package pkg : mPackages.values()) {
7906            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7907                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7908                if (res == null) {
7909                    res = new ArrayList<PackageParser.Package>();
7910                }
7911                res.add(pkg);
7912                try {
7913                    updateSharedLibrariesLPr(pkg, changingPkg);
7914                } catch (PackageManagerException e) {
7915                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7916                }
7917            }
7918        }
7919        return res;
7920    }
7921
7922    /**
7923     * Derive the value of the {@code cpuAbiOverride} based on the provided
7924     * value and an optional stored value from the package settings.
7925     */
7926    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7927        String cpuAbiOverride = null;
7928
7929        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7930            cpuAbiOverride = null;
7931        } else if (abiOverride != null) {
7932            cpuAbiOverride = abiOverride;
7933        } else if (settings != null) {
7934            cpuAbiOverride = settings.cpuAbiOverrideString;
7935        }
7936
7937        return cpuAbiOverride;
7938    }
7939
7940    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7941            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7942                    throws PackageManagerException {
7943        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7944        // If the package has children and this is the first dive in the function
7945        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7946        // whether all packages (parent and children) would be successfully scanned
7947        // before the actual scan since scanning mutates internal state and we want
7948        // to atomically install the package and its children.
7949        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7950            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7951                scanFlags |= SCAN_CHECK_ONLY;
7952            }
7953        } else {
7954            scanFlags &= ~SCAN_CHECK_ONLY;
7955        }
7956
7957        final PackageParser.Package scannedPkg;
7958        try {
7959            // Scan the parent
7960            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7961            // Scan the children
7962            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7963            for (int i = 0; i < childCount; i++) {
7964                PackageParser.Package childPkg = pkg.childPackages.get(i);
7965                scanPackageLI(childPkg, policyFlags,
7966                        scanFlags, currentTime, user);
7967            }
7968        } finally {
7969            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7970        }
7971
7972        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7973            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7974        }
7975
7976        return scannedPkg;
7977    }
7978
7979    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7980            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7981        boolean success = false;
7982        try {
7983            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7984                    currentTime, user);
7985            success = true;
7986            return res;
7987        } finally {
7988            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7989                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7990                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7991                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7992                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7993            }
7994        }
7995    }
7996
7997    /**
7998     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7999     */
8000    private static boolean apkHasCode(String fileName) {
8001        StrictJarFile jarFile = null;
8002        try {
8003            jarFile = new StrictJarFile(fileName,
8004                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8005            return jarFile.findEntry("classes.dex") != null;
8006        } catch (IOException ignore) {
8007        } finally {
8008            try {
8009                if (jarFile != null) {
8010                    jarFile.close();
8011                }
8012            } catch (IOException ignore) {}
8013        }
8014        return false;
8015    }
8016
8017    /**
8018     * Enforces code policy for the package. This ensures that if an APK has
8019     * declared hasCode="true" in its manifest that the APK actually contains
8020     * code.
8021     *
8022     * @throws PackageManagerException If bytecode could not be found when it should exist
8023     */
8024    private static void assertCodePolicy(PackageParser.Package pkg)
8025            throws PackageManagerException {
8026        final boolean shouldHaveCode =
8027                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8028        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8029            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8030                    "Package " + pkg.baseCodePath + " code is missing");
8031        }
8032
8033        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8034            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8035                final boolean splitShouldHaveCode =
8036                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8037                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8038                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8039                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8040                }
8041            }
8042        }
8043    }
8044
8045    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8046            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8047                    throws PackageManagerException {
8048        if (DEBUG_PACKAGE_SCANNING) {
8049            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8050                Log.d(TAG, "Scanning package " + pkg.packageName);
8051        }
8052
8053        applyPolicy(pkg, policyFlags);
8054
8055        assertPackageIsValid(pkg, policyFlags);
8056
8057        // Initialize package source and resource directories
8058        final File scanFile = new File(pkg.codePath);
8059        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8060        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8061
8062        SharedUserSetting suid = null;
8063        PackageSetting pkgSetting = null;
8064
8065        // Getting the package setting may have a side-effect, so if we
8066        // are only checking if scan would succeed, stash a copy of the
8067        // old setting to restore at the end.
8068        PackageSetting nonMutatedPs = null;
8069
8070        // writer
8071        synchronized (mPackages) {
8072            if (pkg.mSharedUserId != null) {
8073                // SIDE EFFECTS; may potentially allocate a new shared user
8074                suid = mSettings.getSharedUserLPw(
8075                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8076                if (DEBUG_PACKAGE_SCANNING) {
8077                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8078                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8079                                + "): packages=" + suid.packages);
8080                }
8081            }
8082
8083            // Check if we are renaming from an original package name.
8084            PackageSetting origPackage = null;
8085            String realName = null;
8086            if (pkg.mOriginalPackages != null) {
8087                // This package may need to be renamed to a previously
8088                // installed name.  Let's check on that...
8089                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8090                if (pkg.mOriginalPackages.contains(renamed)) {
8091                    // This package had originally been installed as the
8092                    // original name, and we have already taken care of
8093                    // transitioning to the new one.  Just update the new
8094                    // one to continue using the old name.
8095                    realName = pkg.mRealPackage;
8096                    if (!pkg.packageName.equals(renamed)) {
8097                        // Callers into this function may have already taken
8098                        // care of renaming the package; only do it here if
8099                        // it is not already done.
8100                        pkg.setPackageName(renamed);
8101                    }
8102                } else {
8103                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8104                        if ((origPackage = mSettings.getPackageLPr(
8105                                pkg.mOriginalPackages.get(i))) != null) {
8106                            // We do have the package already installed under its
8107                            // original name...  should we use it?
8108                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8109                                // New package is not compatible with original.
8110                                origPackage = null;
8111                                continue;
8112                            } else if (origPackage.sharedUser != null) {
8113                                // Make sure uid is compatible between packages.
8114                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8115                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8116                                            + " to " + pkg.packageName + ": old uid "
8117                                            + origPackage.sharedUser.name
8118                                            + " differs from " + pkg.mSharedUserId);
8119                                    origPackage = null;
8120                                    continue;
8121                                }
8122                                // TODO: Add case when shared user id is added [b/28144775]
8123                            } else {
8124                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8125                                        + pkg.packageName + " to old name " + origPackage.name);
8126                            }
8127                            break;
8128                        }
8129                    }
8130                }
8131            }
8132
8133            if (mTransferedPackages.contains(pkg.packageName)) {
8134                Slog.w(TAG, "Package " + pkg.packageName
8135                        + " was transferred to another, but its .apk remains");
8136            }
8137
8138            // See comments in nonMutatedPs declaration
8139            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8140                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8141                if (foundPs != null) {
8142                    nonMutatedPs = new PackageSetting(foundPs);
8143                }
8144            }
8145
8146            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8147            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8148                PackageManagerService.reportSettingsProblem(Log.WARN,
8149                        "Package " + pkg.packageName + " shared user changed from "
8150                                + (pkgSetting.sharedUser != null
8151                                        ? pkgSetting.sharedUser.name : "<nothing>")
8152                                + " to "
8153                                + (suid != null ? suid.name : "<nothing>")
8154                                + "; replacing with new");
8155                pkgSetting = null;
8156            }
8157            final PackageSetting oldPkgSetting =
8158                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8159            final PackageSetting disabledPkgSetting =
8160                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8161            if (pkgSetting == null) {
8162                final String parentPackageName = (pkg.parentPackage != null)
8163                        ? pkg.parentPackage.packageName : null;
8164                // REMOVE SharedUserSetting from method; update in a separate call
8165                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8166                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8167                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8168                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8169                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8170                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8171                        UserManagerService.getInstance());
8172                // SIDE EFFECTS; updates system state; move elsewhere
8173                if (origPackage != null) {
8174                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8175                }
8176                mSettings.addUserToSettingLPw(pkgSetting);
8177            } else {
8178                // REMOVE SharedUserSetting from method; update in a separate call
8179                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8180                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8181                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8182                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8183                        UserManagerService.getInstance());
8184            }
8185            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8186            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8187
8188            // SIDE EFFECTS; modifies system state; move elsewhere
8189            if (pkgSetting.origPackage != null) {
8190                // If we are first transitioning from an original package,
8191                // fix up the new package's name now.  We need to do this after
8192                // looking up the package under its new name, so getPackageLP
8193                // can take care of fiddling things correctly.
8194                pkg.setPackageName(origPackage.name);
8195
8196                // File a report about this.
8197                String msg = "New package " + pkgSetting.realName
8198                        + " renamed to replace old package " + pkgSetting.name;
8199                reportSettingsProblem(Log.WARN, msg);
8200
8201                // Make a note of it.
8202                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8203                    mTransferedPackages.add(origPackage.name);
8204                }
8205
8206                // No longer need to retain this.
8207                pkgSetting.origPackage = null;
8208            }
8209
8210            // SIDE EFFECTS; modifies system state; move elsewhere
8211            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8212                // Make a note of it.
8213                mTransferedPackages.add(pkg.packageName);
8214            }
8215
8216            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8217                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8218            }
8219
8220            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8221                // Check all shared libraries and map to their actual file path.
8222                // We only do this here for apps not on a system dir, because those
8223                // are the only ones that can fail an install due to this.  We
8224                // will take care of the system apps by updating all of their
8225                // library paths after the scan is done.
8226                updateSharedLibrariesLPr(pkg, null);
8227            }
8228
8229            if (mFoundPolicyFile) {
8230                SELinuxMMAC.assignSeinfoValue(pkg);
8231            }
8232
8233            pkg.applicationInfo.uid = pkgSetting.appId;
8234            pkg.mExtras = pkgSetting;
8235            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8236                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8237                    // We just determined the app is signed correctly, so bring
8238                    // over the latest parsed certs.
8239                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8240                } else {
8241                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8242                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8243                                "Package " + pkg.packageName + " upgrade keys do not match the "
8244                                + "previously installed version");
8245                    } else {
8246                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8247                        String msg = "System package " + pkg.packageName
8248                                + " signature changed; retaining data.";
8249                        reportSettingsProblem(Log.WARN, msg);
8250                    }
8251                }
8252            } else {
8253                try {
8254                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8255                    verifySignaturesLP(pkgSetting, pkg);
8256                    // We just determined the app is signed correctly, so bring
8257                    // over the latest parsed certs.
8258                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8259                } catch (PackageManagerException e) {
8260                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8261                        throw e;
8262                    }
8263                    // The signature has changed, but this package is in the system
8264                    // image...  let's recover!
8265                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8266                    // However...  if this package is part of a shared user, but it
8267                    // doesn't match the signature of the shared user, let's fail.
8268                    // What this means is that you can't change the signatures
8269                    // associated with an overall shared user, which doesn't seem all
8270                    // that unreasonable.
8271                    if (pkgSetting.sharedUser != null) {
8272                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8273                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8274                            throw new PackageManagerException(
8275                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8276                                    "Signature mismatch for shared user: "
8277                                            + pkgSetting.sharedUser);
8278                        }
8279                    }
8280                    // File a report about this.
8281                    String msg = "System package " + pkg.packageName
8282                            + " signature changed; retaining data.";
8283                    reportSettingsProblem(Log.WARN, msg);
8284                }
8285            }
8286
8287            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8288                // This package wants to adopt ownership of permissions from
8289                // another package.
8290                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8291                    final String origName = pkg.mAdoptPermissions.get(i);
8292                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8293                    if (orig != null) {
8294                        if (verifyPackageUpdateLPr(orig, pkg)) {
8295                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8296                                    + pkg.packageName);
8297                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8298                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8299                        }
8300                    }
8301                }
8302            }
8303        }
8304
8305        pkg.applicationInfo.processName = fixProcessName(
8306                pkg.applicationInfo.packageName,
8307                pkg.applicationInfo.processName);
8308
8309        if (pkg != mPlatformPackage) {
8310            // Get all of our default paths setup
8311            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8312        }
8313
8314        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8315
8316        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8317            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8318            derivePackageAbi(
8319                    pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8320            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8321
8322            // Some system apps still use directory structure for native libraries
8323            // in which case we might end up not detecting abi solely based on apk
8324            // structure. Try to detect abi based on directory structure.
8325            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8326                    pkg.applicationInfo.primaryCpuAbi == null) {
8327                setBundledAppAbisAndRoots(pkg, pkgSetting);
8328                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8329            }
8330        } else {
8331            if ((scanFlags & SCAN_MOVE) != 0) {
8332                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8333                // but we already have this packages package info in the PackageSetting. We just
8334                // use that and derive the native library path based on the new codepath.
8335                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8336                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8337            }
8338
8339            // Set native library paths again. For moves, the path will be updated based on the
8340            // ABIs we've determined above. For non-moves, the path will be updated based on the
8341            // ABIs we determined during compilation, but the path will depend on the final
8342            // package path (after the rename away from the stage path).
8343            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8344        }
8345
8346        // This is a special case for the "system" package, where the ABI is
8347        // dictated by the zygote configuration (and init.rc). We should keep track
8348        // of this ABI so that we can deal with "normal" applications that run under
8349        // the same UID correctly.
8350        if (mPlatformPackage == pkg) {
8351            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8352                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8353        }
8354
8355        // If there's a mismatch between the abi-override in the package setting
8356        // and the abiOverride specified for the install. Warn about this because we
8357        // would've already compiled the app without taking the package setting into
8358        // account.
8359        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8360            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8361                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8362                        " for package " + pkg.packageName);
8363            }
8364        }
8365
8366        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8367        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8368        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8369
8370        // Copy the derived override back to the parsed package, so that we can
8371        // update the package settings accordingly.
8372        pkg.cpuAbiOverride = cpuAbiOverride;
8373
8374        if (DEBUG_ABI_SELECTION) {
8375            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8376                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8377                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8378        }
8379
8380        // Push the derived path down into PackageSettings so we know what to
8381        // clean up at uninstall time.
8382        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8383
8384        if (DEBUG_ABI_SELECTION) {
8385            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8386                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8387                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8388        }
8389
8390        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8391        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8392            // We don't do this here during boot because we can do it all
8393            // at once after scanning all existing packages.
8394            //
8395            // We also do this *before* we perform dexopt on this package, so that
8396            // we can avoid redundant dexopts, and also to make sure we've got the
8397            // code and package path correct.
8398            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8399        }
8400
8401        if (mFactoryTest && pkg.requestedPermissions.contains(
8402                android.Manifest.permission.FACTORY_TEST)) {
8403            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8404        }
8405
8406        if (isSystemApp(pkg)) {
8407            pkgSetting.isOrphaned = true;
8408        }
8409
8410        // Take care of first install / last update times.
8411        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8412        if (currentTime != 0) {
8413            if (pkgSetting.firstInstallTime == 0) {
8414                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8415            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8416                pkgSetting.lastUpdateTime = currentTime;
8417            }
8418        } else if (pkgSetting.firstInstallTime == 0) {
8419            // We need *something*.  Take time time stamp of the file.
8420            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8421        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8422            if (scanFileTime != pkgSetting.timeStamp) {
8423                // A package on the system image has changed; consider this
8424                // to be an update.
8425                pkgSetting.lastUpdateTime = scanFileTime;
8426            }
8427        }
8428        pkgSetting.setTimeStamp(scanFileTime);
8429
8430        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8431            if (nonMutatedPs != null) {
8432                synchronized (mPackages) {
8433                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8434                }
8435            }
8436        } else {
8437            // Modify state for the given package setting
8438            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8439                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8440        }
8441        return pkg;
8442    }
8443
8444    /**
8445     * Applies policy to the parsed package based upon the given policy flags.
8446     * Ensures the package is in a good state.
8447     * <p>
8448     * Implementation detail: This method must NOT have any side effect. It would
8449     * ideally be static, but, it requires locks to read system state.
8450     */
8451    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8452        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8454            if (pkg.applicationInfo.isDirectBootAware()) {
8455                // we're direct boot aware; set for all components
8456                for (PackageParser.Service s : pkg.services) {
8457                    s.info.encryptionAware = s.info.directBootAware = true;
8458                }
8459                for (PackageParser.Provider p : pkg.providers) {
8460                    p.info.encryptionAware = p.info.directBootAware = true;
8461                }
8462                for (PackageParser.Activity a : pkg.activities) {
8463                    a.info.encryptionAware = a.info.directBootAware = true;
8464                }
8465                for (PackageParser.Activity r : pkg.receivers) {
8466                    r.info.encryptionAware = r.info.directBootAware = true;
8467                }
8468            }
8469        } else {
8470            // Only allow system apps to be flagged as core apps.
8471            pkg.coreApp = false;
8472            // clear flags not applicable to regular apps
8473            pkg.applicationInfo.privateFlags &=
8474                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8475            pkg.applicationInfo.privateFlags &=
8476                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8477        }
8478        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8479
8480        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8481            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8482        }
8483
8484        if (!isSystemApp(pkg)) {
8485            // Only system apps can use these features.
8486            pkg.mOriginalPackages = null;
8487            pkg.mRealPackage = null;
8488            pkg.mAdoptPermissions = null;
8489        }
8490    }
8491
8492    /**
8493     * Asserts the parsed package is valid according to teh given policy. If the
8494     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8495     * <p>
8496     * Implementation detail: This method must NOT have any side effects. It would
8497     * ideally be static, but, it requires locks to read system state.
8498     *
8499     * @throws PackageManagerException If the package fails any of the validation checks
8500     */
8501    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags)
8502            throws PackageManagerException {
8503        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8504            assertCodePolicy(pkg);
8505        }
8506
8507        if (pkg.applicationInfo.getCodePath() == null ||
8508                pkg.applicationInfo.getResourcePath() == null) {
8509            // Bail out. The resource and code paths haven't been set.
8510            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8511                    "Code and resource paths haven't been set correctly");
8512        }
8513
8514        // Make sure we're not adding any bogus keyset info
8515        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8516        ksms.assertScannedPackageValid(pkg);
8517
8518        synchronized (mPackages) {
8519            // The special "android" package can only be defined once
8520            if (pkg.packageName.equals("android")) {
8521                if (mAndroidApplication != null) {
8522                    Slog.w(TAG, "*************************************************");
8523                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8524                    Slog.w(TAG, " codePath=" + pkg.codePath);
8525                    Slog.w(TAG, "*************************************************");
8526                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8527                            "Core android package being redefined.  Skipping.");
8528                }
8529            }
8530
8531            // A package name must be unique; don't allow duplicates
8532            if (mPackages.containsKey(pkg.packageName)
8533                    || mSharedLibraries.containsKey(pkg.packageName)) {
8534                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8535                        "Application package " + pkg.packageName
8536                        + " already installed.  Skipping duplicate.");
8537            }
8538
8539            // Only privileged apps and updated privileged apps can add child packages.
8540            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8541                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8542                    throw new PackageManagerException("Only privileged apps can add child "
8543                            + "packages. Ignoring package " + pkg.packageName);
8544                }
8545                final int childCount = pkg.childPackages.size();
8546                for (int i = 0; i < childCount; i++) {
8547                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8548                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8549                            childPkg.packageName)) {
8550                        throw new PackageManagerException("Can't override child of "
8551                                + "another disabled app. Ignoring package " + pkg.packageName);
8552                    }
8553                }
8554            }
8555
8556            // If we're only installing presumed-existing packages, require that the
8557            // scanned APK is both already known and at the path previously established
8558            // for it.  Previously unknown packages we pick up normally, but if we have an
8559            // a priori expectation about this package's install presence, enforce it.
8560            // With a singular exception for new system packages. When an OTA contains
8561            // a new system package, we allow the codepath to change from a system location
8562            // to the user-installed location. If we don't allow this change, any newer,
8563            // user-installed version of the application will be ignored.
8564            if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) {
8565                if (mExpectingBetter.containsKey(pkg.packageName)) {
8566                    logCriticalInfo(Log.WARN,
8567                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8568                } else {
8569                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8570                    if (known != null) {
8571                        if (DEBUG_PACKAGE_SCANNING) {
8572                            Log.d(TAG, "Examining " + pkg.codePath
8573                                    + " and requiring known paths " + known.codePathString
8574                                    + " & " + known.resourcePathString);
8575                        }
8576                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8577                                || !pkg.applicationInfo.getResourcePath().equals(
8578                                        known.resourcePathString)) {
8579                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8580                                    "Application package " + pkg.packageName
8581                                    + " found at " + pkg.applicationInfo.getCodePath()
8582                                    + " but expected at " + known.codePathString
8583                                    + "; ignoring.");
8584                        }
8585                    }
8586                }
8587            }
8588
8589            // Verify that this new package doesn't have any content providers
8590            // that conflict with existing packages.  Only do this if the
8591            // package isn't already installed, since we don't want to break
8592            // things that are installed.
8593            if ((policyFlags & SCAN_NEW_INSTALL) != 0) {
8594                final int N = pkg.providers.size();
8595                int i;
8596                for (i=0; i<N; i++) {
8597                    PackageParser.Provider p = pkg.providers.get(i);
8598                    if (p.info.authority != null) {
8599                        String names[] = p.info.authority.split(";");
8600                        for (int j = 0; j < names.length; j++) {
8601                            if (mProvidersByAuthority.containsKey(names[j])) {
8602                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8603                                final String otherPackageName =
8604                                        ((other != null && other.getComponentName() != null) ?
8605                                                other.getComponentName().getPackageName() : "?");
8606                                throw new PackageManagerException(
8607                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8608                                        "Can't install because provider name " + names[j]
8609                                                + " (in package " + pkg.applicationInfo.packageName
8610                                                + ") is already used by " + otherPackageName);
8611                            }
8612                        }
8613                    }
8614                }
8615            }
8616        }
8617    }
8618
8619    /**
8620     * Adds a scanned package to the system. When this method is finished, the package will
8621     * be available for query, resolution, etc...
8622     */
8623    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8624            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8625        final String pkgName = pkg.packageName;
8626        if (mCustomResolverComponentName != null &&
8627                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8628            setUpCustomResolverActivity(pkg);
8629        }
8630
8631        if (pkg.packageName.equals("android")) {
8632            synchronized (mPackages) {
8633                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8634                    // Set up information for our fall-back user intent resolution activity.
8635                    mPlatformPackage = pkg;
8636                    pkg.mVersionCode = mSdkVersion;
8637                    mAndroidApplication = pkg.applicationInfo;
8638
8639                    if (!mResolverReplaced) {
8640                        mResolveActivity.applicationInfo = mAndroidApplication;
8641                        mResolveActivity.name = ResolverActivity.class.getName();
8642                        mResolveActivity.packageName = mAndroidApplication.packageName;
8643                        mResolveActivity.processName = "system:ui";
8644                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8645                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8646                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8647                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8648                        mResolveActivity.exported = true;
8649                        mResolveActivity.enabled = true;
8650                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8651                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8652                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8653                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8654                                | ActivityInfo.CONFIG_ORIENTATION
8655                                | ActivityInfo.CONFIG_KEYBOARD
8656                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8657                        mResolveInfo.activityInfo = mResolveActivity;
8658                        mResolveInfo.priority = 0;
8659                        mResolveInfo.preferredOrder = 0;
8660                        mResolveInfo.match = 0;
8661                        mResolveComponentName = new ComponentName(
8662                                mAndroidApplication.packageName, mResolveActivity.name);
8663                    }
8664                }
8665            }
8666        }
8667
8668        ArrayList<PackageParser.Package> clientLibPkgs = null;
8669        // writer
8670        synchronized (mPackages) {
8671            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8672                // Only system apps can add new shared libraries.
8673                if (pkg.libraryNames != null) {
8674                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8675                        String name = pkg.libraryNames.get(i);
8676                        boolean allowed = false;
8677                        if (pkg.isUpdatedSystemApp()) {
8678                            // New library entries can only be added through the
8679                            // system image.  This is important to get rid of a lot
8680                            // of nasty edge cases: for example if we allowed a non-
8681                            // system update of the app to add a library, then uninstalling
8682                            // the update would make the library go away, and assumptions
8683                            // we made such as through app install filtering would now
8684                            // have allowed apps on the device which aren't compatible
8685                            // with it.  Better to just have the restriction here, be
8686                            // conservative, and create many fewer cases that can negatively
8687                            // impact the user experience.
8688                            final PackageSetting sysPs = mSettings
8689                                    .getDisabledSystemPkgLPr(pkg.packageName);
8690                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8691                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8692                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8693                                        allowed = true;
8694                                        break;
8695                                    }
8696                                }
8697                            }
8698                        } else {
8699                            allowed = true;
8700                        }
8701                        if (allowed) {
8702                            if (!mSharedLibraries.containsKey(name)) {
8703                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8704                            } else if (!name.equals(pkg.packageName)) {
8705                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8706                                        + name + " already exists; skipping");
8707                            }
8708                        } else {
8709                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8710                                    + name + " that is not declared on system image; skipping");
8711                        }
8712                    }
8713                    if ((scanFlags & SCAN_BOOTING) == 0) {
8714                        // If we are not booting, we need to update any applications
8715                        // that are clients of our shared library.  If we are booting,
8716                        // this will all be done once the scan is complete.
8717                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8718                    }
8719                }
8720            }
8721        }
8722
8723        if ((scanFlags & SCAN_BOOTING) != 0) {
8724            // No apps can run during boot scan, so they don't need to be frozen
8725        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8726            // Caller asked to not kill app, so it's probably not frozen
8727        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8728            // Caller asked us to ignore frozen check for some reason; they
8729            // probably didn't know the package name
8730        } else {
8731            // We're doing major surgery on this package, so it better be frozen
8732            // right now to keep it from launching
8733            checkPackageFrozen(pkgName);
8734        }
8735
8736        // Also need to kill any apps that are dependent on the library.
8737        if (clientLibPkgs != null) {
8738            for (int i=0; i<clientLibPkgs.size(); i++) {
8739                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8740                killApplication(clientPkg.applicationInfo.packageName,
8741                        clientPkg.applicationInfo.uid, "update lib");
8742            }
8743        }
8744
8745        // writer
8746        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8747
8748        boolean createIdmapFailed = false;
8749        synchronized (mPackages) {
8750            // We don't expect installation to fail beyond this point
8751
8752            if (pkgSetting.pkg != null) {
8753                // Note that |user| might be null during the initial boot scan. If a codePath
8754                // for an app has changed during a boot scan, it's due to an app update that's
8755                // part of the system partition and marker changes must be applied to all users.
8756                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8757                final int[] userIds = resolveUserIds(userId);
8758                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8759            }
8760
8761            // Add the new setting to mSettings
8762            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8763            // Add the new setting to mPackages
8764            mPackages.put(pkg.applicationInfo.packageName, pkg);
8765            // Make sure we don't accidentally delete its data.
8766            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8767            while (iter.hasNext()) {
8768                PackageCleanItem item = iter.next();
8769                if (pkgName.equals(item.packageName)) {
8770                    iter.remove();
8771                }
8772            }
8773
8774            // Add the package's KeySets to the global KeySetManagerService
8775            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8776            ksms.addScannedPackageLPw(pkg);
8777
8778            int N = pkg.providers.size();
8779            StringBuilder r = null;
8780            int i;
8781            for (i=0; i<N; i++) {
8782                PackageParser.Provider p = pkg.providers.get(i);
8783                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8784                        p.info.processName);
8785                mProviders.addProvider(p);
8786                p.syncable = p.info.isSyncable;
8787                if (p.info.authority != null) {
8788                    String names[] = p.info.authority.split(";");
8789                    p.info.authority = null;
8790                    for (int j = 0; j < names.length; j++) {
8791                        if (j == 1 && p.syncable) {
8792                            // We only want the first authority for a provider to possibly be
8793                            // syncable, so if we already added this provider using a different
8794                            // authority clear the syncable flag. We copy the provider before
8795                            // changing it because the mProviders object contains a reference
8796                            // to a provider that we don't want to change.
8797                            // Only do this for the second authority since the resulting provider
8798                            // object can be the same for all future authorities for this provider.
8799                            p = new PackageParser.Provider(p);
8800                            p.syncable = false;
8801                        }
8802                        if (!mProvidersByAuthority.containsKey(names[j])) {
8803                            mProvidersByAuthority.put(names[j], p);
8804                            if (p.info.authority == null) {
8805                                p.info.authority = names[j];
8806                            } else {
8807                                p.info.authority = p.info.authority + ";" + names[j];
8808                            }
8809                            if (DEBUG_PACKAGE_SCANNING) {
8810                                if (chatty)
8811                                    Log.d(TAG, "Registered content provider: " + names[j]
8812                                            + ", className = " + p.info.name + ", isSyncable = "
8813                                            + p.info.isSyncable);
8814                            }
8815                        } else {
8816                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8817                            Slog.w(TAG, "Skipping provider name " + names[j] +
8818                                    " (in package " + pkg.applicationInfo.packageName +
8819                                    "): name already used by "
8820                                    + ((other != null && other.getComponentName() != null)
8821                                            ? other.getComponentName().getPackageName() : "?"));
8822                        }
8823                    }
8824                }
8825                if (chatty) {
8826                    if (r == null) {
8827                        r = new StringBuilder(256);
8828                    } else {
8829                        r.append(' ');
8830                    }
8831                    r.append(p.info.name);
8832                }
8833            }
8834            if (r != null) {
8835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8836            }
8837
8838            N = pkg.services.size();
8839            r = null;
8840            for (i=0; i<N; i++) {
8841                PackageParser.Service s = pkg.services.get(i);
8842                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8843                        s.info.processName);
8844                mServices.addService(s);
8845                if (chatty) {
8846                    if (r == null) {
8847                        r = new StringBuilder(256);
8848                    } else {
8849                        r.append(' ');
8850                    }
8851                    r.append(s.info.name);
8852                }
8853            }
8854            if (r != null) {
8855                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8856            }
8857
8858            N = pkg.receivers.size();
8859            r = null;
8860            for (i=0; i<N; i++) {
8861                PackageParser.Activity a = pkg.receivers.get(i);
8862                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8863                        a.info.processName);
8864                mReceivers.addActivity(a, "receiver");
8865                if (chatty) {
8866                    if (r == null) {
8867                        r = new StringBuilder(256);
8868                    } else {
8869                        r.append(' ');
8870                    }
8871                    r.append(a.info.name);
8872                }
8873            }
8874            if (r != null) {
8875                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8876            }
8877
8878            N = pkg.activities.size();
8879            r = null;
8880            for (i=0; i<N; i++) {
8881                PackageParser.Activity a = pkg.activities.get(i);
8882                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8883                        a.info.processName);
8884                mActivities.addActivity(a, "activity");
8885                if (chatty) {
8886                    if (r == null) {
8887                        r = new StringBuilder(256);
8888                    } else {
8889                        r.append(' ');
8890                    }
8891                    r.append(a.info.name);
8892                }
8893            }
8894            if (r != null) {
8895                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8896            }
8897
8898            N = pkg.permissionGroups.size();
8899            r = null;
8900            for (i=0; i<N; i++) {
8901                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8902                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8903                final String curPackageName = cur == null ? null : cur.info.packageName;
8904                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8905                if (cur == null || isPackageUpdate) {
8906                    mPermissionGroups.put(pg.info.name, pg);
8907                    if (chatty) {
8908                        if (r == null) {
8909                            r = new StringBuilder(256);
8910                        } else {
8911                            r.append(' ');
8912                        }
8913                        if (isPackageUpdate) {
8914                            r.append("UPD:");
8915                        }
8916                        r.append(pg.info.name);
8917                    }
8918                } else {
8919                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8920                            + pg.info.packageName + " ignored: original from "
8921                            + cur.info.packageName);
8922                    if (chatty) {
8923                        if (r == null) {
8924                            r = new StringBuilder(256);
8925                        } else {
8926                            r.append(' ');
8927                        }
8928                        r.append("DUP:");
8929                        r.append(pg.info.name);
8930                    }
8931                }
8932            }
8933            if (r != null) {
8934                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8935            }
8936
8937            N = pkg.permissions.size();
8938            r = null;
8939            for (i=0; i<N; i++) {
8940                PackageParser.Permission p = pkg.permissions.get(i);
8941
8942                // Assume by default that we did not install this permission into the system.
8943                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8944
8945                // Now that permission groups have a special meaning, we ignore permission
8946                // groups for legacy apps to prevent unexpected behavior. In particular,
8947                // permissions for one app being granted to someone just becase they happen
8948                // to be in a group defined by another app (before this had no implications).
8949                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8950                    p.group = mPermissionGroups.get(p.info.group);
8951                    // Warn for a permission in an unknown group.
8952                    if (p.info.group != null && p.group == null) {
8953                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8954                                + p.info.packageName + " in an unknown group " + p.info.group);
8955                    }
8956                }
8957
8958                ArrayMap<String, BasePermission> permissionMap =
8959                        p.tree ? mSettings.mPermissionTrees
8960                                : mSettings.mPermissions;
8961                BasePermission bp = permissionMap.get(p.info.name);
8962
8963                // Allow system apps to redefine non-system permissions
8964                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8965                    final boolean currentOwnerIsSystem = (bp.perm != null
8966                            && isSystemApp(bp.perm.owner));
8967                    if (isSystemApp(p.owner)) {
8968                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8969                            // It's a built-in permission and no owner, take ownership now
8970                            bp.packageSetting = pkgSetting;
8971                            bp.perm = p;
8972                            bp.uid = pkg.applicationInfo.uid;
8973                            bp.sourcePackage = p.info.packageName;
8974                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8975                        } else if (!currentOwnerIsSystem) {
8976                            String msg = "New decl " + p.owner + " of permission  "
8977                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8978                            reportSettingsProblem(Log.WARN, msg);
8979                            bp = null;
8980                        }
8981                    }
8982                }
8983
8984                if (bp == null) {
8985                    bp = new BasePermission(p.info.name, p.info.packageName,
8986                            BasePermission.TYPE_NORMAL);
8987                    permissionMap.put(p.info.name, bp);
8988                }
8989
8990                if (bp.perm == null) {
8991                    if (bp.sourcePackage == null
8992                            || bp.sourcePackage.equals(p.info.packageName)) {
8993                        BasePermission tree = findPermissionTreeLP(p.info.name);
8994                        if (tree == null
8995                                || tree.sourcePackage.equals(p.info.packageName)) {
8996                            bp.packageSetting = pkgSetting;
8997                            bp.perm = p;
8998                            bp.uid = pkg.applicationInfo.uid;
8999                            bp.sourcePackage = p.info.packageName;
9000                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9001                            if (chatty) {
9002                                if (r == null) {
9003                                    r = new StringBuilder(256);
9004                                } else {
9005                                    r.append(' ');
9006                                }
9007                                r.append(p.info.name);
9008                            }
9009                        } else {
9010                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9011                                    + p.info.packageName + " ignored: base tree "
9012                                    + tree.name + " is from package "
9013                                    + tree.sourcePackage);
9014                        }
9015                    } else {
9016                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9017                                + p.info.packageName + " ignored: original from "
9018                                + bp.sourcePackage);
9019                    }
9020                } else if (chatty) {
9021                    if (r == null) {
9022                        r = new StringBuilder(256);
9023                    } else {
9024                        r.append(' ');
9025                    }
9026                    r.append("DUP:");
9027                    r.append(p.info.name);
9028                }
9029                if (bp.perm == p) {
9030                    bp.protectionLevel = p.info.protectionLevel;
9031                }
9032            }
9033
9034            if (r != null) {
9035                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9036            }
9037
9038            N = pkg.instrumentation.size();
9039            r = null;
9040            for (i=0; i<N; i++) {
9041                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9042                a.info.packageName = pkg.applicationInfo.packageName;
9043                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9044                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9045                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9046                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9047                a.info.dataDir = pkg.applicationInfo.dataDir;
9048                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9049                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9050                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9051                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9052                mInstrumentation.put(a.getComponentName(), a);
9053                if (chatty) {
9054                    if (r == null) {
9055                        r = new StringBuilder(256);
9056                    } else {
9057                        r.append(' ');
9058                    }
9059                    r.append(a.info.name);
9060                }
9061            }
9062            if (r != null) {
9063                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9064            }
9065
9066            if (pkg.protectedBroadcasts != null) {
9067                N = pkg.protectedBroadcasts.size();
9068                for (i=0; i<N; i++) {
9069                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9070                }
9071            }
9072
9073            // Create idmap files for pairs of (packages, overlay packages).
9074            // Note: "android", ie framework-res.apk, is handled by native layers.
9075            if (pkg.mOverlayTarget != null) {
9076                // This is an overlay package.
9077                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9078                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9079                        mOverlays.put(pkg.mOverlayTarget,
9080                                new ArrayMap<String, PackageParser.Package>());
9081                    }
9082                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9083                    map.put(pkg.packageName, pkg);
9084                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9085                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9086                        createIdmapFailed = true;
9087                    }
9088                }
9089            } else if (mOverlays.containsKey(pkg.packageName) &&
9090                    !pkg.packageName.equals("android")) {
9091                // This is a regular package, with one or more known overlay packages.
9092                createIdmapsForPackageLI(pkg);
9093            }
9094        }
9095
9096        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9097
9098        if (createIdmapFailed) {
9099            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9100                    "scanPackageLI failed to createIdmap");
9101        }
9102    }
9103
9104    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9105            PackageParser.Package update, int[] userIds) {
9106        if (existing.applicationInfo == null || update.applicationInfo == null) {
9107            // This isn't due to an app installation.
9108            return;
9109        }
9110
9111        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9112        final File newCodePath = new File(update.applicationInfo.getCodePath());
9113
9114        // The codePath hasn't changed, so there's nothing for us to do.
9115        if (Objects.equals(oldCodePath, newCodePath)) {
9116            return;
9117        }
9118
9119        File canonicalNewCodePath;
9120        try {
9121            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9122        } catch (IOException e) {
9123            Slog.w(TAG, "Failed to get canonical path.", e);
9124            return;
9125        }
9126
9127        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9128        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9129        // that the last component of the path (i.e, the name) doesn't need canonicalization
9130        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9131        // but may change in the future. Hopefully this function won't exist at that point.
9132        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9133                oldCodePath.getName());
9134
9135        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9136        // with "@".
9137        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9138        if (!oldMarkerPrefix.endsWith("@")) {
9139            oldMarkerPrefix += "@";
9140        }
9141        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9142        if (!newMarkerPrefix.endsWith("@")) {
9143            newMarkerPrefix += "@";
9144        }
9145
9146        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9147        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9148        for (String updatedPath : updatedPaths) {
9149            String updatedPathName = new File(updatedPath).getName();
9150            markerSuffixes.add(updatedPathName.replace('/', '@'));
9151        }
9152
9153        for (int userId : userIds) {
9154            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9155
9156            for (String markerSuffix : markerSuffixes) {
9157                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9158                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9159                if (oldForeignUseMark.exists()) {
9160                    try {
9161                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9162                                newForeignUseMark.getAbsolutePath());
9163                    } catch (ErrnoException e) {
9164                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9165                        oldForeignUseMark.delete();
9166                    }
9167                }
9168            }
9169        }
9170    }
9171
9172    /**
9173     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9174     * is derived purely on the basis of the contents of {@code scanFile} and
9175     * {@code cpuAbiOverride}.
9176     *
9177     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9178     */
9179    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9180                                 String cpuAbiOverride, boolean extractLibs,
9181                                 File appLib32InstallDir)
9182            throws PackageManagerException {
9183        // TODO: We can probably be smarter about this stuff. For installed apps,
9184        // we can calculate this information at install time once and for all. For
9185        // system apps, we can probably assume that this information doesn't change
9186        // after the first boot scan. As things stand, we do lots of unnecessary work.
9187
9188        // Give ourselves some initial paths; we'll come back for another
9189        // pass once we've determined ABI below.
9190        setNativeLibraryPaths(pkg, appLib32InstallDir);
9191
9192        // We would never need to extract libs for forward-locked and external packages,
9193        // since the container service will do it for us. We shouldn't attempt to
9194        // extract libs from system app when it was not updated.
9195        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9196                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9197            extractLibs = false;
9198        }
9199
9200        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9201        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9202
9203        NativeLibraryHelper.Handle handle = null;
9204        try {
9205            handle = NativeLibraryHelper.Handle.create(pkg);
9206            // TODO(multiArch): This can be null for apps that didn't go through the
9207            // usual installation process. We can calculate it again, like we
9208            // do during install time.
9209            //
9210            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9211            // unnecessary.
9212            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9213
9214            // Null out the abis so that they can be recalculated.
9215            pkg.applicationInfo.primaryCpuAbi = null;
9216            pkg.applicationInfo.secondaryCpuAbi = null;
9217            if (isMultiArch(pkg.applicationInfo)) {
9218                // Warn if we've set an abiOverride for multi-lib packages..
9219                // By definition, we need to copy both 32 and 64 bit libraries for
9220                // such packages.
9221                if (pkg.cpuAbiOverride != null
9222                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9223                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9224                }
9225
9226                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9227                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9228                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9229                    if (extractLibs) {
9230                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9231                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9232                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9233                                useIsaSpecificSubdirs);
9234                    } else {
9235                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9236                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9237                    }
9238                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9239                }
9240
9241                maybeThrowExceptionForMultiArchCopy(
9242                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9243
9244                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9245                    if (extractLibs) {
9246                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9247                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9248                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9249                                useIsaSpecificSubdirs);
9250                    } else {
9251                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9252                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9253                    }
9254                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9255                }
9256
9257                maybeThrowExceptionForMultiArchCopy(
9258                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9259
9260                if (abi64 >= 0) {
9261                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9262                }
9263
9264                if (abi32 >= 0) {
9265                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9266                    if (abi64 >= 0) {
9267                        if (pkg.use32bitAbi) {
9268                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9269                            pkg.applicationInfo.primaryCpuAbi = abi;
9270                        } else {
9271                            pkg.applicationInfo.secondaryCpuAbi = abi;
9272                        }
9273                    } else {
9274                        pkg.applicationInfo.primaryCpuAbi = abi;
9275                    }
9276                }
9277
9278            } else {
9279                String[] abiList = (cpuAbiOverride != null) ?
9280                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9281
9282                // Enable gross and lame hacks for apps that are built with old
9283                // SDK tools. We must scan their APKs for renderscript bitcode and
9284                // not launch them if it's present. Don't bother checking on devices
9285                // that don't have 64 bit support.
9286                boolean needsRenderScriptOverride = false;
9287                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9288                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9289                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9290                    needsRenderScriptOverride = true;
9291                }
9292
9293                final int copyRet;
9294                if (extractLibs) {
9295                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9296                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9297                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9298                } else {
9299                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9300                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9301                }
9302                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9303
9304                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9305                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9306                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9307                }
9308
9309                if (copyRet >= 0) {
9310                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9311                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9312                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9313                } else if (needsRenderScriptOverride) {
9314                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9315                }
9316            }
9317        } catch (IOException ioe) {
9318            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9319        } finally {
9320            IoUtils.closeQuietly(handle);
9321        }
9322
9323        // Now that we've calculated the ABIs and determined if it's an internal app,
9324        // we will go ahead and populate the nativeLibraryPath.
9325        setNativeLibraryPaths(pkg, appLib32InstallDir);
9326    }
9327
9328    /**
9329     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9330     * i.e, so that all packages can be run inside a single process if required.
9331     *
9332     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9333     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9334     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9335     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9336     * updating a package that belongs to a shared user.
9337     *
9338     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9339     * adds unnecessary complexity.
9340     */
9341    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9342            PackageParser.Package scannedPackage) {
9343        String requiredInstructionSet = null;
9344        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9345            requiredInstructionSet = VMRuntime.getInstructionSet(
9346                     scannedPackage.applicationInfo.primaryCpuAbi);
9347        }
9348
9349        PackageSetting requirer = null;
9350        for (PackageSetting ps : packagesForUser) {
9351            // If packagesForUser contains scannedPackage, we skip it. This will happen
9352            // when scannedPackage is an update of an existing package. Without this check,
9353            // we will never be able to change the ABI of any package belonging to a shared
9354            // user, even if it's compatible with other packages.
9355            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9356                if (ps.primaryCpuAbiString == null) {
9357                    continue;
9358                }
9359
9360                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9361                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9362                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9363                    // this but there's not much we can do.
9364                    String errorMessage = "Instruction set mismatch, "
9365                            + ((requirer == null) ? "[caller]" : requirer)
9366                            + " requires " + requiredInstructionSet + " whereas " + ps
9367                            + " requires " + instructionSet;
9368                    Slog.w(TAG, errorMessage);
9369                }
9370
9371                if (requiredInstructionSet == null) {
9372                    requiredInstructionSet = instructionSet;
9373                    requirer = ps;
9374                }
9375            }
9376        }
9377
9378        if (requiredInstructionSet != null) {
9379            String adjustedAbi;
9380            if (requirer != null) {
9381                // requirer != null implies that either scannedPackage was null or that scannedPackage
9382                // did not require an ABI, in which case we have to adjust scannedPackage to match
9383                // the ABI of the set (which is the same as requirer's ABI)
9384                adjustedAbi = requirer.primaryCpuAbiString;
9385                if (scannedPackage != null) {
9386                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9387                }
9388            } else {
9389                // requirer == null implies that we're updating all ABIs in the set to
9390                // match scannedPackage.
9391                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9392            }
9393
9394            for (PackageSetting ps : packagesForUser) {
9395                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9396                    if (ps.primaryCpuAbiString != null) {
9397                        continue;
9398                    }
9399
9400                    ps.primaryCpuAbiString = adjustedAbi;
9401                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9402                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9403                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9404                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9405                                + " (requirer="
9406                                + (requirer == null ? "null" : requirer.pkg.packageName)
9407                                + ", scannedPackage="
9408                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9409                                + ")");
9410                        try {
9411                            mInstaller.rmdex(ps.codePathString,
9412                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9413                        } catch (InstallerException ignored) {
9414                        }
9415                    }
9416                }
9417            }
9418        }
9419    }
9420
9421    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9422        synchronized (mPackages) {
9423            mResolverReplaced = true;
9424            // Set up information for custom user intent resolution activity.
9425            mResolveActivity.applicationInfo = pkg.applicationInfo;
9426            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9427            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9428            mResolveActivity.processName = pkg.applicationInfo.packageName;
9429            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9430            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9431                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9432            mResolveActivity.theme = 0;
9433            mResolveActivity.exported = true;
9434            mResolveActivity.enabled = true;
9435            mResolveInfo.activityInfo = mResolveActivity;
9436            mResolveInfo.priority = 0;
9437            mResolveInfo.preferredOrder = 0;
9438            mResolveInfo.match = 0;
9439            mResolveComponentName = mCustomResolverComponentName;
9440            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9441                    mResolveComponentName);
9442        }
9443    }
9444
9445    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9446        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9447
9448        // Set up information for ephemeral installer activity
9449        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9450        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9451        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9452        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9453        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9454        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9455                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9456        mEphemeralInstallerActivity.theme = 0;
9457        mEphemeralInstallerActivity.exported = true;
9458        mEphemeralInstallerActivity.enabled = true;
9459        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9460        mEphemeralInstallerInfo.priority = 0;
9461        mEphemeralInstallerInfo.preferredOrder = 1;
9462        mEphemeralInstallerInfo.isDefault = true;
9463        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9464                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9465
9466        if (DEBUG_EPHEMERAL) {
9467            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9468        }
9469    }
9470
9471    private static String calculateBundledApkRoot(final String codePathString) {
9472        final File codePath = new File(codePathString);
9473        final File codeRoot;
9474        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9475            codeRoot = Environment.getRootDirectory();
9476        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9477            codeRoot = Environment.getOemDirectory();
9478        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9479            codeRoot = Environment.getVendorDirectory();
9480        } else {
9481            // Unrecognized code path; take its top real segment as the apk root:
9482            // e.g. /something/app/blah.apk => /something
9483            try {
9484                File f = codePath.getCanonicalFile();
9485                File parent = f.getParentFile();    // non-null because codePath is a file
9486                File tmp;
9487                while ((tmp = parent.getParentFile()) != null) {
9488                    f = parent;
9489                    parent = tmp;
9490                }
9491                codeRoot = f;
9492                Slog.w(TAG, "Unrecognized code path "
9493                        + codePath + " - using " + codeRoot);
9494            } catch (IOException e) {
9495                // Can't canonicalize the code path -- shenanigans?
9496                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9497                return Environment.getRootDirectory().getPath();
9498            }
9499        }
9500        return codeRoot.getPath();
9501    }
9502
9503    /**
9504     * Derive and set the location of native libraries for the given package,
9505     * which varies depending on where and how the package was installed.
9506     */
9507    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9508        final ApplicationInfo info = pkg.applicationInfo;
9509        final String codePath = pkg.codePath;
9510        final File codeFile = new File(codePath);
9511        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9512        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9513
9514        info.nativeLibraryRootDir = null;
9515        info.nativeLibraryRootRequiresIsa = false;
9516        info.nativeLibraryDir = null;
9517        info.secondaryNativeLibraryDir = null;
9518
9519        if (isApkFile(codeFile)) {
9520            // Monolithic install
9521            if (bundledApp) {
9522                // If "/system/lib64/apkname" exists, assume that is the per-package
9523                // native library directory to use; otherwise use "/system/lib/apkname".
9524                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9525                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9526                        getPrimaryInstructionSet(info));
9527
9528                // This is a bundled system app so choose the path based on the ABI.
9529                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9530                // is just the default path.
9531                final String apkName = deriveCodePathName(codePath);
9532                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9533                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9534                        apkName).getAbsolutePath();
9535
9536                if (info.secondaryCpuAbi != null) {
9537                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9538                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9539                            secondaryLibDir, apkName).getAbsolutePath();
9540                }
9541            } else if (asecApp) {
9542                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9543                        .getAbsolutePath();
9544            } else {
9545                final String apkName = deriveCodePathName(codePath);
9546                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9547                        .getAbsolutePath();
9548            }
9549
9550            info.nativeLibraryRootRequiresIsa = false;
9551            info.nativeLibraryDir = info.nativeLibraryRootDir;
9552        } else {
9553            // Cluster install
9554            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9555            info.nativeLibraryRootRequiresIsa = true;
9556
9557            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9558                    getPrimaryInstructionSet(info)).getAbsolutePath();
9559
9560            if (info.secondaryCpuAbi != null) {
9561                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9562                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9563            }
9564        }
9565    }
9566
9567    /**
9568     * Calculate the abis and roots for a bundled app. These can uniquely
9569     * be determined from the contents of the system partition, i.e whether
9570     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9571     * of this information, and instead assume that the system was built
9572     * sensibly.
9573     */
9574    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9575                                           PackageSetting pkgSetting) {
9576        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9577
9578        // If "/system/lib64/apkname" exists, assume that is the per-package
9579        // native library directory to use; otherwise use "/system/lib/apkname".
9580        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9581        setBundledAppAbi(pkg, apkRoot, apkName);
9582        // pkgSetting might be null during rescan following uninstall of updates
9583        // to a bundled app, so accommodate that possibility.  The settings in
9584        // that case will be established later from the parsed package.
9585        //
9586        // If the settings aren't null, sync them up with what we've just derived.
9587        // note that apkRoot isn't stored in the package settings.
9588        if (pkgSetting != null) {
9589            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9590            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9591        }
9592    }
9593
9594    /**
9595     * Deduces the ABI of a bundled app and sets the relevant fields on the
9596     * parsed pkg object.
9597     *
9598     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9599     *        under which system libraries are installed.
9600     * @param apkName the name of the installed package.
9601     */
9602    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9603        final File codeFile = new File(pkg.codePath);
9604
9605        final boolean has64BitLibs;
9606        final boolean has32BitLibs;
9607        if (isApkFile(codeFile)) {
9608            // Monolithic install
9609            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9610            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9611        } else {
9612            // Cluster install
9613            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9614            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9615                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9616                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9617                has64BitLibs = (new File(rootDir, isa)).exists();
9618            } else {
9619                has64BitLibs = false;
9620            }
9621            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9622                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9623                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9624                has32BitLibs = (new File(rootDir, isa)).exists();
9625            } else {
9626                has32BitLibs = false;
9627            }
9628        }
9629
9630        if (has64BitLibs && !has32BitLibs) {
9631            // The package has 64 bit libs, but not 32 bit libs. Its primary
9632            // ABI should be 64 bit. We can safely assume here that the bundled
9633            // native libraries correspond to the most preferred ABI in the list.
9634
9635            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9636            pkg.applicationInfo.secondaryCpuAbi = null;
9637        } else if (has32BitLibs && !has64BitLibs) {
9638            // The package has 32 bit libs but not 64 bit libs. Its primary
9639            // ABI should be 32 bit.
9640
9641            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9642            pkg.applicationInfo.secondaryCpuAbi = null;
9643        } else if (has32BitLibs && has64BitLibs) {
9644            // The application has both 64 and 32 bit bundled libraries. We check
9645            // here that the app declares multiArch support, and warn if it doesn't.
9646            //
9647            // We will be lenient here and record both ABIs. The primary will be the
9648            // ABI that's higher on the list, i.e, a device that's configured to prefer
9649            // 64 bit apps will see a 64 bit primary ABI,
9650
9651            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9652                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9653            }
9654
9655            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9656                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9657                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9658            } else {
9659                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9660                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9661            }
9662        } else {
9663            pkg.applicationInfo.primaryCpuAbi = null;
9664            pkg.applicationInfo.secondaryCpuAbi = null;
9665        }
9666    }
9667
9668    private void killApplication(String pkgName, int appId, String reason) {
9669        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9670    }
9671
9672    private void killApplication(String pkgName, int appId, int userId, String reason) {
9673        // Request the ActivityManager to kill the process(only for existing packages)
9674        // so that we do not end up in a confused state while the user is still using the older
9675        // version of the application while the new one gets installed.
9676        final long token = Binder.clearCallingIdentity();
9677        try {
9678            IActivityManager am = ActivityManagerNative.getDefault();
9679            if (am != null) {
9680                try {
9681                    am.killApplication(pkgName, appId, userId, reason);
9682                } catch (RemoteException e) {
9683                }
9684            }
9685        } finally {
9686            Binder.restoreCallingIdentity(token);
9687        }
9688    }
9689
9690    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9691        // Remove the parent package setting
9692        PackageSetting ps = (PackageSetting) pkg.mExtras;
9693        if (ps != null) {
9694            removePackageLI(ps, chatty);
9695        }
9696        // Remove the child package setting
9697        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9698        for (int i = 0; i < childCount; i++) {
9699            PackageParser.Package childPkg = pkg.childPackages.get(i);
9700            ps = (PackageSetting) childPkg.mExtras;
9701            if (ps != null) {
9702                removePackageLI(ps, chatty);
9703            }
9704        }
9705    }
9706
9707    void removePackageLI(PackageSetting ps, boolean chatty) {
9708        if (DEBUG_INSTALL) {
9709            if (chatty)
9710                Log.d(TAG, "Removing package " + ps.name);
9711        }
9712
9713        // writer
9714        synchronized (mPackages) {
9715            mPackages.remove(ps.name);
9716            final PackageParser.Package pkg = ps.pkg;
9717            if (pkg != null) {
9718                cleanPackageDataStructuresLILPw(pkg, chatty);
9719            }
9720        }
9721    }
9722
9723    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9724        if (DEBUG_INSTALL) {
9725            if (chatty)
9726                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9727        }
9728
9729        // writer
9730        synchronized (mPackages) {
9731            // Remove the parent package
9732            mPackages.remove(pkg.applicationInfo.packageName);
9733            cleanPackageDataStructuresLILPw(pkg, chatty);
9734
9735            // Remove the child packages
9736            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9737            for (int i = 0; i < childCount; i++) {
9738                PackageParser.Package childPkg = pkg.childPackages.get(i);
9739                mPackages.remove(childPkg.applicationInfo.packageName);
9740                cleanPackageDataStructuresLILPw(childPkg, chatty);
9741            }
9742        }
9743    }
9744
9745    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9746        int N = pkg.providers.size();
9747        StringBuilder r = null;
9748        int i;
9749        for (i=0; i<N; i++) {
9750            PackageParser.Provider p = pkg.providers.get(i);
9751            mProviders.removeProvider(p);
9752            if (p.info.authority == null) {
9753
9754                /* There was another ContentProvider with this authority when
9755                 * this app was installed so this authority is null,
9756                 * Ignore it as we don't have to unregister the provider.
9757                 */
9758                continue;
9759            }
9760            String names[] = p.info.authority.split(";");
9761            for (int j = 0; j < names.length; j++) {
9762                if (mProvidersByAuthority.get(names[j]) == p) {
9763                    mProvidersByAuthority.remove(names[j]);
9764                    if (DEBUG_REMOVE) {
9765                        if (chatty)
9766                            Log.d(TAG, "Unregistered content provider: " + names[j]
9767                                    + ", className = " + p.info.name + ", isSyncable = "
9768                                    + p.info.isSyncable);
9769                    }
9770                }
9771            }
9772            if (DEBUG_REMOVE && chatty) {
9773                if (r == null) {
9774                    r = new StringBuilder(256);
9775                } else {
9776                    r.append(' ');
9777                }
9778                r.append(p.info.name);
9779            }
9780        }
9781        if (r != null) {
9782            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9783        }
9784
9785        N = pkg.services.size();
9786        r = null;
9787        for (i=0; i<N; i++) {
9788            PackageParser.Service s = pkg.services.get(i);
9789            mServices.removeService(s);
9790            if (chatty) {
9791                if (r == null) {
9792                    r = new StringBuilder(256);
9793                } else {
9794                    r.append(' ');
9795                }
9796                r.append(s.info.name);
9797            }
9798        }
9799        if (r != null) {
9800            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9801        }
9802
9803        N = pkg.receivers.size();
9804        r = null;
9805        for (i=0; i<N; i++) {
9806            PackageParser.Activity a = pkg.receivers.get(i);
9807            mReceivers.removeActivity(a, "receiver");
9808            if (DEBUG_REMOVE && chatty) {
9809                if (r == null) {
9810                    r = new StringBuilder(256);
9811                } else {
9812                    r.append(' ');
9813                }
9814                r.append(a.info.name);
9815            }
9816        }
9817        if (r != null) {
9818            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9819        }
9820
9821        N = pkg.activities.size();
9822        r = null;
9823        for (i=0; i<N; i++) {
9824            PackageParser.Activity a = pkg.activities.get(i);
9825            mActivities.removeActivity(a, "activity");
9826            if (DEBUG_REMOVE && chatty) {
9827                if (r == null) {
9828                    r = new StringBuilder(256);
9829                } else {
9830                    r.append(' ');
9831                }
9832                r.append(a.info.name);
9833            }
9834        }
9835        if (r != null) {
9836            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9837        }
9838
9839        N = pkg.permissions.size();
9840        r = null;
9841        for (i=0; i<N; i++) {
9842            PackageParser.Permission p = pkg.permissions.get(i);
9843            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9844            if (bp == null) {
9845                bp = mSettings.mPermissionTrees.get(p.info.name);
9846            }
9847            if (bp != null && bp.perm == p) {
9848                bp.perm = null;
9849                if (DEBUG_REMOVE && chatty) {
9850                    if (r == null) {
9851                        r = new StringBuilder(256);
9852                    } else {
9853                        r.append(' ');
9854                    }
9855                    r.append(p.info.name);
9856                }
9857            }
9858            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9859                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9860                if (appOpPkgs != null) {
9861                    appOpPkgs.remove(pkg.packageName);
9862                }
9863            }
9864        }
9865        if (r != null) {
9866            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9867        }
9868
9869        N = pkg.requestedPermissions.size();
9870        r = null;
9871        for (i=0; i<N; i++) {
9872            String perm = pkg.requestedPermissions.get(i);
9873            BasePermission bp = mSettings.mPermissions.get(perm);
9874            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9875                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9876                if (appOpPkgs != null) {
9877                    appOpPkgs.remove(pkg.packageName);
9878                    if (appOpPkgs.isEmpty()) {
9879                        mAppOpPermissionPackages.remove(perm);
9880                    }
9881                }
9882            }
9883        }
9884        if (r != null) {
9885            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9886        }
9887
9888        N = pkg.instrumentation.size();
9889        r = null;
9890        for (i=0; i<N; i++) {
9891            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9892            mInstrumentation.remove(a.getComponentName());
9893            if (DEBUG_REMOVE && chatty) {
9894                if (r == null) {
9895                    r = new StringBuilder(256);
9896                } else {
9897                    r.append(' ');
9898                }
9899                r.append(a.info.name);
9900            }
9901        }
9902        if (r != null) {
9903            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9904        }
9905
9906        r = null;
9907        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9908            // Only system apps can hold shared libraries.
9909            if (pkg.libraryNames != null) {
9910                for (i=0; i<pkg.libraryNames.size(); i++) {
9911                    String name = pkg.libraryNames.get(i);
9912                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9913                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9914                        mSharedLibraries.remove(name);
9915                        if (DEBUG_REMOVE && chatty) {
9916                            if (r == null) {
9917                                r = new StringBuilder(256);
9918                            } else {
9919                                r.append(' ');
9920                            }
9921                            r.append(name);
9922                        }
9923                    }
9924                }
9925            }
9926        }
9927        if (r != null) {
9928            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9929        }
9930    }
9931
9932    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9933        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9934            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9935                return true;
9936            }
9937        }
9938        return false;
9939    }
9940
9941    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9942    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9943    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9944
9945    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9946        // Update the parent permissions
9947        updatePermissionsLPw(pkg.packageName, pkg, flags);
9948        // Update the child permissions
9949        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9950        for (int i = 0; i < childCount; i++) {
9951            PackageParser.Package childPkg = pkg.childPackages.get(i);
9952            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9953        }
9954    }
9955
9956    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9957            int flags) {
9958        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9959        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9960    }
9961
9962    private void updatePermissionsLPw(String changingPkg,
9963            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9964        // Make sure there are no dangling permission trees.
9965        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9966        while (it.hasNext()) {
9967            final BasePermission bp = it.next();
9968            if (bp.packageSetting == null) {
9969                // We may not yet have parsed the package, so just see if
9970                // we still know about its settings.
9971                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9972            }
9973            if (bp.packageSetting == null) {
9974                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9975                        + " from package " + bp.sourcePackage);
9976                it.remove();
9977            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9978                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9979                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9980                            + " from package " + bp.sourcePackage);
9981                    flags |= UPDATE_PERMISSIONS_ALL;
9982                    it.remove();
9983                }
9984            }
9985        }
9986
9987        // Make sure all dynamic permissions have been assigned to a package,
9988        // and make sure there are no dangling permissions.
9989        it = mSettings.mPermissions.values().iterator();
9990        while (it.hasNext()) {
9991            final BasePermission bp = it.next();
9992            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9993                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9994                        + bp.name + " pkg=" + bp.sourcePackage
9995                        + " info=" + bp.pendingInfo);
9996                if (bp.packageSetting == null && bp.pendingInfo != null) {
9997                    final BasePermission tree = findPermissionTreeLP(bp.name);
9998                    if (tree != null && tree.perm != null) {
9999                        bp.packageSetting = tree.packageSetting;
10000                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10001                                new PermissionInfo(bp.pendingInfo));
10002                        bp.perm.info.packageName = tree.perm.info.packageName;
10003                        bp.perm.info.name = bp.name;
10004                        bp.uid = tree.uid;
10005                    }
10006                }
10007            }
10008            if (bp.packageSetting == null) {
10009                // We may not yet have parsed the package, so just see if
10010                // we still know about its settings.
10011                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10012            }
10013            if (bp.packageSetting == null) {
10014                Slog.w(TAG, "Removing dangling permission: " + bp.name
10015                        + " from package " + bp.sourcePackage);
10016                it.remove();
10017            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10018                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10019                    Slog.i(TAG, "Removing old permission: " + bp.name
10020                            + " from package " + bp.sourcePackage);
10021                    flags |= UPDATE_PERMISSIONS_ALL;
10022                    it.remove();
10023                }
10024            }
10025        }
10026
10027        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10028        // Now update the permissions for all packages, in particular
10029        // replace the granted permissions of the system packages.
10030        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10031            for (PackageParser.Package pkg : mPackages.values()) {
10032                if (pkg != pkgInfo) {
10033                    // Only replace for packages on requested volume
10034                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10035                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10036                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10037                    grantPermissionsLPw(pkg, replace, changingPkg);
10038                }
10039            }
10040        }
10041
10042        if (pkgInfo != null) {
10043            // Only replace for packages on requested volume
10044            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10045            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10046                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10047            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10048        }
10049        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10050    }
10051
10052    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10053            String packageOfInterest) {
10054        // IMPORTANT: There are two types of permissions: install and runtime.
10055        // Install time permissions are granted when the app is installed to
10056        // all device users and users added in the future. Runtime permissions
10057        // are granted at runtime explicitly to specific users. Normal and signature
10058        // protected permissions are install time permissions. Dangerous permissions
10059        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10060        // otherwise they are runtime permissions. This function does not manage
10061        // runtime permissions except for the case an app targeting Lollipop MR1
10062        // being upgraded to target a newer SDK, in which case dangerous permissions
10063        // are transformed from install time to runtime ones.
10064
10065        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10066        if (ps == null) {
10067            return;
10068        }
10069
10070        PermissionsState permissionsState = ps.getPermissionsState();
10071        PermissionsState origPermissions = permissionsState;
10072
10073        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10074
10075        boolean runtimePermissionsRevoked = false;
10076        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10077
10078        boolean changedInstallPermission = false;
10079
10080        if (replace) {
10081            ps.installPermissionsFixed = false;
10082            if (!ps.isSharedUser()) {
10083                origPermissions = new PermissionsState(permissionsState);
10084                permissionsState.reset();
10085            } else {
10086                // We need to know only about runtime permission changes since the
10087                // calling code always writes the install permissions state but
10088                // the runtime ones are written only if changed. The only cases of
10089                // changed runtime permissions here are promotion of an install to
10090                // runtime and revocation of a runtime from a shared user.
10091                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10092                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10093                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10094                    runtimePermissionsRevoked = true;
10095                }
10096            }
10097        }
10098
10099        permissionsState.setGlobalGids(mGlobalGids);
10100
10101        final int N = pkg.requestedPermissions.size();
10102        for (int i=0; i<N; i++) {
10103            final String name = pkg.requestedPermissions.get(i);
10104            final BasePermission bp = mSettings.mPermissions.get(name);
10105
10106            if (DEBUG_INSTALL) {
10107                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10108            }
10109
10110            if (bp == null || bp.packageSetting == null) {
10111                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10112                    Slog.w(TAG, "Unknown permission " + name
10113                            + " in package " + pkg.packageName);
10114                }
10115                continue;
10116            }
10117
10118
10119            // Limit ephemeral apps to ephemeral allowed permissions.
10120            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10121                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10122                        + pkg.packageName);
10123                continue;
10124            }
10125
10126            final String perm = bp.name;
10127            boolean allowedSig = false;
10128            int grant = GRANT_DENIED;
10129
10130            // Keep track of app op permissions.
10131            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10132                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10133                if (pkgs == null) {
10134                    pkgs = new ArraySet<>();
10135                    mAppOpPermissionPackages.put(bp.name, pkgs);
10136                }
10137                pkgs.add(pkg.packageName);
10138            }
10139
10140            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10141            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10142                    >= Build.VERSION_CODES.M;
10143            switch (level) {
10144                case PermissionInfo.PROTECTION_NORMAL: {
10145                    // For all apps normal permissions are install time ones.
10146                    grant = GRANT_INSTALL;
10147                } break;
10148
10149                case PermissionInfo.PROTECTION_DANGEROUS: {
10150                    // If a permission review is required for legacy apps we represent
10151                    // their permissions as always granted runtime ones since we need
10152                    // to keep the review required permission flag per user while an
10153                    // install permission's state is shared across all users.
10154                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10155                        // For legacy apps dangerous permissions are install time ones.
10156                        grant = GRANT_INSTALL;
10157                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10158                        // For legacy apps that became modern, install becomes runtime.
10159                        grant = GRANT_UPGRADE;
10160                    } else if (mPromoteSystemApps
10161                            && isSystemApp(ps)
10162                            && mExistingSystemPackages.contains(ps.name)) {
10163                        // For legacy system apps, install becomes runtime.
10164                        // We cannot check hasInstallPermission() for system apps since those
10165                        // permissions were granted implicitly and not persisted pre-M.
10166                        grant = GRANT_UPGRADE;
10167                    } else {
10168                        // For modern apps keep runtime permissions unchanged.
10169                        grant = GRANT_RUNTIME;
10170                    }
10171                } break;
10172
10173                case PermissionInfo.PROTECTION_SIGNATURE: {
10174                    // For all apps signature permissions are install time ones.
10175                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10176                    if (allowedSig) {
10177                        grant = GRANT_INSTALL;
10178                    }
10179                } break;
10180            }
10181
10182            if (DEBUG_INSTALL) {
10183                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10184            }
10185
10186            if (grant != GRANT_DENIED) {
10187                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10188                    // If this is an existing, non-system package, then
10189                    // we can't add any new permissions to it.
10190                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10191                        // Except...  if this is a permission that was added
10192                        // to the platform (note: need to only do this when
10193                        // updating the platform).
10194                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10195                            grant = GRANT_DENIED;
10196                        }
10197                    }
10198                }
10199
10200                switch (grant) {
10201                    case GRANT_INSTALL: {
10202                        // Revoke this as runtime permission to handle the case of
10203                        // a runtime permission being downgraded to an install one.
10204                        // Also in permission review mode we keep dangerous permissions
10205                        // for legacy apps
10206                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10207                            if (origPermissions.getRuntimePermissionState(
10208                                    bp.name, userId) != null) {
10209                                // Revoke the runtime permission and clear the flags.
10210                                origPermissions.revokeRuntimePermission(bp, userId);
10211                                origPermissions.updatePermissionFlags(bp, userId,
10212                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10213                                // If we revoked a permission permission, we have to write.
10214                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10215                                        changedRuntimePermissionUserIds, userId);
10216                            }
10217                        }
10218                        // Grant an install permission.
10219                        if (permissionsState.grantInstallPermission(bp) !=
10220                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10221                            changedInstallPermission = true;
10222                        }
10223                    } break;
10224
10225                    case GRANT_RUNTIME: {
10226                        // Grant previously granted runtime permissions.
10227                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10228                            PermissionState permissionState = origPermissions
10229                                    .getRuntimePermissionState(bp.name, userId);
10230                            int flags = permissionState != null
10231                                    ? permissionState.getFlags() : 0;
10232                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10233                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10234                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10235                                    // If we cannot put the permission as it was, we have to write.
10236                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10237                                            changedRuntimePermissionUserIds, userId);
10238                                }
10239                                // If the app supports runtime permissions no need for a review.
10240                                if (mPermissionReviewRequired
10241                                        && appSupportsRuntimePermissions
10242                                        && (flags & PackageManager
10243                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10244                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10245                                    // Since we changed the flags, we have to write.
10246                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10247                                            changedRuntimePermissionUserIds, userId);
10248                                }
10249                            } else if (mPermissionReviewRequired
10250                                    && !appSupportsRuntimePermissions) {
10251                                // For legacy apps that need a permission review, every new
10252                                // runtime permission is granted but it is pending a review.
10253                                // We also need to review only platform defined runtime
10254                                // permissions as these are the only ones the platform knows
10255                                // how to disable the API to simulate revocation as legacy
10256                                // apps don't expect to run with revoked permissions.
10257                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10258                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10259                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10260                                        // We changed the flags, hence have to write.
10261                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10262                                                changedRuntimePermissionUserIds, userId);
10263                                    }
10264                                }
10265                                if (permissionsState.grantRuntimePermission(bp, userId)
10266                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10267                                    // We changed the permission, hence have to write.
10268                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10269                                            changedRuntimePermissionUserIds, userId);
10270                                }
10271                            }
10272                            // Propagate the permission flags.
10273                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10274                        }
10275                    } break;
10276
10277                    case GRANT_UPGRADE: {
10278                        // Grant runtime permissions for a previously held install permission.
10279                        PermissionState permissionState = origPermissions
10280                                .getInstallPermissionState(bp.name);
10281                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10282
10283                        if (origPermissions.revokeInstallPermission(bp)
10284                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10285                            // We will be transferring the permission flags, so clear them.
10286                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10287                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10288                            changedInstallPermission = true;
10289                        }
10290
10291                        // If the permission is not to be promoted to runtime we ignore it and
10292                        // also its other flags as they are not applicable to install permissions.
10293                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10294                            for (int userId : currentUserIds) {
10295                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10296                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10297                                    // Transfer the permission flags.
10298                                    permissionsState.updatePermissionFlags(bp, userId,
10299                                            flags, flags);
10300                                    // If we granted the permission, we have to write.
10301                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10302                                            changedRuntimePermissionUserIds, userId);
10303                                }
10304                            }
10305                        }
10306                    } break;
10307
10308                    default: {
10309                        if (packageOfInterest == null
10310                                || packageOfInterest.equals(pkg.packageName)) {
10311                            Slog.w(TAG, "Not granting permission " + perm
10312                                    + " to package " + pkg.packageName
10313                                    + " because it was previously installed without");
10314                        }
10315                    } break;
10316                }
10317            } else {
10318                if (permissionsState.revokeInstallPermission(bp) !=
10319                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10320                    // Also drop the permission flags.
10321                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10322                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10323                    changedInstallPermission = true;
10324                    Slog.i(TAG, "Un-granting permission " + perm
10325                            + " from package " + pkg.packageName
10326                            + " (protectionLevel=" + bp.protectionLevel
10327                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10328                            + ")");
10329                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10330                    // Don't print warning for app op permissions, since it is fine for them
10331                    // not to be granted, there is a UI for the user to decide.
10332                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10333                        Slog.w(TAG, "Not granting permission " + perm
10334                                + " to package " + pkg.packageName
10335                                + " (protectionLevel=" + bp.protectionLevel
10336                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10337                                + ")");
10338                    }
10339                }
10340            }
10341        }
10342
10343        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10344                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10345            // This is the first that we have heard about this package, so the
10346            // permissions we have now selected are fixed until explicitly
10347            // changed.
10348            ps.installPermissionsFixed = true;
10349        }
10350
10351        // Persist the runtime permissions state for users with changes. If permissions
10352        // were revoked because no app in the shared user declares them we have to
10353        // write synchronously to avoid losing runtime permissions state.
10354        for (int userId : changedRuntimePermissionUserIds) {
10355            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10356        }
10357    }
10358
10359    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10360        boolean allowed = false;
10361        final int NP = PackageParser.NEW_PERMISSIONS.length;
10362        for (int ip=0; ip<NP; ip++) {
10363            final PackageParser.NewPermissionInfo npi
10364                    = PackageParser.NEW_PERMISSIONS[ip];
10365            if (npi.name.equals(perm)
10366                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10367                allowed = true;
10368                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10369                        + pkg.packageName);
10370                break;
10371            }
10372        }
10373        return allowed;
10374    }
10375
10376    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10377            BasePermission bp, PermissionsState origPermissions) {
10378        boolean allowed;
10379        allowed = (compareSignatures(
10380                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10381                        == PackageManager.SIGNATURE_MATCH)
10382                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10383                        == PackageManager.SIGNATURE_MATCH);
10384        if (!allowed && (bp.protectionLevel
10385                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10386            if (isSystemApp(pkg)) {
10387                // For updated system applications, a system permission
10388                // is granted only if it had been defined by the original application.
10389                if (pkg.isUpdatedSystemApp()) {
10390                    final PackageSetting sysPs = mSettings
10391                            .getDisabledSystemPkgLPr(pkg.packageName);
10392                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10393                        // If the original was granted this permission, we take
10394                        // that grant decision as read and propagate it to the
10395                        // update.
10396                        if (sysPs.isPrivileged()) {
10397                            allowed = true;
10398                        }
10399                    } else {
10400                        // The system apk may have been updated with an older
10401                        // version of the one on the data partition, but which
10402                        // granted a new system permission that it didn't have
10403                        // before.  In this case we do want to allow the app to
10404                        // now get the new permission if the ancestral apk is
10405                        // privileged to get it.
10406                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10407                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10408                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10409                                    allowed = true;
10410                                    break;
10411                                }
10412                            }
10413                        }
10414                        // Also if a privileged parent package on the system image or any of
10415                        // its children requested a privileged permission, the updated child
10416                        // packages can also get the permission.
10417                        if (pkg.parentPackage != null) {
10418                            final PackageSetting disabledSysParentPs = mSettings
10419                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10420                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10421                                    && disabledSysParentPs.isPrivileged()) {
10422                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10423                                    allowed = true;
10424                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10425                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10426                                    for (int i = 0; i < count; i++) {
10427                                        PackageParser.Package disabledSysChildPkg =
10428                                                disabledSysParentPs.pkg.childPackages.get(i);
10429                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10430                                                perm)) {
10431                                            allowed = true;
10432                                            break;
10433                                        }
10434                                    }
10435                                }
10436                            }
10437                        }
10438                    }
10439                } else {
10440                    allowed = isPrivilegedApp(pkg);
10441                }
10442            }
10443        }
10444        if (!allowed) {
10445            if (!allowed && (bp.protectionLevel
10446                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10447                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10448                // If this was a previously normal/dangerous permission that got moved
10449                // to a system permission as part of the runtime permission redesign, then
10450                // we still want to blindly grant it to old apps.
10451                allowed = true;
10452            }
10453            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10454                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10455                // If this permission is to be granted to the system installer and
10456                // this app is an installer, then it gets the permission.
10457                allowed = true;
10458            }
10459            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10460                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10461                // If this permission is to be granted to the system verifier and
10462                // this app is a verifier, then it gets the permission.
10463                allowed = true;
10464            }
10465            if (!allowed && (bp.protectionLevel
10466                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10467                    && isSystemApp(pkg)) {
10468                // Any pre-installed system app is allowed to get this permission.
10469                allowed = true;
10470            }
10471            if (!allowed && (bp.protectionLevel
10472                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10473                // For development permissions, a development permission
10474                // is granted only if it was already granted.
10475                allowed = origPermissions.hasInstallPermission(perm);
10476            }
10477            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10478                    && pkg.packageName.equals(mSetupWizardPackage)) {
10479                // If this permission is to be granted to the system setup wizard and
10480                // this app is a setup wizard, then it gets the permission.
10481                allowed = true;
10482            }
10483        }
10484        return allowed;
10485    }
10486
10487    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10488        final int permCount = pkg.requestedPermissions.size();
10489        for (int j = 0; j < permCount; j++) {
10490            String requestedPermission = pkg.requestedPermissions.get(j);
10491            if (permission.equals(requestedPermission)) {
10492                return true;
10493            }
10494        }
10495        return false;
10496    }
10497
10498    final class ActivityIntentResolver
10499            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10500        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10501                boolean defaultOnly, int userId) {
10502            if (!sUserManager.exists(userId)) return null;
10503            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10504            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10505        }
10506
10507        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10508                int userId) {
10509            if (!sUserManager.exists(userId)) return null;
10510            mFlags = flags;
10511            return super.queryIntent(intent, resolvedType,
10512                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10513        }
10514
10515        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10516                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10517            if (!sUserManager.exists(userId)) return null;
10518            if (packageActivities == null) {
10519                return null;
10520            }
10521            mFlags = flags;
10522            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10523            final int N = packageActivities.size();
10524            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10525                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10526
10527            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10528            for (int i = 0; i < N; ++i) {
10529                intentFilters = packageActivities.get(i).intents;
10530                if (intentFilters != null && intentFilters.size() > 0) {
10531                    PackageParser.ActivityIntentInfo[] array =
10532                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10533                    intentFilters.toArray(array);
10534                    listCut.add(array);
10535                }
10536            }
10537            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10538        }
10539
10540        /**
10541         * Finds a privileged activity that matches the specified activity names.
10542         */
10543        private PackageParser.Activity findMatchingActivity(
10544                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10545            for (PackageParser.Activity sysActivity : activityList) {
10546                if (sysActivity.info.name.equals(activityInfo.name)) {
10547                    return sysActivity;
10548                }
10549                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10550                    return sysActivity;
10551                }
10552                if (sysActivity.info.targetActivity != null) {
10553                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10554                        return sysActivity;
10555                    }
10556                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10557                        return sysActivity;
10558                    }
10559                }
10560            }
10561            return null;
10562        }
10563
10564        public class IterGenerator<E> {
10565            public Iterator<E> generate(ActivityIntentInfo info) {
10566                return null;
10567            }
10568        }
10569
10570        public class ActionIterGenerator extends IterGenerator<String> {
10571            @Override
10572            public Iterator<String> generate(ActivityIntentInfo info) {
10573                return info.actionsIterator();
10574            }
10575        }
10576
10577        public class CategoriesIterGenerator extends IterGenerator<String> {
10578            @Override
10579            public Iterator<String> generate(ActivityIntentInfo info) {
10580                return info.categoriesIterator();
10581            }
10582        }
10583
10584        public class SchemesIterGenerator extends IterGenerator<String> {
10585            @Override
10586            public Iterator<String> generate(ActivityIntentInfo info) {
10587                return info.schemesIterator();
10588            }
10589        }
10590
10591        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10592            @Override
10593            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10594                return info.authoritiesIterator();
10595            }
10596        }
10597
10598        /**
10599         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10600         * MODIFIED. Do not pass in a list that should not be changed.
10601         */
10602        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10603                IterGenerator<T> generator, Iterator<T> searchIterator) {
10604            // loop through the set of actions; every one must be found in the intent filter
10605            while (searchIterator.hasNext()) {
10606                // we must have at least one filter in the list to consider a match
10607                if (intentList.size() == 0) {
10608                    break;
10609                }
10610
10611                final T searchAction = searchIterator.next();
10612
10613                // loop through the set of intent filters
10614                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10615                while (intentIter.hasNext()) {
10616                    final ActivityIntentInfo intentInfo = intentIter.next();
10617                    boolean selectionFound = false;
10618
10619                    // loop through the intent filter's selection criteria; at least one
10620                    // of them must match the searched criteria
10621                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10622                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10623                        final T intentSelection = intentSelectionIter.next();
10624                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10625                            selectionFound = true;
10626                            break;
10627                        }
10628                    }
10629
10630                    // the selection criteria wasn't found in this filter's set; this filter
10631                    // is not a potential match
10632                    if (!selectionFound) {
10633                        intentIter.remove();
10634                    }
10635                }
10636            }
10637        }
10638
10639        private boolean isProtectedAction(ActivityIntentInfo filter) {
10640            final Iterator<String> actionsIter = filter.actionsIterator();
10641            while (actionsIter != null && actionsIter.hasNext()) {
10642                final String filterAction = actionsIter.next();
10643                if (PROTECTED_ACTIONS.contains(filterAction)) {
10644                    return true;
10645                }
10646            }
10647            return false;
10648        }
10649
10650        /**
10651         * Adjusts the priority of the given intent filter according to policy.
10652         * <p>
10653         * <ul>
10654         * <li>The priority for non privileged applications is capped to '0'</li>
10655         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10656         * <li>The priority for unbundled updates to privileged applications is capped to the
10657         *      priority defined on the system partition</li>
10658         * </ul>
10659         * <p>
10660         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10661         * allowed to obtain any priority on any action.
10662         */
10663        private void adjustPriority(
10664                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10665            // nothing to do; priority is fine as-is
10666            if (intent.getPriority() <= 0) {
10667                return;
10668            }
10669
10670            final ActivityInfo activityInfo = intent.activity.info;
10671            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10672
10673            final boolean privilegedApp =
10674                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10675            if (!privilegedApp) {
10676                // non-privileged applications can never define a priority >0
10677                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10678                        + " package: " + applicationInfo.packageName
10679                        + " activity: " + intent.activity.className
10680                        + " origPrio: " + intent.getPriority());
10681                intent.setPriority(0);
10682                return;
10683            }
10684
10685            if (systemActivities == null) {
10686                // the system package is not disabled; we're parsing the system partition
10687                if (isProtectedAction(intent)) {
10688                    if (mDeferProtectedFilters) {
10689                        // We can't deal with these just yet. No component should ever obtain a
10690                        // >0 priority for a protected actions, with ONE exception -- the setup
10691                        // wizard. The setup wizard, however, cannot be known until we're able to
10692                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10693                        // until all intent filters have been processed. Chicken, meet egg.
10694                        // Let the filter temporarily have a high priority and rectify the
10695                        // priorities after all system packages have been scanned.
10696                        mProtectedFilters.add(intent);
10697                        if (DEBUG_FILTERS) {
10698                            Slog.i(TAG, "Protected action; save for later;"
10699                                    + " package: " + applicationInfo.packageName
10700                                    + " activity: " + intent.activity.className
10701                                    + " origPrio: " + intent.getPriority());
10702                        }
10703                        return;
10704                    } else {
10705                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10706                            Slog.i(TAG, "No setup wizard;"
10707                                + " All protected intents capped to priority 0");
10708                        }
10709                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10710                            if (DEBUG_FILTERS) {
10711                                Slog.i(TAG, "Found setup wizard;"
10712                                    + " allow priority " + intent.getPriority() + ";"
10713                                    + " package: " + intent.activity.info.packageName
10714                                    + " activity: " + intent.activity.className
10715                                    + " priority: " + intent.getPriority());
10716                            }
10717                            // setup wizard gets whatever it wants
10718                            return;
10719                        }
10720                        Slog.w(TAG, "Protected action; cap priority to 0;"
10721                                + " package: " + intent.activity.info.packageName
10722                                + " activity: " + intent.activity.className
10723                                + " origPrio: " + intent.getPriority());
10724                        intent.setPriority(0);
10725                        return;
10726                    }
10727                }
10728                // privileged apps on the system image get whatever priority they request
10729                return;
10730            }
10731
10732            // privileged app unbundled update ... try to find the same activity
10733            final PackageParser.Activity foundActivity =
10734                    findMatchingActivity(systemActivities, activityInfo);
10735            if (foundActivity == null) {
10736                // this is a new activity; it cannot obtain >0 priority
10737                if (DEBUG_FILTERS) {
10738                    Slog.i(TAG, "New activity; cap priority to 0;"
10739                            + " package: " + applicationInfo.packageName
10740                            + " activity: " + intent.activity.className
10741                            + " origPrio: " + intent.getPriority());
10742                }
10743                intent.setPriority(0);
10744                return;
10745            }
10746
10747            // found activity, now check for filter equivalence
10748
10749            // a shallow copy is enough; we modify the list, not its contents
10750            final List<ActivityIntentInfo> intentListCopy =
10751                    new ArrayList<>(foundActivity.intents);
10752            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10753
10754            // find matching action subsets
10755            final Iterator<String> actionsIterator = intent.actionsIterator();
10756            if (actionsIterator != null) {
10757                getIntentListSubset(
10758                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10759                if (intentListCopy.size() == 0) {
10760                    // no more intents to match; we're not equivalent
10761                    if (DEBUG_FILTERS) {
10762                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10763                                + " package: " + applicationInfo.packageName
10764                                + " activity: " + intent.activity.className
10765                                + " origPrio: " + intent.getPriority());
10766                    }
10767                    intent.setPriority(0);
10768                    return;
10769                }
10770            }
10771
10772            // find matching category subsets
10773            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10774            if (categoriesIterator != null) {
10775                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10776                        categoriesIterator);
10777                if (intentListCopy.size() == 0) {
10778                    // no more intents to match; we're not equivalent
10779                    if (DEBUG_FILTERS) {
10780                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10781                                + " package: " + applicationInfo.packageName
10782                                + " activity: " + intent.activity.className
10783                                + " origPrio: " + intent.getPriority());
10784                    }
10785                    intent.setPriority(0);
10786                    return;
10787                }
10788            }
10789
10790            // find matching schemes subsets
10791            final Iterator<String> schemesIterator = intent.schemesIterator();
10792            if (schemesIterator != null) {
10793                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10794                        schemesIterator);
10795                if (intentListCopy.size() == 0) {
10796                    // no more intents to match; we're not equivalent
10797                    if (DEBUG_FILTERS) {
10798                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10799                                + " package: " + applicationInfo.packageName
10800                                + " activity: " + intent.activity.className
10801                                + " origPrio: " + intent.getPriority());
10802                    }
10803                    intent.setPriority(0);
10804                    return;
10805                }
10806            }
10807
10808            // find matching authorities subsets
10809            final Iterator<IntentFilter.AuthorityEntry>
10810                    authoritiesIterator = intent.authoritiesIterator();
10811            if (authoritiesIterator != null) {
10812                getIntentListSubset(intentListCopy,
10813                        new AuthoritiesIterGenerator(),
10814                        authoritiesIterator);
10815                if (intentListCopy.size() == 0) {
10816                    // no more intents to match; we're not equivalent
10817                    if (DEBUG_FILTERS) {
10818                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10819                                + " package: " + applicationInfo.packageName
10820                                + " activity: " + intent.activity.className
10821                                + " origPrio: " + intent.getPriority());
10822                    }
10823                    intent.setPriority(0);
10824                    return;
10825                }
10826            }
10827
10828            // we found matching filter(s); app gets the max priority of all intents
10829            int cappedPriority = 0;
10830            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10831                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10832            }
10833            if (intent.getPriority() > cappedPriority) {
10834                if (DEBUG_FILTERS) {
10835                    Slog.i(TAG, "Found matching filter(s);"
10836                            + " cap priority to " + cappedPriority + ";"
10837                            + " package: " + applicationInfo.packageName
10838                            + " activity: " + intent.activity.className
10839                            + " origPrio: " + intent.getPriority());
10840                }
10841                intent.setPriority(cappedPriority);
10842                return;
10843            }
10844            // all this for nothing; the requested priority was <= what was on the system
10845        }
10846
10847        public final void addActivity(PackageParser.Activity a, String type) {
10848            mActivities.put(a.getComponentName(), a);
10849            if (DEBUG_SHOW_INFO)
10850                Log.v(
10851                TAG, "  " + type + " " +
10852                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10853            if (DEBUG_SHOW_INFO)
10854                Log.v(TAG, "    Class=" + a.info.name);
10855            final int NI = a.intents.size();
10856            for (int j=0; j<NI; j++) {
10857                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10858                if ("activity".equals(type)) {
10859                    final PackageSetting ps =
10860                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10861                    final List<PackageParser.Activity> systemActivities =
10862                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10863                    adjustPriority(systemActivities, intent);
10864                }
10865                if (DEBUG_SHOW_INFO) {
10866                    Log.v(TAG, "    IntentFilter:");
10867                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10868                }
10869                if (!intent.debugCheck()) {
10870                    Log.w(TAG, "==> For Activity " + a.info.name);
10871                }
10872                addFilter(intent);
10873            }
10874        }
10875
10876        public final void removeActivity(PackageParser.Activity a, String type) {
10877            mActivities.remove(a.getComponentName());
10878            if (DEBUG_SHOW_INFO) {
10879                Log.v(TAG, "  " + type + " "
10880                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10881                                : a.info.name) + ":");
10882                Log.v(TAG, "    Class=" + a.info.name);
10883            }
10884            final int NI = a.intents.size();
10885            for (int j=0; j<NI; j++) {
10886                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10887                if (DEBUG_SHOW_INFO) {
10888                    Log.v(TAG, "    IntentFilter:");
10889                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10890                }
10891                removeFilter(intent);
10892            }
10893        }
10894
10895        @Override
10896        protected boolean allowFilterResult(
10897                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10898            ActivityInfo filterAi = filter.activity.info;
10899            for (int i=dest.size()-1; i>=0; i--) {
10900                ActivityInfo destAi = dest.get(i).activityInfo;
10901                if (destAi.name == filterAi.name
10902                        && destAi.packageName == filterAi.packageName) {
10903                    return false;
10904                }
10905            }
10906            return true;
10907        }
10908
10909        @Override
10910        protected ActivityIntentInfo[] newArray(int size) {
10911            return new ActivityIntentInfo[size];
10912        }
10913
10914        @Override
10915        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10916            if (!sUserManager.exists(userId)) return true;
10917            PackageParser.Package p = filter.activity.owner;
10918            if (p != null) {
10919                PackageSetting ps = (PackageSetting)p.mExtras;
10920                if (ps != null) {
10921                    // System apps are never considered stopped for purposes of
10922                    // filtering, because there may be no way for the user to
10923                    // actually re-launch them.
10924                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10925                            && ps.getStopped(userId);
10926                }
10927            }
10928            return false;
10929        }
10930
10931        @Override
10932        protected boolean isPackageForFilter(String packageName,
10933                PackageParser.ActivityIntentInfo info) {
10934            return packageName.equals(info.activity.owner.packageName);
10935        }
10936
10937        @Override
10938        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10939                int match, int userId) {
10940            if (!sUserManager.exists(userId)) return null;
10941            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10942                return null;
10943            }
10944            final PackageParser.Activity activity = info.activity;
10945            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10946            if (ps == null) {
10947                return null;
10948            }
10949            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10950                    ps.readUserState(userId), userId);
10951            if (ai == null) {
10952                return null;
10953            }
10954            final ResolveInfo res = new ResolveInfo();
10955            res.activityInfo = ai;
10956            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10957                res.filter = info;
10958            }
10959            if (info != null) {
10960                res.handleAllWebDataURI = info.handleAllWebDataURI();
10961            }
10962            res.priority = info.getPriority();
10963            res.preferredOrder = activity.owner.mPreferredOrder;
10964            //System.out.println("Result: " + res.activityInfo.className +
10965            //                   " = " + res.priority);
10966            res.match = match;
10967            res.isDefault = info.hasDefault;
10968            res.labelRes = info.labelRes;
10969            res.nonLocalizedLabel = info.nonLocalizedLabel;
10970            if (userNeedsBadging(userId)) {
10971                res.noResourceId = true;
10972            } else {
10973                res.icon = info.icon;
10974            }
10975            res.iconResourceId = info.icon;
10976            res.system = res.activityInfo.applicationInfo.isSystemApp();
10977            return res;
10978        }
10979
10980        @Override
10981        protected void sortResults(List<ResolveInfo> results) {
10982            Collections.sort(results, mResolvePrioritySorter);
10983        }
10984
10985        @Override
10986        protected void dumpFilter(PrintWriter out, String prefix,
10987                PackageParser.ActivityIntentInfo filter) {
10988            out.print(prefix); out.print(
10989                    Integer.toHexString(System.identityHashCode(filter.activity)));
10990                    out.print(' ');
10991                    filter.activity.printComponentShortName(out);
10992                    out.print(" filter ");
10993                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10994        }
10995
10996        @Override
10997        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10998            return filter.activity;
10999        }
11000
11001        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11002            PackageParser.Activity activity = (PackageParser.Activity)label;
11003            out.print(prefix); out.print(
11004                    Integer.toHexString(System.identityHashCode(activity)));
11005                    out.print(' ');
11006                    activity.printComponentShortName(out);
11007            if (count > 1) {
11008                out.print(" ("); out.print(count); out.print(" filters)");
11009            }
11010            out.println();
11011        }
11012
11013        // Keys are String (activity class name), values are Activity.
11014        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11015                = new ArrayMap<ComponentName, PackageParser.Activity>();
11016        private int mFlags;
11017    }
11018
11019    private final class ServiceIntentResolver
11020            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11021        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11022                boolean defaultOnly, int userId) {
11023            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11024            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11025        }
11026
11027        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11028                int userId) {
11029            if (!sUserManager.exists(userId)) return null;
11030            mFlags = flags;
11031            return super.queryIntent(intent, resolvedType,
11032                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11033        }
11034
11035        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11036                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11037            if (!sUserManager.exists(userId)) return null;
11038            if (packageServices == null) {
11039                return null;
11040            }
11041            mFlags = flags;
11042            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11043            final int N = packageServices.size();
11044            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11045                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11046
11047            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11048            for (int i = 0; i < N; ++i) {
11049                intentFilters = packageServices.get(i).intents;
11050                if (intentFilters != null && intentFilters.size() > 0) {
11051                    PackageParser.ServiceIntentInfo[] array =
11052                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11053                    intentFilters.toArray(array);
11054                    listCut.add(array);
11055                }
11056            }
11057            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11058        }
11059
11060        public final void addService(PackageParser.Service s) {
11061            mServices.put(s.getComponentName(), s);
11062            if (DEBUG_SHOW_INFO) {
11063                Log.v(TAG, "  "
11064                        + (s.info.nonLocalizedLabel != null
11065                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11066                Log.v(TAG, "    Class=" + s.info.name);
11067            }
11068            final int NI = s.intents.size();
11069            int j;
11070            for (j=0; j<NI; j++) {
11071                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11072                if (DEBUG_SHOW_INFO) {
11073                    Log.v(TAG, "    IntentFilter:");
11074                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11075                }
11076                if (!intent.debugCheck()) {
11077                    Log.w(TAG, "==> For Service " + s.info.name);
11078                }
11079                addFilter(intent);
11080            }
11081        }
11082
11083        public final void removeService(PackageParser.Service s) {
11084            mServices.remove(s.getComponentName());
11085            if (DEBUG_SHOW_INFO) {
11086                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11087                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11088                Log.v(TAG, "    Class=" + s.info.name);
11089            }
11090            final int NI = s.intents.size();
11091            int j;
11092            for (j=0; j<NI; j++) {
11093                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11094                if (DEBUG_SHOW_INFO) {
11095                    Log.v(TAG, "    IntentFilter:");
11096                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11097                }
11098                removeFilter(intent);
11099            }
11100        }
11101
11102        @Override
11103        protected boolean allowFilterResult(
11104                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11105            ServiceInfo filterSi = filter.service.info;
11106            for (int i=dest.size()-1; i>=0; i--) {
11107                ServiceInfo destAi = dest.get(i).serviceInfo;
11108                if (destAi.name == filterSi.name
11109                        && destAi.packageName == filterSi.packageName) {
11110                    return false;
11111                }
11112            }
11113            return true;
11114        }
11115
11116        @Override
11117        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11118            return new PackageParser.ServiceIntentInfo[size];
11119        }
11120
11121        @Override
11122        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11123            if (!sUserManager.exists(userId)) return true;
11124            PackageParser.Package p = filter.service.owner;
11125            if (p != null) {
11126                PackageSetting ps = (PackageSetting)p.mExtras;
11127                if (ps != null) {
11128                    // System apps are never considered stopped for purposes of
11129                    // filtering, because there may be no way for the user to
11130                    // actually re-launch them.
11131                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11132                            && ps.getStopped(userId);
11133                }
11134            }
11135            return false;
11136        }
11137
11138        @Override
11139        protected boolean isPackageForFilter(String packageName,
11140                PackageParser.ServiceIntentInfo info) {
11141            return packageName.equals(info.service.owner.packageName);
11142        }
11143
11144        @Override
11145        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11146                int match, int userId) {
11147            if (!sUserManager.exists(userId)) return null;
11148            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11149            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11150                return null;
11151            }
11152            final PackageParser.Service service = info.service;
11153            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11154            if (ps == null) {
11155                return null;
11156            }
11157            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11158                    ps.readUserState(userId), userId);
11159            if (si == null) {
11160                return null;
11161            }
11162            final ResolveInfo res = new ResolveInfo();
11163            res.serviceInfo = si;
11164            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11165                res.filter = filter;
11166            }
11167            res.priority = info.getPriority();
11168            res.preferredOrder = service.owner.mPreferredOrder;
11169            res.match = match;
11170            res.isDefault = info.hasDefault;
11171            res.labelRes = info.labelRes;
11172            res.nonLocalizedLabel = info.nonLocalizedLabel;
11173            res.icon = info.icon;
11174            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11175            return res;
11176        }
11177
11178        @Override
11179        protected void sortResults(List<ResolveInfo> results) {
11180            Collections.sort(results, mResolvePrioritySorter);
11181        }
11182
11183        @Override
11184        protected void dumpFilter(PrintWriter out, String prefix,
11185                PackageParser.ServiceIntentInfo filter) {
11186            out.print(prefix); out.print(
11187                    Integer.toHexString(System.identityHashCode(filter.service)));
11188                    out.print(' ');
11189                    filter.service.printComponentShortName(out);
11190                    out.print(" filter ");
11191                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11192        }
11193
11194        @Override
11195        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11196            return filter.service;
11197        }
11198
11199        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11200            PackageParser.Service service = (PackageParser.Service)label;
11201            out.print(prefix); out.print(
11202                    Integer.toHexString(System.identityHashCode(service)));
11203                    out.print(' ');
11204                    service.printComponentShortName(out);
11205            if (count > 1) {
11206                out.print(" ("); out.print(count); out.print(" filters)");
11207            }
11208            out.println();
11209        }
11210
11211//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11212//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11213//            final List<ResolveInfo> retList = Lists.newArrayList();
11214//            while (i.hasNext()) {
11215//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11216//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11217//                    retList.add(resolveInfo);
11218//                }
11219//            }
11220//            return retList;
11221//        }
11222
11223        // Keys are String (activity class name), values are Activity.
11224        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11225                = new ArrayMap<ComponentName, PackageParser.Service>();
11226        private int mFlags;
11227    };
11228
11229    private final class ProviderIntentResolver
11230            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11231        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11232                boolean defaultOnly, int userId) {
11233            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11234            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11235        }
11236
11237        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11238                int userId) {
11239            if (!sUserManager.exists(userId))
11240                return null;
11241            mFlags = flags;
11242            return super.queryIntent(intent, resolvedType,
11243                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11244        }
11245
11246        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11247                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11248            if (!sUserManager.exists(userId))
11249                return null;
11250            if (packageProviders == null) {
11251                return null;
11252            }
11253            mFlags = flags;
11254            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11255            final int N = packageProviders.size();
11256            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11257                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11258
11259            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11260            for (int i = 0; i < N; ++i) {
11261                intentFilters = packageProviders.get(i).intents;
11262                if (intentFilters != null && intentFilters.size() > 0) {
11263                    PackageParser.ProviderIntentInfo[] array =
11264                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11265                    intentFilters.toArray(array);
11266                    listCut.add(array);
11267                }
11268            }
11269            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11270        }
11271
11272        public final void addProvider(PackageParser.Provider p) {
11273            if (mProviders.containsKey(p.getComponentName())) {
11274                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11275                return;
11276            }
11277
11278            mProviders.put(p.getComponentName(), p);
11279            if (DEBUG_SHOW_INFO) {
11280                Log.v(TAG, "  "
11281                        + (p.info.nonLocalizedLabel != null
11282                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11283                Log.v(TAG, "    Class=" + p.info.name);
11284            }
11285            final int NI = p.intents.size();
11286            int j;
11287            for (j = 0; j < NI; j++) {
11288                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11289                if (DEBUG_SHOW_INFO) {
11290                    Log.v(TAG, "    IntentFilter:");
11291                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11292                }
11293                if (!intent.debugCheck()) {
11294                    Log.w(TAG, "==> For Provider " + p.info.name);
11295                }
11296                addFilter(intent);
11297            }
11298        }
11299
11300        public final void removeProvider(PackageParser.Provider p) {
11301            mProviders.remove(p.getComponentName());
11302            if (DEBUG_SHOW_INFO) {
11303                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11304                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11305                Log.v(TAG, "    Class=" + p.info.name);
11306            }
11307            final int NI = p.intents.size();
11308            int j;
11309            for (j = 0; j < NI; j++) {
11310                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11311                if (DEBUG_SHOW_INFO) {
11312                    Log.v(TAG, "    IntentFilter:");
11313                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11314                }
11315                removeFilter(intent);
11316            }
11317        }
11318
11319        @Override
11320        protected boolean allowFilterResult(
11321                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11322            ProviderInfo filterPi = filter.provider.info;
11323            for (int i = dest.size() - 1; i >= 0; i--) {
11324                ProviderInfo destPi = dest.get(i).providerInfo;
11325                if (destPi.name == filterPi.name
11326                        && destPi.packageName == filterPi.packageName) {
11327                    return false;
11328                }
11329            }
11330            return true;
11331        }
11332
11333        @Override
11334        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11335            return new PackageParser.ProviderIntentInfo[size];
11336        }
11337
11338        @Override
11339        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11340            if (!sUserManager.exists(userId))
11341                return true;
11342            PackageParser.Package p = filter.provider.owner;
11343            if (p != null) {
11344                PackageSetting ps = (PackageSetting) p.mExtras;
11345                if (ps != null) {
11346                    // System apps are never considered stopped for purposes of
11347                    // filtering, because there may be no way for the user to
11348                    // actually re-launch them.
11349                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11350                            && ps.getStopped(userId);
11351                }
11352            }
11353            return false;
11354        }
11355
11356        @Override
11357        protected boolean isPackageForFilter(String packageName,
11358                PackageParser.ProviderIntentInfo info) {
11359            return packageName.equals(info.provider.owner.packageName);
11360        }
11361
11362        @Override
11363        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11364                int match, int userId) {
11365            if (!sUserManager.exists(userId))
11366                return null;
11367            final PackageParser.ProviderIntentInfo info = filter;
11368            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11369                return null;
11370            }
11371            final PackageParser.Provider provider = info.provider;
11372            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11373            if (ps == null) {
11374                return null;
11375            }
11376            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11377                    ps.readUserState(userId), userId);
11378            if (pi == null) {
11379                return null;
11380            }
11381            final ResolveInfo res = new ResolveInfo();
11382            res.providerInfo = pi;
11383            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11384                res.filter = filter;
11385            }
11386            res.priority = info.getPriority();
11387            res.preferredOrder = provider.owner.mPreferredOrder;
11388            res.match = match;
11389            res.isDefault = info.hasDefault;
11390            res.labelRes = info.labelRes;
11391            res.nonLocalizedLabel = info.nonLocalizedLabel;
11392            res.icon = info.icon;
11393            res.system = res.providerInfo.applicationInfo.isSystemApp();
11394            return res;
11395        }
11396
11397        @Override
11398        protected void sortResults(List<ResolveInfo> results) {
11399            Collections.sort(results, mResolvePrioritySorter);
11400        }
11401
11402        @Override
11403        protected void dumpFilter(PrintWriter out, String prefix,
11404                PackageParser.ProviderIntentInfo filter) {
11405            out.print(prefix);
11406            out.print(
11407                    Integer.toHexString(System.identityHashCode(filter.provider)));
11408            out.print(' ');
11409            filter.provider.printComponentShortName(out);
11410            out.print(" filter ");
11411            out.println(Integer.toHexString(System.identityHashCode(filter)));
11412        }
11413
11414        @Override
11415        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11416            return filter.provider;
11417        }
11418
11419        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11420            PackageParser.Provider provider = (PackageParser.Provider)label;
11421            out.print(prefix); out.print(
11422                    Integer.toHexString(System.identityHashCode(provider)));
11423                    out.print(' ');
11424                    provider.printComponentShortName(out);
11425            if (count > 1) {
11426                out.print(" ("); out.print(count); out.print(" filters)");
11427            }
11428            out.println();
11429        }
11430
11431        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11432                = new ArrayMap<ComponentName, PackageParser.Provider>();
11433        private int mFlags;
11434    }
11435
11436    private static final class EphemeralIntentResolver
11437            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11438        /**
11439         * The result that has the highest defined order. Ordering applies on a
11440         * per-package basis. Mapping is from package name to Pair of order and
11441         * EphemeralResolveInfo.
11442         * <p>
11443         * NOTE: This is implemented as a field variable for convenience and efficiency.
11444         * By having a field variable, we're able to track filter ordering as soon as
11445         * a non-zero order is defined. Otherwise, multiple loops across the result set
11446         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11447         * this needs to be contained entirely within {@link #filterResults()}.
11448         */
11449        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11450
11451        @Override
11452        protected EphemeralResolveIntentInfo[] newArray(int size) {
11453            return new EphemeralResolveIntentInfo[size];
11454        }
11455
11456        @Override
11457        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11458            return true;
11459        }
11460
11461        @Override
11462        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11463                int userId) {
11464            if (!sUserManager.exists(userId)) {
11465                return null;
11466            }
11467            final String packageName = info.getEphemeralResolveInfo().getPackageName();
11468            final Integer order = info.getOrder();
11469            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11470                    mOrderResult.get(packageName);
11471            // ordering is enabled and this item's order isn't high enough
11472            if (lastOrderResult != null && lastOrderResult.first >= order) {
11473                return null;
11474            }
11475            final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11476            if (order > 0) {
11477                // non-zero order, enable ordering
11478                mOrderResult.put(packageName, new Pair<>(order, res));
11479            }
11480            return res;
11481        }
11482
11483        @Override
11484        protected void filterResults(List<EphemeralResolveInfo> results) {
11485            // only do work if ordering is enabled [most of the time it won't be]
11486            if (mOrderResult.size() == 0) {
11487                return;
11488            }
11489            int resultSize = results.size();
11490            for (int i = 0; i < resultSize; i++) {
11491                final EphemeralResolveInfo info = results.get(i);
11492                final String packageName = info.getPackageName();
11493                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11494                if (savedInfo == null) {
11495                    // package doesn't having ordering
11496                    continue;
11497                }
11498                if (savedInfo.second == info) {
11499                    // circled back to the highest ordered item; remove from order list
11500                    mOrderResult.remove(savedInfo);
11501                    if (mOrderResult.size() == 0) {
11502                        // no more ordered items
11503                        break;
11504                    }
11505                    continue;
11506                }
11507                // item has a worse order, remove it from the result list
11508                results.remove(i);
11509                resultSize--;
11510                i--;
11511            }
11512        }
11513    }
11514
11515    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11516            new Comparator<ResolveInfo>() {
11517        public int compare(ResolveInfo r1, ResolveInfo r2) {
11518            int v1 = r1.priority;
11519            int v2 = r2.priority;
11520            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11521            if (v1 != v2) {
11522                return (v1 > v2) ? -1 : 1;
11523            }
11524            v1 = r1.preferredOrder;
11525            v2 = r2.preferredOrder;
11526            if (v1 != v2) {
11527                return (v1 > v2) ? -1 : 1;
11528            }
11529            if (r1.isDefault != r2.isDefault) {
11530                return r1.isDefault ? -1 : 1;
11531            }
11532            v1 = r1.match;
11533            v2 = r2.match;
11534            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11535            if (v1 != v2) {
11536                return (v1 > v2) ? -1 : 1;
11537            }
11538            if (r1.system != r2.system) {
11539                return r1.system ? -1 : 1;
11540            }
11541            if (r1.activityInfo != null) {
11542                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11543            }
11544            if (r1.serviceInfo != null) {
11545                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11546            }
11547            if (r1.providerInfo != null) {
11548                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11549            }
11550            return 0;
11551        }
11552    };
11553
11554    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11555            new Comparator<ProviderInfo>() {
11556        public int compare(ProviderInfo p1, ProviderInfo p2) {
11557            final int v1 = p1.initOrder;
11558            final int v2 = p2.initOrder;
11559            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11560        }
11561    };
11562
11563    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11564            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11565            final int[] userIds) {
11566        mHandler.post(new Runnable() {
11567            @Override
11568            public void run() {
11569                try {
11570                    final IActivityManager am = ActivityManagerNative.getDefault();
11571                    if (am == null) return;
11572                    final int[] resolvedUserIds;
11573                    if (userIds == null) {
11574                        resolvedUserIds = am.getRunningUserIds();
11575                    } else {
11576                        resolvedUserIds = userIds;
11577                    }
11578                    for (int id : resolvedUserIds) {
11579                        final Intent intent = new Intent(action,
11580                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11581                        if (extras != null) {
11582                            intent.putExtras(extras);
11583                        }
11584                        if (targetPkg != null) {
11585                            intent.setPackage(targetPkg);
11586                        }
11587                        // Modify the UID when posting to other users
11588                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11589                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11590                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11591                            intent.putExtra(Intent.EXTRA_UID, uid);
11592                        }
11593                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11594                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11595                        if (DEBUG_BROADCASTS) {
11596                            RuntimeException here = new RuntimeException("here");
11597                            here.fillInStackTrace();
11598                            Slog.d(TAG, "Sending to user " + id + ": "
11599                                    + intent.toShortString(false, true, false, false)
11600                                    + " " + intent.getExtras(), here);
11601                        }
11602                        am.broadcastIntent(null, intent, null, finishedReceiver,
11603                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11604                                null, finishedReceiver != null, false, id);
11605                    }
11606                } catch (RemoteException ex) {
11607                }
11608            }
11609        });
11610    }
11611
11612    /**
11613     * Check if the external storage media is available. This is true if there
11614     * is a mounted external storage medium or if the external storage is
11615     * emulated.
11616     */
11617    private boolean isExternalMediaAvailable() {
11618        return mMediaMounted || Environment.isExternalStorageEmulated();
11619    }
11620
11621    @Override
11622    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11623        // writer
11624        synchronized (mPackages) {
11625            if (!isExternalMediaAvailable()) {
11626                // If the external storage is no longer mounted at this point,
11627                // the caller may not have been able to delete all of this
11628                // packages files and can not delete any more.  Bail.
11629                return null;
11630            }
11631            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11632            if (lastPackage != null) {
11633                pkgs.remove(lastPackage);
11634            }
11635            if (pkgs.size() > 0) {
11636                return pkgs.get(0);
11637            }
11638        }
11639        return null;
11640    }
11641
11642    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11643        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11644                userId, andCode ? 1 : 0, packageName);
11645        if (mSystemReady) {
11646            msg.sendToTarget();
11647        } else {
11648            if (mPostSystemReadyMessages == null) {
11649                mPostSystemReadyMessages = new ArrayList<>();
11650            }
11651            mPostSystemReadyMessages.add(msg);
11652        }
11653    }
11654
11655    void startCleaningPackages() {
11656        // reader
11657        if (!isExternalMediaAvailable()) {
11658            return;
11659        }
11660        synchronized (mPackages) {
11661            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11662                return;
11663            }
11664        }
11665        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11666        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11667        IActivityManager am = ActivityManagerNative.getDefault();
11668        if (am != null) {
11669            try {
11670                am.startService(null, intent, null, mContext.getOpPackageName(),
11671                        UserHandle.USER_SYSTEM);
11672            } catch (RemoteException e) {
11673            }
11674        }
11675    }
11676
11677    @Override
11678    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11679            int installFlags, String installerPackageName, int userId) {
11680        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11681
11682        final int callingUid = Binder.getCallingUid();
11683        enforceCrossUserPermission(callingUid, userId,
11684                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11685
11686        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11687            try {
11688                if (observer != null) {
11689                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11690                }
11691            } catch (RemoteException re) {
11692            }
11693            return;
11694        }
11695
11696        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11697            installFlags |= PackageManager.INSTALL_FROM_ADB;
11698
11699        } else {
11700            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11701            // about installerPackageName.
11702
11703            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11704            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11705        }
11706
11707        UserHandle user;
11708        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11709            user = UserHandle.ALL;
11710        } else {
11711            user = new UserHandle(userId);
11712        }
11713
11714        // Only system components can circumvent runtime permissions when installing.
11715        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11716                && mContext.checkCallingOrSelfPermission(Manifest.permission
11717                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11718            throw new SecurityException("You need the "
11719                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11720                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11721        }
11722
11723        final File originFile = new File(originPath);
11724        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11725
11726        final Message msg = mHandler.obtainMessage(INIT_COPY);
11727        final VerificationInfo verificationInfo = new VerificationInfo(
11728                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11729        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11730                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11731                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11732                null /*certificates*/);
11733        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11734        msg.obj = params;
11735
11736        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11737                System.identityHashCode(msg.obj));
11738        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11739                System.identityHashCode(msg.obj));
11740
11741        mHandler.sendMessage(msg);
11742    }
11743
11744    void installStage(String packageName, File stagedDir, String stagedCid,
11745            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11746            String installerPackageName, int installerUid, UserHandle user,
11747            Certificate[][] certificates) {
11748        if (DEBUG_EPHEMERAL) {
11749            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11750                Slog.d(TAG, "Ephemeral install of " + packageName);
11751            }
11752        }
11753        final VerificationInfo verificationInfo = new VerificationInfo(
11754                sessionParams.originatingUri, sessionParams.referrerUri,
11755                sessionParams.originatingUid, installerUid);
11756
11757        final OriginInfo origin;
11758        if (stagedDir != null) {
11759            origin = OriginInfo.fromStagedFile(stagedDir);
11760        } else {
11761            origin = OriginInfo.fromStagedContainer(stagedCid);
11762        }
11763
11764        final Message msg = mHandler.obtainMessage(INIT_COPY);
11765        final InstallParams params = new InstallParams(origin, null, observer,
11766                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11767                verificationInfo, user, sessionParams.abiOverride,
11768                sessionParams.grantedRuntimePermissions, certificates);
11769        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11770        msg.obj = params;
11771
11772        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11773                System.identityHashCode(msg.obj));
11774        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11775                System.identityHashCode(msg.obj));
11776
11777        mHandler.sendMessage(msg);
11778    }
11779
11780    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11781            int userId) {
11782        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11783        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11784    }
11785
11786    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11787            int appId, int... userIds) {
11788        if (ArrayUtils.isEmpty(userIds)) {
11789            return;
11790        }
11791        Bundle extras = new Bundle(1);
11792        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11793        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11794
11795        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11796                packageName, extras, 0, null, null, userIds);
11797        if (isSystem) {
11798            mHandler.post(() -> {
11799                        for (int userId : userIds) {
11800                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
11801                        }
11802                    }
11803            );
11804        }
11805    }
11806
11807    /**
11808     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
11809     * automatically without needing an explicit launch.
11810     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
11811     */
11812    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
11813        // If user is not running, the app didn't miss any broadcast
11814        if (!mUserManagerInternal.isUserRunning(userId)) {
11815            return;
11816        }
11817        final IActivityManager am = ActivityManagerNative.getDefault();
11818        try {
11819            // Deliver LOCKED_BOOT_COMPLETED first
11820            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
11821                    .setPackage(packageName);
11822            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
11823            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
11824                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11825
11826            // Deliver BOOT_COMPLETED only if user is unlocked
11827            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
11828                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
11829                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
11830                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11831            }
11832        } catch (RemoteException e) {
11833            throw e.rethrowFromSystemServer();
11834        }
11835    }
11836
11837    @Override
11838    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11839            int userId) {
11840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11841        PackageSetting pkgSetting;
11842        final int uid = Binder.getCallingUid();
11843        enforceCrossUserPermission(uid, userId,
11844                true /* requireFullPermission */, true /* checkShell */,
11845                "setApplicationHiddenSetting for user " + userId);
11846
11847        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11848            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11849            return false;
11850        }
11851
11852        long callingId = Binder.clearCallingIdentity();
11853        try {
11854            boolean sendAdded = false;
11855            boolean sendRemoved = false;
11856            // writer
11857            synchronized (mPackages) {
11858                pkgSetting = mSettings.mPackages.get(packageName);
11859                if (pkgSetting == null) {
11860                    return false;
11861                }
11862                // Do not allow "android" is being disabled
11863                if ("android".equals(packageName)) {
11864                    Slog.w(TAG, "Cannot hide package: android");
11865                    return false;
11866                }
11867                // Only allow protected packages to hide themselves.
11868                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11869                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11870                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11871                    return false;
11872                }
11873
11874                if (pkgSetting.getHidden(userId) != hidden) {
11875                    pkgSetting.setHidden(hidden, userId);
11876                    mSettings.writePackageRestrictionsLPr(userId);
11877                    if (hidden) {
11878                        sendRemoved = true;
11879                    } else {
11880                        sendAdded = true;
11881                    }
11882                }
11883            }
11884            if (sendAdded) {
11885                sendPackageAddedForUser(packageName, pkgSetting, userId);
11886                return true;
11887            }
11888            if (sendRemoved) {
11889                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11890                        "hiding pkg");
11891                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11892                return true;
11893            }
11894        } finally {
11895            Binder.restoreCallingIdentity(callingId);
11896        }
11897        return false;
11898    }
11899
11900    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11901            int userId) {
11902        final PackageRemovedInfo info = new PackageRemovedInfo();
11903        info.removedPackage = packageName;
11904        info.removedUsers = new int[] {userId};
11905        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11906        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11907    }
11908
11909    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11910        if (pkgList.length > 0) {
11911            Bundle extras = new Bundle(1);
11912            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11913
11914            sendPackageBroadcast(
11915                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11916                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11917                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11918                    new int[] {userId});
11919        }
11920    }
11921
11922    /**
11923     * Returns true if application is not found or there was an error. Otherwise it returns
11924     * the hidden state of the package for the given user.
11925     */
11926    @Override
11927    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11929        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11930                true /* requireFullPermission */, false /* checkShell */,
11931                "getApplicationHidden for user " + userId);
11932        PackageSetting pkgSetting;
11933        long callingId = Binder.clearCallingIdentity();
11934        try {
11935            // writer
11936            synchronized (mPackages) {
11937                pkgSetting = mSettings.mPackages.get(packageName);
11938                if (pkgSetting == null) {
11939                    return true;
11940                }
11941                return pkgSetting.getHidden(userId);
11942            }
11943        } finally {
11944            Binder.restoreCallingIdentity(callingId);
11945        }
11946    }
11947
11948    /**
11949     * @hide
11950     */
11951    @Override
11952    public int installExistingPackageAsUser(String packageName, int userId) {
11953        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11954                null);
11955        PackageSetting pkgSetting;
11956        final int uid = Binder.getCallingUid();
11957        enforceCrossUserPermission(uid, userId,
11958                true /* requireFullPermission */, true /* checkShell */,
11959                "installExistingPackage for user " + userId);
11960        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11961            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11962        }
11963
11964        long callingId = Binder.clearCallingIdentity();
11965        try {
11966            boolean installed = false;
11967
11968            // writer
11969            synchronized (mPackages) {
11970                pkgSetting = mSettings.mPackages.get(packageName);
11971                if (pkgSetting == null) {
11972                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11973                }
11974                if (!pkgSetting.getInstalled(userId)) {
11975                    pkgSetting.setInstalled(true, userId);
11976                    pkgSetting.setHidden(false, userId);
11977                    mSettings.writePackageRestrictionsLPr(userId);
11978                    installed = true;
11979                }
11980            }
11981
11982            if (installed) {
11983                if (pkgSetting.pkg != null) {
11984                    synchronized (mInstallLock) {
11985                        // We don't need to freeze for a brand new install
11986                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11987                    }
11988                }
11989                sendPackageAddedForUser(packageName, pkgSetting, userId);
11990            }
11991        } finally {
11992            Binder.restoreCallingIdentity(callingId);
11993        }
11994
11995        return PackageManager.INSTALL_SUCCEEDED;
11996    }
11997
11998    boolean isUserRestricted(int userId, String restrictionKey) {
11999        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12000        if (restrictions.getBoolean(restrictionKey, false)) {
12001            Log.w(TAG, "User is restricted: " + restrictionKey);
12002            return true;
12003        }
12004        return false;
12005    }
12006
12007    @Override
12008    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12009            int userId) {
12010        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12011        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12012                true /* requireFullPermission */, true /* checkShell */,
12013                "setPackagesSuspended for user " + userId);
12014
12015        if (ArrayUtils.isEmpty(packageNames)) {
12016            return packageNames;
12017        }
12018
12019        // List of package names for whom the suspended state has changed.
12020        List<String> changedPackages = new ArrayList<>(packageNames.length);
12021        // List of package names for whom the suspended state is not set as requested in this
12022        // method.
12023        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12024        long callingId = Binder.clearCallingIdentity();
12025        try {
12026            for (int i = 0; i < packageNames.length; i++) {
12027                String packageName = packageNames[i];
12028                boolean changed = false;
12029                final int appId;
12030                synchronized (mPackages) {
12031                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12032                    if (pkgSetting == null) {
12033                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12034                                + "\". Skipping suspending/un-suspending.");
12035                        unactionedPackages.add(packageName);
12036                        continue;
12037                    }
12038                    appId = pkgSetting.appId;
12039                    if (pkgSetting.getSuspended(userId) != suspended) {
12040                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12041                            unactionedPackages.add(packageName);
12042                            continue;
12043                        }
12044                        pkgSetting.setSuspended(suspended, userId);
12045                        mSettings.writePackageRestrictionsLPr(userId);
12046                        changed = true;
12047                        changedPackages.add(packageName);
12048                    }
12049                }
12050
12051                if (changed && suspended) {
12052                    killApplication(packageName, UserHandle.getUid(userId, appId),
12053                            "suspending package");
12054                }
12055            }
12056        } finally {
12057            Binder.restoreCallingIdentity(callingId);
12058        }
12059
12060        if (!changedPackages.isEmpty()) {
12061            sendPackagesSuspendedForUser(changedPackages.toArray(
12062                    new String[changedPackages.size()]), userId, suspended);
12063        }
12064
12065        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12066    }
12067
12068    @Override
12069    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12070        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12071                true /* requireFullPermission */, false /* checkShell */,
12072                "isPackageSuspendedForUser for user " + userId);
12073        synchronized (mPackages) {
12074            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12075            if (pkgSetting == null) {
12076                throw new IllegalArgumentException("Unknown target package: " + packageName);
12077            }
12078            return pkgSetting.getSuspended(userId);
12079        }
12080    }
12081
12082    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12083        if (isPackageDeviceAdmin(packageName, userId)) {
12084            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12085                    + "\": has an active device admin");
12086            return false;
12087        }
12088
12089        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12090        if (packageName.equals(activeLauncherPackageName)) {
12091            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12092                    + "\": contains the active launcher");
12093            return false;
12094        }
12095
12096        if (packageName.equals(mRequiredInstallerPackage)) {
12097            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12098                    + "\": required for package installation");
12099            return false;
12100        }
12101
12102        if (packageName.equals(mRequiredUninstallerPackage)) {
12103            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12104                    + "\": required for package uninstallation");
12105            return false;
12106        }
12107
12108        if (packageName.equals(mRequiredVerifierPackage)) {
12109            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12110                    + "\": required for package verification");
12111            return false;
12112        }
12113
12114        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12115            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12116                    + "\": is the default dialer");
12117            return false;
12118        }
12119
12120        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12121            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12122                    + "\": protected package");
12123            return false;
12124        }
12125
12126        return true;
12127    }
12128
12129    private String getActiveLauncherPackageName(int userId) {
12130        Intent intent = new Intent(Intent.ACTION_MAIN);
12131        intent.addCategory(Intent.CATEGORY_HOME);
12132        ResolveInfo resolveInfo = resolveIntent(
12133                intent,
12134                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12135                PackageManager.MATCH_DEFAULT_ONLY,
12136                userId);
12137
12138        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12139    }
12140
12141    private String getDefaultDialerPackageName(int userId) {
12142        synchronized (mPackages) {
12143            return mSettings.getDefaultDialerPackageNameLPw(userId);
12144        }
12145    }
12146
12147    @Override
12148    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12149        mContext.enforceCallingOrSelfPermission(
12150                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12151                "Only package verification agents can verify applications");
12152
12153        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12154        final PackageVerificationResponse response = new PackageVerificationResponse(
12155                verificationCode, Binder.getCallingUid());
12156        msg.arg1 = id;
12157        msg.obj = response;
12158        mHandler.sendMessage(msg);
12159    }
12160
12161    @Override
12162    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12163            long millisecondsToDelay) {
12164        mContext.enforceCallingOrSelfPermission(
12165                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12166                "Only package verification agents can extend verification timeouts");
12167
12168        final PackageVerificationState state = mPendingVerification.get(id);
12169        final PackageVerificationResponse response = new PackageVerificationResponse(
12170                verificationCodeAtTimeout, Binder.getCallingUid());
12171
12172        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12173            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12174        }
12175        if (millisecondsToDelay < 0) {
12176            millisecondsToDelay = 0;
12177        }
12178        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12179                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12180            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12181        }
12182
12183        if ((state != null) && !state.timeoutExtended()) {
12184            state.extendTimeout();
12185
12186            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12187            msg.arg1 = id;
12188            msg.obj = response;
12189            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12190        }
12191    }
12192
12193    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12194            int verificationCode, UserHandle user) {
12195        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12196        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12197        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12198        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12199        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12200
12201        mContext.sendBroadcastAsUser(intent, user,
12202                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12203    }
12204
12205    private ComponentName matchComponentForVerifier(String packageName,
12206            List<ResolveInfo> receivers) {
12207        ActivityInfo targetReceiver = null;
12208
12209        final int NR = receivers.size();
12210        for (int i = 0; i < NR; i++) {
12211            final ResolveInfo info = receivers.get(i);
12212            if (info.activityInfo == null) {
12213                continue;
12214            }
12215
12216            if (packageName.equals(info.activityInfo.packageName)) {
12217                targetReceiver = info.activityInfo;
12218                break;
12219            }
12220        }
12221
12222        if (targetReceiver == null) {
12223            return null;
12224        }
12225
12226        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12227    }
12228
12229    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12230            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12231        if (pkgInfo.verifiers.length == 0) {
12232            return null;
12233        }
12234
12235        final int N = pkgInfo.verifiers.length;
12236        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12237        for (int i = 0; i < N; i++) {
12238            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12239
12240            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12241                    receivers);
12242            if (comp == null) {
12243                continue;
12244            }
12245
12246            final int verifierUid = getUidForVerifier(verifierInfo);
12247            if (verifierUid == -1) {
12248                continue;
12249            }
12250
12251            if (DEBUG_VERIFY) {
12252                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12253                        + " with the correct signature");
12254            }
12255            sufficientVerifiers.add(comp);
12256            verificationState.addSufficientVerifier(verifierUid);
12257        }
12258
12259        return sufficientVerifiers;
12260    }
12261
12262    private int getUidForVerifier(VerifierInfo verifierInfo) {
12263        synchronized (mPackages) {
12264            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12265            if (pkg == null) {
12266                return -1;
12267            } else if (pkg.mSignatures.length != 1) {
12268                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12269                        + " has more than one signature; ignoring");
12270                return -1;
12271            }
12272
12273            /*
12274             * If the public key of the package's signature does not match
12275             * our expected public key, then this is a different package and
12276             * we should skip.
12277             */
12278
12279            final byte[] expectedPublicKey;
12280            try {
12281                final Signature verifierSig = pkg.mSignatures[0];
12282                final PublicKey publicKey = verifierSig.getPublicKey();
12283                expectedPublicKey = publicKey.getEncoded();
12284            } catch (CertificateException e) {
12285                return -1;
12286            }
12287
12288            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12289
12290            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12291                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12292                        + " does not have the expected public key; ignoring");
12293                return -1;
12294            }
12295
12296            return pkg.applicationInfo.uid;
12297        }
12298    }
12299
12300    @Override
12301    public void finishPackageInstall(int token, boolean didLaunch) {
12302        enforceSystemOrRoot("Only the system is allowed to finish installs");
12303
12304        if (DEBUG_INSTALL) {
12305            Slog.v(TAG, "BM finishing package install for " + token);
12306        }
12307        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12308
12309        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12310        mHandler.sendMessage(msg);
12311    }
12312
12313    /**
12314     * Get the verification agent timeout.
12315     *
12316     * @return verification timeout in milliseconds
12317     */
12318    private long getVerificationTimeout() {
12319        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12320                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12321                DEFAULT_VERIFICATION_TIMEOUT);
12322    }
12323
12324    /**
12325     * Get the default verification agent response code.
12326     *
12327     * @return default verification response code
12328     */
12329    private int getDefaultVerificationResponse() {
12330        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12331                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12332                DEFAULT_VERIFICATION_RESPONSE);
12333    }
12334
12335    /**
12336     * Check whether or not package verification has been enabled.
12337     *
12338     * @return true if verification should be performed
12339     */
12340    private boolean isVerificationEnabled(int userId, int installFlags) {
12341        if (!DEFAULT_VERIFY_ENABLE) {
12342            return false;
12343        }
12344        // Ephemeral apps don't get the full verification treatment
12345        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12346            if (DEBUG_EPHEMERAL) {
12347                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12348            }
12349            return false;
12350        }
12351
12352        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12353
12354        // Check if installing from ADB
12355        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12356            // Do not run verification in a test harness environment
12357            if (ActivityManager.isRunningInTestHarness()) {
12358                return false;
12359            }
12360            if (ensureVerifyAppsEnabled) {
12361                return true;
12362            }
12363            // Check if the developer does not want package verification for ADB installs
12364            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12365                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12366                return false;
12367            }
12368        }
12369
12370        if (ensureVerifyAppsEnabled) {
12371            return true;
12372        }
12373
12374        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12375                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12376    }
12377
12378    @Override
12379    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12380            throws RemoteException {
12381        mContext.enforceCallingOrSelfPermission(
12382                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12383                "Only intentfilter verification agents can verify applications");
12384
12385        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12386        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12387                Binder.getCallingUid(), verificationCode, failedDomains);
12388        msg.arg1 = id;
12389        msg.obj = response;
12390        mHandler.sendMessage(msg);
12391    }
12392
12393    @Override
12394    public int getIntentVerificationStatus(String packageName, int userId) {
12395        synchronized (mPackages) {
12396            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12397        }
12398    }
12399
12400    @Override
12401    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12402        mContext.enforceCallingOrSelfPermission(
12403                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12404
12405        boolean result = false;
12406        synchronized (mPackages) {
12407            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12408        }
12409        if (result) {
12410            scheduleWritePackageRestrictionsLocked(userId);
12411        }
12412        return result;
12413    }
12414
12415    @Override
12416    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12417            String packageName) {
12418        synchronized (mPackages) {
12419            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12420        }
12421    }
12422
12423    @Override
12424    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12425        if (TextUtils.isEmpty(packageName)) {
12426            return ParceledListSlice.emptyList();
12427        }
12428        synchronized (mPackages) {
12429            PackageParser.Package pkg = mPackages.get(packageName);
12430            if (pkg == null || pkg.activities == null) {
12431                return ParceledListSlice.emptyList();
12432            }
12433            final int count = pkg.activities.size();
12434            ArrayList<IntentFilter> result = new ArrayList<>();
12435            for (int n=0; n<count; n++) {
12436                PackageParser.Activity activity = pkg.activities.get(n);
12437                if (activity.intents != null && activity.intents.size() > 0) {
12438                    result.addAll(activity.intents);
12439                }
12440            }
12441            return new ParceledListSlice<>(result);
12442        }
12443    }
12444
12445    @Override
12446    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12447        mContext.enforceCallingOrSelfPermission(
12448                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12449
12450        synchronized (mPackages) {
12451            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12452            if (packageName != null) {
12453                result |= updateIntentVerificationStatus(packageName,
12454                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12455                        userId);
12456                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12457                        packageName, userId);
12458            }
12459            return result;
12460        }
12461    }
12462
12463    @Override
12464    public String getDefaultBrowserPackageName(int userId) {
12465        synchronized (mPackages) {
12466            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12467        }
12468    }
12469
12470    /**
12471     * Get the "allow unknown sources" setting.
12472     *
12473     * @return the current "allow unknown sources" setting
12474     */
12475    private int getUnknownSourcesSettings() {
12476        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12477                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12478                -1);
12479    }
12480
12481    @Override
12482    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12483        final int uid = Binder.getCallingUid();
12484        // writer
12485        synchronized (mPackages) {
12486            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12487            if (targetPackageSetting == null) {
12488                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12489            }
12490
12491            PackageSetting installerPackageSetting;
12492            if (installerPackageName != null) {
12493                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12494                if (installerPackageSetting == null) {
12495                    throw new IllegalArgumentException("Unknown installer package: "
12496                            + installerPackageName);
12497                }
12498            } else {
12499                installerPackageSetting = null;
12500            }
12501
12502            Signature[] callerSignature;
12503            Object obj = mSettings.getUserIdLPr(uid);
12504            if (obj != null) {
12505                if (obj instanceof SharedUserSetting) {
12506                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12507                } else if (obj instanceof PackageSetting) {
12508                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12509                } else {
12510                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12511                }
12512            } else {
12513                throw new SecurityException("Unknown calling UID: " + uid);
12514            }
12515
12516            // Verify: can't set installerPackageName to a package that is
12517            // not signed with the same cert as the caller.
12518            if (installerPackageSetting != null) {
12519                if (compareSignatures(callerSignature,
12520                        installerPackageSetting.signatures.mSignatures)
12521                        != PackageManager.SIGNATURE_MATCH) {
12522                    throw new SecurityException(
12523                            "Caller does not have same cert as new installer package "
12524                            + installerPackageName);
12525                }
12526            }
12527
12528            // Verify: if target already has an installer package, it must
12529            // be signed with the same cert as the caller.
12530            if (targetPackageSetting.installerPackageName != null) {
12531                PackageSetting setting = mSettings.mPackages.get(
12532                        targetPackageSetting.installerPackageName);
12533                // If the currently set package isn't valid, then it's always
12534                // okay to change it.
12535                if (setting != null) {
12536                    if (compareSignatures(callerSignature,
12537                            setting.signatures.mSignatures)
12538                            != PackageManager.SIGNATURE_MATCH) {
12539                        throw new SecurityException(
12540                                "Caller does not have same cert as old installer package "
12541                                + targetPackageSetting.installerPackageName);
12542                    }
12543                }
12544            }
12545
12546            // Okay!
12547            targetPackageSetting.installerPackageName = installerPackageName;
12548            if (installerPackageName != null) {
12549                mSettings.mInstallerPackages.add(installerPackageName);
12550            }
12551            scheduleWriteSettingsLocked();
12552        }
12553    }
12554
12555    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12556        // Queue up an async operation since the package installation may take a little while.
12557        mHandler.post(new Runnable() {
12558            public void run() {
12559                mHandler.removeCallbacks(this);
12560                 // Result object to be returned
12561                PackageInstalledInfo res = new PackageInstalledInfo();
12562                res.setReturnCode(currentStatus);
12563                res.uid = -1;
12564                res.pkg = null;
12565                res.removedInfo = null;
12566                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12567                    args.doPreInstall(res.returnCode);
12568                    synchronized (mInstallLock) {
12569                        installPackageTracedLI(args, res);
12570                    }
12571                    args.doPostInstall(res.returnCode, res.uid);
12572                }
12573
12574                // A restore should be performed at this point if (a) the install
12575                // succeeded, (b) the operation is not an update, and (c) the new
12576                // package has not opted out of backup participation.
12577                final boolean update = res.removedInfo != null
12578                        && res.removedInfo.removedPackage != null;
12579                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12580                boolean doRestore = !update
12581                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12582
12583                // Set up the post-install work request bookkeeping.  This will be used
12584                // and cleaned up by the post-install event handling regardless of whether
12585                // there's a restore pass performed.  Token values are >= 1.
12586                int token;
12587                if (mNextInstallToken < 0) mNextInstallToken = 1;
12588                token = mNextInstallToken++;
12589
12590                PostInstallData data = new PostInstallData(args, res);
12591                mRunningInstalls.put(token, data);
12592                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12593
12594                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12595                    // Pass responsibility to the Backup Manager.  It will perform a
12596                    // restore if appropriate, then pass responsibility back to the
12597                    // Package Manager to run the post-install observer callbacks
12598                    // and broadcasts.
12599                    IBackupManager bm = IBackupManager.Stub.asInterface(
12600                            ServiceManager.getService(Context.BACKUP_SERVICE));
12601                    if (bm != null) {
12602                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12603                                + " to BM for possible restore");
12604                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12605                        try {
12606                            // TODO: http://b/22388012
12607                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12608                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12609                            } else {
12610                                doRestore = false;
12611                            }
12612                        } catch (RemoteException e) {
12613                            // can't happen; the backup manager is local
12614                        } catch (Exception e) {
12615                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12616                            doRestore = false;
12617                        }
12618                    } else {
12619                        Slog.e(TAG, "Backup Manager not found!");
12620                        doRestore = false;
12621                    }
12622                }
12623
12624                if (!doRestore) {
12625                    // No restore possible, or the Backup Manager was mysteriously not
12626                    // available -- just fire the post-install work request directly.
12627                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12628
12629                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12630
12631                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12632                    mHandler.sendMessage(msg);
12633                }
12634            }
12635        });
12636    }
12637
12638    /**
12639     * Callback from PackageSettings whenever an app is first transitioned out of the
12640     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12641     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12642     * here whether the app is the target of an ongoing install, and only send the
12643     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12644     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12645     * handling.
12646     */
12647    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12648        // Serialize this with the rest of the install-process message chain.  In the
12649        // restore-at-install case, this Runnable will necessarily run before the
12650        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12651        // are coherent.  In the non-restore case, the app has already completed install
12652        // and been launched through some other means, so it is not in a problematic
12653        // state for observers to see the FIRST_LAUNCH signal.
12654        mHandler.post(new Runnable() {
12655            @Override
12656            public void run() {
12657                for (int i = 0; i < mRunningInstalls.size(); i++) {
12658                    final PostInstallData data = mRunningInstalls.valueAt(i);
12659                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12660                        continue;
12661                    }
12662                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12663                        // right package; but is it for the right user?
12664                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12665                            if (userId == data.res.newUsers[uIndex]) {
12666                                if (DEBUG_BACKUP) {
12667                                    Slog.i(TAG, "Package " + pkgName
12668                                            + " being restored so deferring FIRST_LAUNCH");
12669                                }
12670                                return;
12671                            }
12672                        }
12673                    }
12674                }
12675                // didn't find it, so not being restored
12676                if (DEBUG_BACKUP) {
12677                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12678                }
12679                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12680            }
12681        });
12682    }
12683
12684    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12685        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12686                installerPkg, null, userIds);
12687    }
12688
12689    private abstract class HandlerParams {
12690        private static final int MAX_RETRIES = 4;
12691
12692        /**
12693         * Number of times startCopy() has been attempted and had a non-fatal
12694         * error.
12695         */
12696        private int mRetries = 0;
12697
12698        /** User handle for the user requesting the information or installation. */
12699        private final UserHandle mUser;
12700        String traceMethod;
12701        int traceCookie;
12702
12703        HandlerParams(UserHandle user) {
12704            mUser = user;
12705        }
12706
12707        UserHandle getUser() {
12708            return mUser;
12709        }
12710
12711        HandlerParams setTraceMethod(String traceMethod) {
12712            this.traceMethod = traceMethod;
12713            return this;
12714        }
12715
12716        HandlerParams setTraceCookie(int traceCookie) {
12717            this.traceCookie = traceCookie;
12718            return this;
12719        }
12720
12721        final boolean startCopy() {
12722            boolean res;
12723            try {
12724                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12725
12726                if (++mRetries > MAX_RETRIES) {
12727                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12728                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12729                    handleServiceError();
12730                    return false;
12731                } else {
12732                    handleStartCopy();
12733                    res = true;
12734                }
12735            } catch (RemoteException e) {
12736                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12737                mHandler.sendEmptyMessage(MCS_RECONNECT);
12738                res = false;
12739            }
12740            handleReturnCode();
12741            return res;
12742        }
12743
12744        final void serviceError() {
12745            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12746            handleServiceError();
12747            handleReturnCode();
12748        }
12749
12750        abstract void handleStartCopy() throws RemoteException;
12751        abstract void handleServiceError();
12752        abstract void handleReturnCode();
12753    }
12754
12755    class MeasureParams extends HandlerParams {
12756        private final PackageStats mStats;
12757        private boolean mSuccess;
12758
12759        private final IPackageStatsObserver mObserver;
12760
12761        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12762            super(new UserHandle(stats.userHandle));
12763            mObserver = observer;
12764            mStats = stats;
12765        }
12766
12767        @Override
12768        public String toString() {
12769            return "MeasureParams{"
12770                + Integer.toHexString(System.identityHashCode(this))
12771                + " " + mStats.packageName + "}";
12772        }
12773
12774        @Override
12775        void handleStartCopy() throws RemoteException {
12776            synchronized (mInstallLock) {
12777                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12778            }
12779
12780            if (mSuccess) {
12781                boolean mounted = false;
12782                try {
12783                    final String status = Environment.getExternalStorageState();
12784                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12785                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12786                } catch (Exception e) {
12787                }
12788
12789                if (mounted) {
12790                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12791
12792                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12793                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12794
12795                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12796                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12797
12798                    // Always subtract cache size, since it's a subdirectory
12799                    mStats.externalDataSize -= mStats.externalCacheSize;
12800
12801                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12802                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12803
12804                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12805                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12806                }
12807            }
12808        }
12809
12810        @Override
12811        void handleReturnCode() {
12812            if (mObserver != null) {
12813                try {
12814                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12815                } catch (RemoteException e) {
12816                    Slog.i(TAG, "Observer no longer exists.");
12817                }
12818            }
12819        }
12820
12821        @Override
12822        void handleServiceError() {
12823            Slog.e(TAG, "Could not measure application " + mStats.packageName
12824                            + " external storage");
12825        }
12826    }
12827
12828    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12829            throws RemoteException {
12830        long result = 0;
12831        for (File path : paths) {
12832            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12833        }
12834        return result;
12835    }
12836
12837    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12838        for (File path : paths) {
12839            try {
12840                mcs.clearDirectory(path.getAbsolutePath());
12841            } catch (RemoteException e) {
12842            }
12843        }
12844    }
12845
12846    static class OriginInfo {
12847        /**
12848         * Location where install is coming from, before it has been
12849         * copied/renamed into place. This could be a single monolithic APK
12850         * file, or a cluster directory. This location may be untrusted.
12851         */
12852        final File file;
12853        final String cid;
12854
12855        /**
12856         * Flag indicating that {@link #file} or {@link #cid} has already been
12857         * staged, meaning downstream users don't need to defensively copy the
12858         * contents.
12859         */
12860        final boolean staged;
12861
12862        /**
12863         * Flag indicating that {@link #file} or {@link #cid} is an already
12864         * installed app that is being moved.
12865         */
12866        final boolean existing;
12867
12868        final String resolvedPath;
12869        final File resolvedFile;
12870
12871        static OriginInfo fromNothing() {
12872            return new OriginInfo(null, null, false, false);
12873        }
12874
12875        static OriginInfo fromUntrustedFile(File file) {
12876            return new OriginInfo(file, null, false, false);
12877        }
12878
12879        static OriginInfo fromExistingFile(File file) {
12880            return new OriginInfo(file, null, false, true);
12881        }
12882
12883        static OriginInfo fromStagedFile(File file) {
12884            return new OriginInfo(file, null, true, false);
12885        }
12886
12887        static OriginInfo fromStagedContainer(String cid) {
12888            return new OriginInfo(null, cid, true, false);
12889        }
12890
12891        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12892            this.file = file;
12893            this.cid = cid;
12894            this.staged = staged;
12895            this.existing = existing;
12896
12897            if (cid != null) {
12898                resolvedPath = PackageHelper.getSdDir(cid);
12899                resolvedFile = new File(resolvedPath);
12900            } else if (file != null) {
12901                resolvedPath = file.getAbsolutePath();
12902                resolvedFile = file;
12903            } else {
12904                resolvedPath = null;
12905                resolvedFile = null;
12906            }
12907        }
12908    }
12909
12910    static class MoveInfo {
12911        final int moveId;
12912        final String fromUuid;
12913        final String toUuid;
12914        final String packageName;
12915        final String dataAppName;
12916        final int appId;
12917        final String seinfo;
12918        final int targetSdkVersion;
12919
12920        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12921                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12922            this.moveId = moveId;
12923            this.fromUuid = fromUuid;
12924            this.toUuid = toUuid;
12925            this.packageName = packageName;
12926            this.dataAppName = dataAppName;
12927            this.appId = appId;
12928            this.seinfo = seinfo;
12929            this.targetSdkVersion = targetSdkVersion;
12930        }
12931    }
12932
12933    static class VerificationInfo {
12934        /** A constant used to indicate that a uid value is not present. */
12935        public static final int NO_UID = -1;
12936
12937        /** URI referencing where the package was downloaded from. */
12938        final Uri originatingUri;
12939
12940        /** HTTP referrer URI associated with the originatingURI. */
12941        final Uri referrer;
12942
12943        /** UID of the application that the install request originated from. */
12944        final int originatingUid;
12945
12946        /** UID of application requesting the install */
12947        final int installerUid;
12948
12949        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12950            this.originatingUri = originatingUri;
12951            this.referrer = referrer;
12952            this.originatingUid = originatingUid;
12953            this.installerUid = installerUid;
12954        }
12955    }
12956
12957    class InstallParams extends HandlerParams {
12958        final OriginInfo origin;
12959        final MoveInfo move;
12960        final IPackageInstallObserver2 observer;
12961        int installFlags;
12962        final String installerPackageName;
12963        final String volumeUuid;
12964        private InstallArgs mArgs;
12965        private int mRet;
12966        final String packageAbiOverride;
12967        final String[] grantedRuntimePermissions;
12968        final VerificationInfo verificationInfo;
12969        final Certificate[][] certificates;
12970
12971        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12972                int installFlags, String installerPackageName, String volumeUuid,
12973                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12974                String[] grantedPermissions, Certificate[][] certificates) {
12975            super(user);
12976            this.origin = origin;
12977            this.move = move;
12978            this.observer = observer;
12979            this.installFlags = installFlags;
12980            this.installerPackageName = installerPackageName;
12981            this.volumeUuid = volumeUuid;
12982            this.verificationInfo = verificationInfo;
12983            this.packageAbiOverride = packageAbiOverride;
12984            this.grantedRuntimePermissions = grantedPermissions;
12985            this.certificates = certificates;
12986        }
12987
12988        @Override
12989        public String toString() {
12990            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12991                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12992        }
12993
12994        private int installLocationPolicy(PackageInfoLite pkgLite) {
12995            String packageName = pkgLite.packageName;
12996            int installLocation = pkgLite.installLocation;
12997            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12998            // reader
12999            synchronized (mPackages) {
13000                // Currently installed package which the new package is attempting to replace or
13001                // null if no such package is installed.
13002                PackageParser.Package installedPkg = mPackages.get(packageName);
13003                // Package which currently owns the data which the new package will own if installed.
13004                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13005                // will be null whereas dataOwnerPkg will contain information about the package
13006                // which was uninstalled while keeping its data.
13007                PackageParser.Package dataOwnerPkg = installedPkg;
13008                if (dataOwnerPkg  == null) {
13009                    PackageSetting ps = mSettings.mPackages.get(packageName);
13010                    if (ps != null) {
13011                        dataOwnerPkg = ps.pkg;
13012                    }
13013                }
13014
13015                if (dataOwnerPkg != null) {
13016                    // If installed, the package will get access to data left on the device by its
13017                    // predecessor. As a security measure, this is permited only if this is not a
13018                    // version downgrade or if the predecessor package is marked as debuggable and
13019                    // a downgrade is explicitly requested.
13020                    //
13021                    // On debuggable platform builds, downgrades are permitted even for
13022                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13023                    // not offer security guarantees and thus it's OK to disable some security
13024                    // mechanisms to make debugging/testing easier on those builds. However, even on
13025                    // debuggable builds downgrades of packages are permitted only if requested via
13026                    // installFlags. This is because we aim to keep the behavior of debuggable
13027                    // platform builds as close as possible to the behavior of non-debuggable
13028                    // platform builds.
13029                    final boolean downgradeRequested =
13030                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13031                    final boolean packageDebuggable =
13032                                (dataOwnerPkg.applicationInfo.flags
13033                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13034                    final boolean downgradePermitted =
13035                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13036                    if (!downgradePermitted) {
13037                        try {
13038                            checkDowngrade(dataOwnerPkg, pkgLite);
13039                        } catch (PackageManagerException e) {
13040                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13041                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13042                        }
13043                    }
13044                }
13045
13046                if (installedPkg != null) {
13047                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13048                        // Check for updated system application.
13049                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13050                            if (onSd) {
13051                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13052                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13053                            }
13054                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13055                        } else {
13056                            if (onSd) {
13057                                // Install flag overrides everything.
13058                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13059                            }
13060                            // If current upgrade specifies particular preference
13061                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13062                                // Application explicitly specified internal.
13063                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13064                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13065                                // App explictly prefers external. Let policy decide
13066                            } else {
13067                                // Prefer previous location
13068                                if (isExternal(installedPkg)) {
13069                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13070                                }
13071                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13072                            }
13073                        }
13074                    } else {
13075                        // Invalid install. Return error code
13076                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13077                    }
13078                }
13079            }
13080            // All the special cases have been taken care of.
13081            // Return result based on recommended install location.
13082            if (onSd) {
13083                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13084            }
13085            return pkgLite.recommendedInstallLocation;
13086        }
13087
13088        /*
13089         * Invoke remote method to get package information and install
13090         * location values. Override install location based on default
13091         * policy if needed and then create install arguments based
13092         * on the install location.
13093         */
13094        public void handleStartCopy() throws RemoteException {
13095            int ret = PackageManager.INSTALL_SUCCEEDED;
13096
13097            // If we're already staged, we've firmly committed to an install location
13098            if (origin.staged) {
13099                if (origin.file != null) {
13100                    installFlags |= PackageManager.INSTALL_INTERNAL;
13101                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13102                } else if (origin.cid != null) {
13103                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13104                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13105                } else {
13106                    throw new IllegalStateException("Invalid stage location");
13107                }
13108            }
13109
13110            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13111            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13112            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13113            PackageInfoLite pkgLite = null;
13114
13115            if (onInt && onSd) {
13116                // Check if both bits are set.
13117                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13118                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13119            } else if (onSd && ephemeral) {
13120                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13121                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13122            } else {
13123                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13124                        packageAbiOverride);
13125
13126                if (DEBUG_EPHEMERAL && ephemeral) {
13127                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13128                }
13129
13130                /*
13131                 * If we have too little free space, try to free cache
13132                 * before giving up.
13133                 */
13134                if (!origin.staged && pkgLite.recommendedInstallLocation
13135                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13136                    // TODO: focus freeing disk space on the target device
13137                    final StorageManager storage = StorageManager.from(mContext);
13138                    final long lowThreshold = storage.getStorageLowBytes(
13139                            Environment.getDataDirectory());
13140
13141                    final long sizeBytes = mContainerService.calculateInstalledSize(
13142                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13143
13144                    try {
13145                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13146                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13147                                installFlags, packageAbiOverride);
13148                    } catch (InstallerException e) {
13149                        Slog.w(TAG, "Failed to free cache", e);
13150                    }
13151
13152                    /*
13153                     * The cache free must have deleted the file we
13154                     * downloaded to install.
13155                     *
13156                     * TODO: fix the "freeCache" call to not delete
13157                     *       the file we care about.
13158                     */
13159                    if (pkgLite.recommendedInstallLocation
13160                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13161                        pkgLite.recommendedInstallLocation
13162                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13163                    }
13164                }
13165            }
13166
13167            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13168                int loc = pkgLite.recommendedInstallLocation;
13169                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13170                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13171                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13172                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13173                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13174                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13175                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13176                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13177                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13178                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13179                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13180                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13181                } else {
13182                    // Override with defaults if needed.
13183                    loc = installLocationPolicy(pkgLite);
13184                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13185                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13186                    } else if (!onSd && !onInt) {
13187                        // Override install location with flags
13188                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13189                            // Set the flag to install on external media.
13190                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13191                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13192                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13193                            if (DEBUG_EPHEMERAL) {
13194                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13195                            }
13196                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13197                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13198                                    |PackageManager.INSTALL_INTERNAL);
13199                        } else {
13200                            // Make sure the flag for installing on external
13201                            // media is unset
13202                            installFlags |= PackageManager.INSTALL_INTERNAL;
13203                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13204                        }
13205                    }
13206                }
13207            }
13208
13209            final InstallArgs args = createInstallArgs(this);
13210            mArgs = args;
13211
13212            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13213                // TODO: http://b/22976637
13214                // Apps installed for "all" users use the device owner to verify the app
13215                UserHandle verifierUser = getUser();
13216                if (verifierUser == UserHandle.ALL) {
13217                    verifierUser = UserHandle.SYSTEM;
13218                }
13219
13220                /*
13221                 * Determine if we have any installed package verifiers. If we
13222                 * do, then we'll defer to them to verify the packages.
13223                 */
13224                final int requiredUid = mRequiredVerifierPackage == null ? -1
13225                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13226                                verifierUser.getIdentifier());
13227                if (!origin.existing && requiredUid != -1
13228                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13229                    final Intent verification = new Intent(
13230                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13231                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13232                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13233                            PACKAGE_MIME_TYPE);
13234                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13235
13236                    // Query all live verifiers based on current user state
13237                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13238                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13239
13240                    if (DEBUG_VERIFY) {
13241                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13242                                + verification.toString() + " with " + pkgLite.verifiers.length
13243                                + " optional verifiers");
13244                    }
13245
13246                    final int verificationId = mPendingVerificationToken++;
13247
13248                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13249
13250                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13251                            installerPackageName);
13252
13253                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13254                            installFlags);
13255
13256                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13257                            pkgLite.packageName);
13258
13259                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13260                            pkgLite.versionCode);
13261
13262                    if (verificationInfo != null) {
13263                        if (verificationInfo.originatingUri != null) {
13264                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13265                                    verificationInfo.originatingUri);
13266                        }
13267                        if (verificationInfo.referrer != null) {
13268                            verification.putExtra(Intent.EXTRA_REFERRER,
13269                                    verificationInfo.referrer);
13270                        }
13271                        if (verificationInfo.originatingUid >= 0) {
13272                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13273                                    verificationInfo.originatingUid);
13274                        }
13275                        if (verificationInfo.installerUid >= 0) {
13276                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13277                                    verificationInfo.installerUid);
13278                        }
13279                    }
13280
13281                    final PackageVerificationState verificationState = new PackageVerificationState(
13282                            requiredUid, args);
13283
13284                    mPendingVerification.append(verificationId, verificationState);
13285
13286                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13287                            receivers, verificationState);
13288
13289                    /*
13290                     * If any sufficient verifiers were listed in the package
13291                     * manifest, attempt to ask them.
13292                     */
13293                    if (sufficientVerifiers != null) {
13294                        final int N = sufficientVerifiers.size();
13295                        if (N == 0) {
13296                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13297                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13298                        } else {
13299                            for (int i = 0; i < N; i++) {
13300                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13301
13302                                final Intent sufficientIntent = new Intent(verification);
13303                                sufficientIntent.setComponent(verifierComponent);
13304                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13305                            }
13306                        }
13307                    }
13308
13309                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13310                            mRequiredVerifierPackage, receivers);
13311                    if (ret == PackageManager.INSTALL_SUCCEEDED
13312                            && mRequiredVerifierPackage != null) {
13313                        Trace.asyncTraceBegin(
13314                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13315                        /*
13316                         * Send the intent to the required verification agent,
13317                         * but only start the verification timeout after the
13318                         * target BroadcastReceivers have run.
13319                         */
13320                        verification.setComponent(requiredVerifierComponent);
13321                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13322                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13323                                new BroadcastReceiver() {
13324                                    @Override
13325                                    public void onReceive(Context context, Intent intent) {
13326                                        final Message msg = mHandler
13327                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13328                                        msg.arg1 = verificationId;
13329                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13330                                    }
13331                                }, null, 0, null, null);
13332
13333                        /*
13334                         * We don't want the copy to proceed until verification
13335                         * succeeds, so null out this field.
13336                         */
13337                        mArgs = null;
13338                    }
13339                } else {
13340                    /*
13341                     * No package verification is enabled, so immediately start
13342                     * the remote call to initiate copy using temporary file.
13343                     */
13344                    ret = args.copyApk(mContainerService, true);
13345                }
13346            }
13347
13348            mRet = ret;
13349        }
13350
13351        @Override
13352        void handleReturnCode() {
13353            // If mArgs is null, then MCS couldn't be reached. When it
13354            // reconnects, it will try again to install. At that point, this
13355            // will succeed.
13356            if (mArgs != null) {
13357                processPendingInstall(mArgs, mRet);
13358            }
13359        }
13360
13361        @Override
13362        void handleServiceError() {
13363            mArgs = createInstallArgs(this);
13364            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13365        }
13366
13367        public boolean isForwardLocked() {
13368            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13369        }
13370    }
13371
13372    /**
13373     * Used during creation of InstallArgs
13374     *
13375     * @param installFlags package installation flags
13376     * @return true if should be installed on external storage
13377     */
13378    private static boolean installOnExternalAsec(int installFlags) {
13379        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13380            return false;
13381        }
13382        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13383            return true;
13384        }
13385        return false;
13386    }
13387
13388    /**
13389     * Used during creation of InstallArgs
13390     *
13391     * @param installFlags package installation flags
13392     * @return true if should be installed as forward locked
13393     */
13394    private static boolean installForwardLocked(int installFlags) {
13395        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13396    }
13397
13398    private InstallArgs createInstallArgs(InstallParams params) {
13399        if (params.move != null) {
13400            return new MoveInstallArgs(params);
13401        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13402            return new AsecInstallArgs(params);
13403        } else {
13404            return new FileInstallArgs(params);
13405        }
13406    }
13407
13408    /**
13409     * Create args that describe an existing installed package. Typically used
13410     * when cleaning up old installs, or used as a move source.
13411     */
13412    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13413            String resourcePath, String[] instructionSets) {
13414        final boolean isInAsec;
13415        if (installOnExternalAsec(installFlags)) {
13416            /* Apps on SD card are always in ASEC containers. */
13417            isInAsec = true;
13418        } else if (installForwardLocked(installFlags)
13419                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13420            /*
13421             * Forward-locked apps are only in ASEC containers if they're the
13422             * new style
13423             */
13424            isInAsec = true;
13425        } else {
13426            isInAsec = false;
13427        }
13428
13429        if (isInAsec) {
13430            return new AsecInstallArgs(codePath, instructionSets,
13431                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13432        } else {
13433            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13434        }
13435    }
13436
13437    static abstract class InstallArgs {
13438        /** @see InstallParams#origin */
13439        final OriginInfo origin;
13440        /** @see InstallParams#move */
13441        final MoveInfo move;
13442
13443        final IPackageInstallObserver2 observer;
13444        // Always refers to PackageManager flags only
13445        final int installFlags;
13446        final String installerPackageName;
13447        final String volumeUuid;
13448        final UserHandle user;
13449        final String abiOverride;
13450        final String[] installGrantPermissions;
13451        /** If non-null, drop an async trace when the install completes */
13452        final String traceMethod;
13453        final int traceCookie;
13454        final Certificate[][] certificates;
13455
13456        // The list of instruction sets supported by this app. This is currently
13457        // only used during the rmdex() phase to clean up resources. We can get rid of this
13458        // if we move dex files under the common app path.
13459        /* nullable */ String[] instructionSets;
13460
13461        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13462                int installFlags, String installerPackageName, String volumeUuid,
13463                UserHandle user, String[] instructionSets,
13464                String abiOverride, String[] installGrantPermissions,
13465                String traceMethod, int traceCookie, Certificate[][] certificates) {
13466            this.origin = origin;
13467            this.move = move;
13468            this.installFlags = installFlags;
13469            this.observer = observer;
13470            this.installerPackageName = installerPackageName;
13471            this.volumeUuid = volumeUuid;
13472            this.user = user;
13473            this.instructionSets = instructionSets;
13474            this.abiOverride = abiOverride;
13475            this.installGrantPermissions = installGrantPermissions;
13476            this.traceMethod = traceMethod;
13477            this.traceCookie = traceCookie;
13478            this.certificates = certificates;
13479        }
13480
13481        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13482        abstract int doPreInstall(int status);
13483
13484        /**
13485         * Rename package into final resting place. All paths on the given
13486         * scanned package should be updated to reflect the rename.
13487         */
13488        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13489        abstract int doPostInstall(int status, int uid);
13490
13491        /** @see PackageSettingBase#codePathString */
13492        abstract String getCodePath();
13493        /** @see PackageSettingBase#resourcePathString */
13494        abstract String getResourcePath();
13495
13496        // Need installer lock especially for dex file removal.
13497        abstract void cleanUpResourcesLI();
13498        abstract boolean doPostDeleteLI(boolean delete);
13499
13500        /**
13501         * Called before the source arguments are copied. This is used mostly
13502         * for MoveParams when it needs to read the source file to put it in the
13503         * destination.
13504         */
13505        int doPreCopy() {
13506            return PackageManager.INSTALL_SUCCEEDED;
13507        }
13508
13509        /**
13510         * Called after the source arguments are copied. This is used mostly for
13511         * MoveParams when it needs to read the source file to put it in the
13512         * destination.
13513         */
13514        int doPostCopy(int uid) {
13515            return PackageManager.INSTALL_SUCCEEDED;
13516        }
13517
13518        protected boolean isFwdLocked() {
13519            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13520        }
13521
13522        protected boolean isExternalAsec() {
13523            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13524        }
13525
13526        protected boolean isEphemeral() {
13527            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13528        }
13529
13530        UserHandle getUser() {
13531            return user;
13532        }
13533    }
13534
13535    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13536        if (!allCodePaths.isEmpty()) {
13537            if (instructionSets == null) {
13538                throw new IllegalStateException("instructionSet == null");
13539            }
13540            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13541            for (String codePath : allCodePaths) {
13542                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13543                    try {
13544                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13545                    } catch (InstallerException ignored) {
13546                    }
13547                }
13548            }
13549        }
13550    }
13551
13552    /**
13553     * Logic to handle installation of non-ASEC applications, including copying
13554     * and renaming logic.
13555     */
13556    class FileInstallArgs extends InstallArgs {
13557        private File codeFile;
13558        private File resourceFile;
13559
13560        // Example topology:
13561        // /data/app/com.example/base.apk
13562        // /data/app/com.example/split_foo.apk
13563        // /data/app/com.example/lib/arm/libfoo.so
13564        // /data/app/com.example/lib/arm64/libfoo.so
13565        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13566
13567        /** New install */
13568        FileInstallArgs(InstallParams params) {
13569            super(params.origin, params.move, params.observer, params.installFlags,
13570                    params.installerPackageName, params.volumeUuid,
13571                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13572                    params.grantedRuntimePermissions,
13573                    params.traceMethod, params.traceCookie, params.certificates);
13574            if (isFwdLocked()) {
13575                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13576            }
13577        }
13578
13579        /** Existing install */
13580        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13581            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13582                    null, null, null, 0, null /*certificates*/);
13583            this.codeFile = (codePath != null) ? new File(codePath) : null;
13584            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13585        }
13586
13587        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13588            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13589            try {
13590                return doCopyApk(imcs, temp);
13591            } finally {
13592                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13593            }
13594        }
13595
13596        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13597            if (origin.staged) {
13598                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13599                codeFile = origin.file;
13600                resourceFile = origin.file;
13601                return PackageManager.INSTALL_SUCCEEDED;
13602            }
13603
13604            try {
13605                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13606                final File tempDir =
13607                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13608                codeFile = tempDir;
13609                resourceFile = tempDir;
13610            } catch (IOException e) {
13611                Slog.w(TAG, "Failed to create copy file: " + e);
13612                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13613            }
13614
13615            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13616                @Override
13617                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13618                    if (!FileUtils.isValidExtFilename(name)) {
13619                        throw new IllegalArgumentException("Invalid filename: " + name);
13620                    }
13621                    try {
13622                        final File file = new File(codeFile, name);
13623                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13624                                O_RDWR | O_CREAT, 0644);
13625                        Os.chmod(file.getAbsolutePath(), 0644);
13626                        return new ParcelFileDescriptor(fd);
13627                    } catch (ErrnoException e) {
13628                        throw new RemoteException("Failed to open: " + e.getMessage());
13629                    }
13630                }
13631            };
13632
13633            int ret = PackageManager.INSTALL_SUCCEEDED;
13634            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13635            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13636                Slog.e(TAG, "Failed to copy package");
13637                return ret;
13638            }
13639
13640            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13641            NativeLibraryHelper.Handle handle = null;
13642            try {
13643                handle = NativeLibraryHelper.Handle.create(codeFile);
13644                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13645                        abiOverride);
13646            } catch (IOException e) {
13647                Slog.e(TAG, "Copying native libraries failed", e);
13648                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13649            } finally {
13650                IoUtils.closeQuietly(handle);
13651            }
13652
13653            return ret;
13654        }
13655
13656        int doPreInstall(int status) {
13657            if (status != PackageManager.INSTALL_SUCCEEDED) {
13658                cleanUp();
13659            }
13660            return status;
13661        }
13662
13663        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13664            if (status != PackageManager.INSTALL_SUCCEEDED) {
13665                cleanUp();
13666                return false;
13667            }
13668
13669            final File targetDir = codeFile.getParentFile();
13670            final File beforeCodeFile = codeFile;
13671            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13672
13673            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13674            try {
13675                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13676            } catch (ErrnoException e) {
13677                Slog.w(TAG, "Failed to rename", e);
13678                return false;
13679            }
13680
13681            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13682                Slog.w(TAG, "Failed to restorecon");
13683                return false;
13684            }
13685
13686            // Reflect the rename internally
13687            codeFile = afterCodeFile;
13688            resourceFile = afterCodeFile;
13689
13690            // Reflect the rename in scanned details
13691            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13692            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13693                    afterCodeFile, pkg.baseCodePath));
13694            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13695                    afterCodeFile, pkg.splitCodePaths));
13696
13697            // Reflect the rename in app info
13698            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13699            pkg.setApplicationInfoCodePath(pkg.codePath);
13700            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13701            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13702            pkg.setApplicationInfoResourcePath(pkg.codePath);
13703            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13704            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13705
13706            return true;
13707        }
13708
13709        int doPostInstall(int status, int uid) {
13710            if (status != PackageManager.INSTALL_SUCCEEDED) {
13711                cleanUp();
13712            }
13713            return status;
13714        }
13715
13716        @Override
13717        String getCodePath() {
13718            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13719        }
13720
13721        @Override
13722        String getResourcePath() {
13723            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13724        }
13725
13726        private boolean cleanUp() {
13727            if (codeFile == null || !codeFile.exists()) {
13728                return false;
13729            }
13730
13731            removeCodePathLI(codeFile);
13732
13733            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13734                resourceFile.delete();
13735            }
13736
13737            return true;
13738        }
13739
13740        void cleanUpResourcesLI() {
13741            // Try enumerating all code paths before deleting
13742            List<String> allCodePaths = Collections.EMPTY_LIST;
13743            if (codeFile != null && codeFile.exists()) {
13744                try {
13745                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13746                    allCodePaths = pkg.getAllCodePaths();
13747                } catch (PackageParserException e) {
13748                    // Ignored; we tried our best
13749                }
13750            }
13751
13752            cleanUp();
13753            removeDexFiles(allCodePaths, instructionSets);
13754        }
13755
13756        boolean doPostDeleteLI(boolean delete) {
13757            // XXX err, shouldn't we respect the delete flag?
13758            cleanUpResourcesLI();
13759            return true;
13760        }
13761    }
13762
13763    private boolean isAsecExternal(String cid) {
13764        final String asecPath = PackageHelper.getSdFilesystem(cid);
13765        return !asecPath.startsWith(mAsecInternalPath);
13766    }
13767
13768    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13769            PackageManagerException {
13770        if (copyRet < 0) {
13771            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13772                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13773                throw new PackageManagerException(copyRet, message);
13774            }
13775        }
13776    }
13777
13778    /**
13779     * Extract the MountService "container ID" from the full code path of an
13780     * .apk.
13781     */
13782    static String cidFromCodePath(String fullCodePath) {
13783        int eidx = fullCodePath.lastIndexOf("/");
13784        String subStr1 = fullCodePath.substring(0, eidx);
13785        int sidx = subStr1.lastIndexOf("/");
13786        return subStr1.substring(sidx+1, eidx);
13787    }
13788
13789    /**
13790     * Logic to handle installation of ASEC applications, including copying and
13791     * renaming logic.
13792     */
13793    class AsecInstallArgs extends InstallArgs {
13794        static final String RES_FILE_NAME = "pkg.apk";
13795        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13796
13797        String cid;
13798        String packagePath;
13799        String resourcePath;
13800
13801        /** New install */
13802        AsecInstallArgs(InstallParams params) {
13803            super(params.origin, params.move, params.observer, params.installFlags,
13804                    params.installerPackageName, params.volumeUuid,
13805                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13806                    params.grantedRuntimePermissions,
13807                    params.traceMethod, params.traceCookie, params.certificates);
13808        }
13809
13810        /** Existing install */
13811        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13812                        boolean isExternal, boolean isForwardLocked) {
13813            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13814              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13815                    instructionSets, null, null, null, 0, null /*certificates*/);
13816            // Hackily pretend we're still looking at a full code path
13817            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13818                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13819            }
13820
13821            // Extract cid from fullCodePath
13822            int eidx = fullCodePath.lastIndexOf("/");
13823            String subStr1 = fullCodePath.substring(0, eidx);
13824            int sidx = subStr1.lastIndexOf("/");
13825            cid = subStr1.substring(sidx+1, eidx);
13826            setMountPath(subStr1);
13827        }
13828
13829        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13830            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13831              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13832                    instructionSets, null, null, null, 0, null /*certificates*/);
13833            this.cid = cid;
13834            setMountPath(PackageHelper.getSdDir(cid));
13835        }
13836
13837        void createCopyFile() {
13838            cid = mInstallerService.allocateExternalStageCidLegacy();
13839        }
13840
13841        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13842            if (origin.staged && origin.cid != null) {
13843                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13844                cid = origin.cid;
13845                setMountPath(PackageHelper.getSdDir(cid));
13846                return PackageManager.INSTALL_SUCCEEDED;
13847            }
13848
13849            if (temp) {
13850                createCopyFile();
13851            } else {
13852                /*
13853                 * Pre-emptively destroy the container since it's destroyed if
13854                 * copying fails due to it existing anyway.
13855                 */
13856                PackageHelper.destroySdDir(cid);
13857            }
13858
13859            final String newMountPath = imcs.copyPackageToContainer(
13860                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13861                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13862
13863            if (newMountPath != null) {
13864                setMountPath(newMountPath);
13865                return PackageManager.INSTALL_SUCCEEDED;
13866            } else {
13867                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13868            }
13869        }
13870
13871        @Override
13872        String getCodePath() {
13873            return packagePath;
13874        }
13875
13876        @Override
13877        String getResourcePath() {
13878            return resourcePath;
13879        }
13880
13881        int doPreInstall(int status) {
13882            if (status != PackageManager.INSTALL_SUCCEEDED) {
13883                // Destroy container
13884                PackageHelper.destroySdDir(cid);
13885            } else {
13886                boolean mounted = PackageHelper.isContainerMounted(cid);
13887                if (!mounted) {
13888                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13889                            Process.SYSTEM_UID);
13890                    if (newMountPath != null) {
13891                        setMountPath(newMountPath);
13892                    } else {
13893                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13894                    }
13895                }
13896            }
13897            return status;
13898        }
13899
13900        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13901            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13902            String newMountPath = null;
13903            if (PackageHelper.isContainerMounted(cid)) {
13904                // Unmount the container
13905                if (!PackageHelper.unMountSdDir(cid)) {
13906                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13907                    return false;
13908                }
13909            }
13910            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13911                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13912                        " which might be stale. Will try to clean up.");
13913                // Clean up the stale container and proceed to recreate.
13914                if (!PackageHelper.destroySdDir(newCacheId)) {
13915                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13916                    return false;
13917                }
13918                // Successfully cleaned up stale container. Try to rename again.
13919                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13920                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13921                            + " inspite of cleaning it up.");
13922                    return false;
13923                }
13924            }
13925            if (!PackageHelper.isContainerMounted(newCacheId)) {
13926                Slog.w(TAG, "Mounting container " + newCacheId);
13927                newMountPath = PackageHelper.mountSdDir(newCacheId,
13928                        getEncryptKey(), Process.SYSTEM_UID);
13929            } else {
13930                newMountPath = PackageHelper.getSdDir(newCacheId);
13931            }
13932            if (newMountPath == null) {
13933                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13934                return false;
13935            }
13936            Log.i(TAG, "Succesfully renamed " + cid +
13937                    " to " + newCacheId +
13938                    " at new path: " + newMountPath);
13939            cid = newCacheId;
13940
13941            final File beforeCodeFile = new File(packagePath);
13942            setMountPath(newMountPath);
13943            final File afterCodeFile = new File(packagePath);
13944
13945            // Reflect the rename in scanned details
13946            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13947            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13948                    afterCodeFile, pkg.baseCodePath));
13949            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13950                    afterCodeFile, pkg.splitCodePaths));
13951
13952            // Reflect the rename in app info
13953            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13954            pkg.setApplicationInfoCodePath(pkg.codePath);
13955            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13956            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13957            pkg.setApplicationInfoResourcePath(pkg.codePath);
13958            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13959            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13960
13961            return true;
13962        }
13963
13964        private void setMountPath(String mountPath) {
13965            final File mountFile = new File(mountPath);
13966
13967            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13968            if (monolithicFile.exists()) {
13969                packagePath = monolithicFile.getAbsolutePath();
13970                if (isFwdLocked()) {
13971                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13972                } else {
13973                    resourcePath = packagePath;
13974                }
13975            } else {
13976                packagePath = mountFile.getAbsolutePath();
13977                resourcePath = packagePath;
13978            }
13979        }
13980
13981        int doPostInstall(int status, int uid) {
13982            if (status != PackageManager.INSTALL_SUCCEEDED) {
13983                cleanUp();
13984            } else {
13985                final int groupOwner;
13986                final String protectedFile;
13987                if (isFwdLocked()) {
13988                    groupOwner = UserHandle.getSharedAppGid(uid);
13989                    protectedFile = RES_FILE_NAME;
13990                } else {
13991                    groupOwner = -1;
13992                    protectedFile = null;
13993                }
13994
13995                if (uid < Process.FIRST_APPLICATION_UID
13996                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13997                    Slog.e(TAG, "Failed to finalize " + cid);
13998                    PackageHelper.destroySdDir(cid);
13999                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14000                }
14001
14002                boolean mounted = PackageHelper.isContainerMounted(cid);
14003                if (!mounted) {
14004                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14005                }
14006            }
14007            return status;
14008        }
14009
14010        private void cleanUp() {
14011            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14012
14013            // Destroy secure container
14014            PackageHelper.destroySdDir(cid);
14015        }
14016
14017        private List<String> getAllCodePaths() {
14018            final File codeFile = new File(getCodePath());
14019            if (codeFile != null && codeFile.exists()) {
14020                try {
14021                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14022                    return pkg.getAllCodePaths();
14023                } catch (PackageParserException e) {
14024                    // Ignored; we tried our best
14025                }
14026            }
14027            return Collections.EMPTY_LIST;
14028        }
14029
14030        void cleanUpResourcesLI() {
14031            // Enumerate all code paths before deleting
14032            cleanUpResourcesLI(getAllCodePaths());
14033        }
14034
14035        private void cleanUpResourcesLI(List<String> allCodePaths) {
14036            cleanUp();
14037            removeDexFiles(allCodePaths, instructionSets);
14038        }
14039
14040        String getPackageName() {
14041            return getAsecPackageName(cid);
14042        }
14043
14044        boolean doPostDeleteLI(boolean delete) {
14045            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14046            final List<String> allCodePaths = getAllCodePaths();
14047            boolean mounted = PackageHelper.isContainerMounted(cid);
14048            if (mounted) {
14049                // Unmount first
14050                if (PackageHelper.unMountSdDir(cid)) {
14051                    mounted = false;
14052                }
14053            }
14054            if (!mounted && delete) {
14055                cleanUpResourcesLI(allCodePaths);
14056            }
14057            return !mounted;
14058        }
14059
14060        @Override
14061        int doPreCopy() {
14062            if (isFwdLocked()) {
14063                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14064                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14065                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14066                }
14067            }
14068
14069            return PackageManager.INSTALL_SUCCEEDED;
14070        }
14071
14072        @Override
14073        int doPostCopy(int uid) {
14074            if (isFwdLocked()) {
14075                if (uid < Process.FIRST_APPLICATION_UID
14076                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14077                                RES_FILE_NAME)) {
14078                    Slog.e(TAG, "Failed to finalize " + cid);
14079                    PackageHelper.destroySdDir(cid);
14080                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14081                }
14082            }
14083
14084            return PackageManager.INSTALL_SUCCEEDED;
14085        }
14086    }
14087
14088    /**
14089     * Logic to handle movement of existing installed applications.
14090     */
14091    class MoveInstallArgs extends InstallArgs {
14092        private File codeFile;
14093        private File resourceFile;
14094
14095        /** New install */
14096        MoveInstallArgs(InstallParams params) {
14097            super(params.origin, params.move, params.observer, params.installFlags,
14098                    params.installerPackageName, params.volumeUuid,
14099                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14100                    params.grantedRuntimePermissions,
14101                    params.traceMethod, params.traceCookie, params.certificates);
14102        }
14103
14104        int copyApk(IMediaContainerService imcs, boolean temp) {
14105            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14106                    + move.fromUuid + " to " + move.toUuid);
14107            synchronized (mInstaller) {
14108                try {
14109                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14110                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14111                } catch (InstallerException e) {
14112                    Slog.w(TAG, "Failed to move app", e);
14113                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14114                }
14115            }
14116
14117            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14118            resourceFile = codeFile;
14119            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14120
14121            return PackageManager.INSTALL_SUCCEEDED;
14122        }
14123
14124        int doPreInstall(int status) {
14125            if (status != PackageManager.INSTALL_SUCCEEDED) {
14126                cleanUp(move.toUuid);
14127            }
14128            return status;
14129        }
14130
14131        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14132            if (status != PackageManager.INSTALL_SUCCEEDED) {
14133                cleanUp(move.toUuid);
14134                return false;
14135            }
14136
14137            // Reflect the move in app info
14138            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14139            pkg.setApplicationInfoCodePath(pkg.codePath);
14140            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14141            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14142            pkg.setApplicationInfoResourcePath(pkg.codePath);
14143            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14144            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14145
14146            return true;
14147        }
14148
14149        int doPostInstall(int status, int uid) {
14150            if (status == PackageManager.INSTALL_SUCCEEDED) {
14151                cleanUp(move.fromUuid);
14152            } else {
14153                cleanUp(move.toUuid);
14154            }
14155            return status;
14156        }
14157
14158        @Override
14159        String getCodePath() {
14160            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14161        }
14162
14163        @Override
14164        String getResourcePath() {
14165            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14166        }
14167
14168        private boolean cleanUp(String volumeUuid) {
14169            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14170                    move.dataAppName);
14171            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14172            final int[] userIds = sUserManager.getUserIds();
14173            synchronized (mInstallLock) {
14174                // Clean up both app data and code
14175                // All package moves are frozen until finished
14176                for (int userId : userIds) {
14177                    try {
14178                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14179                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14180                    } catch (InstallerException e) {
14181                        Slog.w(TAG, String.valueOf(e));
14182                    }
14183                }
14184                removeCodePathLI(codeFile);
14185            }
14186            return true;
14187        }
14188
14189        void cleanUpResourcesLI() {
14190            throw new UnsupportedOperationException();
14191        }
14192
14193        boolean doPostDeleteLI(boolean delete) {
14194            throw new UnsupportedOperationException();
14195        }
14196    }
14197
14198    static String getAsecPackageName(String packageCid) {
14199        int idx = packageCid.lastIndexOf("-");
14200        if (idx == -1) {
14201            return packageCid;
14202        }
14203        return packageCid.substring(0, idx);
14204    }
14205
14206    // Utility method used to create code paths based on package name and available index.
14207    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14208        String idxStr = "";
14209        int idx = 1;
14210        // Fall back to default value of idx=1 if prefix is not
14211        // part of oldCodePath
14212        if (oldCodePath != null) {
14213            String subStr = oldCodePath;
14214            // Drop the suffix right away
14215            if (suffix != null && subStr.endsWith(suffix)) {
14216                subStr = subStr.substring(0, subStr.length() - suffix.length());
14217            }
14218            // If oldCodePath already contains prefix find out the
14219            // ending index to either increment or decrement.
14220            int sidx = subStr.lastIndexOf(prefix);
14221            if (sidx != -1) {
14222                subStr = subStr.substring(sidx + prefix.length());
14223                if (subStr != null) {
14224                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14225                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14226                    }
14227                    try {
14228                        idx = Integer.parseInt(subStr);
14229                        if (idx <= 1) {
14230                            idx++;
14231                        } else {
14232                            idx--;
14233                        }
14234                    } catch(NumberFormatException e) {
14235                    }
14236                }
14237            }
14238        }
14239        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14240        return prefix + idxStr;
14241    }
14242
14243    private File getNextCodePath(File targetDir, String packageName) {
14244        int suffix = 1;
14245        File result;
14246        do {
14247            result = new File(targetDir, packageName + "-" + suffix);
14248            suffix++;
14249        } while (result.exists());
14250        return result;
14251    }
14252
14253    // Utility method that returns the relative package path with respect
14254    // to the installation directory. Like say for /data/data/com.test-1.apk
14255    // string com.test-1 is returned.
14256    static String deriveCodePathName(String codePath) {
14257        if (codePath == null) {
14258            return null;
14259        }
14260        final File codeFile = new File(codePath);
14261        final String name = codeFile.getName();
14262        if (codeFile.isDirectory()) {
14263            return name;
14264        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14265            final int lastDot = name.lastIndexOf('.');
14266            return name.substring(0, lastDot);
14267        } else {
14268            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14269            return null;
14270        }
14271    }
14272
14273    static class PackageInstalledInfo {
14274        String name;
14275        int uid;
14276        // The set of users that originally had this package installed.
14277        int[] origUsers;
14278        // The set of users that now have this package installed.
14279        int[] newUsers;
14280        PackageParser.Package pkg;
14281        int returnCode;
14282        String returnMsg;
14283        PackageRemovedInfo removedInfo;
14284        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14285
14286        public void setError(int code, String msg) {
14287            setReturnCode(code);
14288            setReturnMessage(msg);
14289            Slog.w(TAG, msg);
14290        }
14291
14292        public void setError(String msg, PackageParserException e) {
14293            setReturnCode(e.error);
14294            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14295            Slog.w(TAG, msg, e);
14296        }
14297
14298        public void setError(String msg, PackageManagerException e) {
14299            returnCode = e.error;
14300            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14301            Slog.w(TAG, msg, e);
14302        }
14303
14304        public void setReturnCode(int returnCode) {
14305            this.returnCode = returnCode;
14306            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14307            for (int i = 0; i < childCount; i++) {
14308                addedChildPackages.valueAt(i).returnCode = returnCode;
14309            }
14310        }
14311
14312        private void setReturnMessage(String returnMsg) {
14313            this.returnMsg = returnMsg;
14314            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14315            for (int i = 0; i < childCount; i++) {
14316                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14317            }
14318        }
14319
14320        // In some error cases we want to convey more info back to the observer
14321        String origPackage;
14322        String origPermission;
14323    }
14324
14325    /*
14326     * Install a non-existing package.
14327     */
14328    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14329            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14330            PackageInstalledInfo res) {
14331        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14332
14333        // Remember this for later, in case we need to rollback this install
14334        String pkgName = pkg.packageName;
14335
14336        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14337
14338        synchronized(mPackages) {
14339            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14340            if (renamedPackage != null) {
14341                // A package with the same name is already installed, though
14342                // it has been renamed to an older name.  The package we
14343                // are trying to install should be installed as an update to
14344                // the existing one, but that has not been requested, so bail.
14345                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14346                        + " without first uninstalling package running as "
14347                        + renamedPackage);
14348                return;
14349            }
14350            if (mPackages.containsKey(pkgName)) {
14351                // Don't allow installation over an existing package with the same name.
14352                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14353                        + " without first uninstalling.");
14354                return;
14355            }
14356        }
14357
14358        try {
14359            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14360                    System.currentTimeMillis(), user);
14361
14362            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14363
14364            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14365                prepareAppDataAfterInstallLIF(newPackage);
14366
14367            } else {
14368                // Remove package from internal structures, but keep around any
14369                // data that might have already existed
14370                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14371                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14372            }
14373        } catch (PackageManagerException e) {
14374            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14375        }
14376
14377        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14378    }
14379
14380    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14381        // Can't rotate keys during boot or if sharedUser.
14382        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14383                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14384            return false;
14385        }
14386        // app is using upgradeKeySets; make sure all are valid
14387        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14388        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14389        for (int i = 0; i < upgradeKeySets.length; i++) {
14390            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14391                Slog.wtf(TAG, "Package "
14392                         + (oldPs.name != null ? oldPs.name : "<null>")
14393                         + " contains upgrade-key-set reference to unknown key-set: "
14394                         + upgradeKeySets[i]
14395                         + " reverting to signatures check.");
14396                return false;
14397            }
14398        }
14399        return true;
14400    }
14401
14402    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14403        // Upgrade keysets are being used.  Determine if new package has a superset of the
14404        // required keys.
14405        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14406        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14407        for (int i = 0; i < upgradeKeySets.length; i++) {
14408            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14409            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14410                return true;
14411            }
14412        }
14413        return false;
14414    }
14415
14416    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14417        try (DigestInputStream digestStream =
14418                new DigestInputStream(new FileInputStream(file), digest)) {
14419            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14420        }
14421    }
14422
14423    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14424            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14425        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14426
14427        final PackageParser.Package oldPackage;
14428        final String pkgName = pkg.packageName;
14429        final int[] allUsers;
14430        final int[] installedUsers;
14431
14432        synchronized(mPackages) {
14433            oldPackage = mPackages.get(pkgName);
14434            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14435
14436            // don't allow upgrade to target a release SDK from a pre-release SDK
14437            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14438                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14439            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14440                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14441            if (oldTargetsPreRelease
14442                    && !newTargetsPreRelease
14443                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14444                Slog.w(TAG, "Can't install package targeting released sdk");
14445                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14446                return;
14447            }
14448
14449            // don't allow an upgrade from full to ephemeral
14450            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14451            if (isEphemeral && !oldIsEphemeral) {
14452                // can't downgrade from full to ephemeral
14453                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14454                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14455                return;
14456            }
14457
14458            // verify signatures are valid
14459            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14460            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14461                if (!checkUpgradeKeySetLP(ps, pkg)) {
14462                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14463                            "New package not signed by keys specified by upgrade-keysets: "
14464                                    + pkgName);
14465                    return;
14466                }
14467            } else {
14468                // default to original signature matching
14469                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14470                        != PackageManager.SIGNATURE_MATCH) {
14471                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14472                            "New package has a different signature: " + pkgName);
14473                    return;
14474                }
14475            }
14476
14477            // don't allow a system upgrade unless the upgrade hash matches
14478            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14479                byte[] digestBytes = null;
14480                try {
14481                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14482                    updateDigest(digest, new File(pkg.baseCodePath));
14483                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14484                        for (String path : pkg.splitCodePaths) {
14485                            updateDigest(digest, new File(path));
14486                        }
14487                    }
14488                    digestBytes = digest.digest();
14489                } catch (NoSuchAlgorithmException | IOException e) {
14490                    res.setError(INSTALL_FAILED_INVALID_APK,
14491                            "Could not compute hash: " + pkgName);
14492                    return;
14493                }
14494                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14495                    res.setError(INSTALL_FAILED_INVALID_APK,
14496                            "New package fails restrict-update check: " + pkgName);
14497                    return;
14498                }
14499                // retain upgrade restriction
14500                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14501            }
14502
14503            // Check for shared user id changes
14504            String invalidPackageName =
14505                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14506            if (invalidPackageName != null) {
14507                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14508                        "Package " + invalidPackageName + " tried to change user "
14509                                + oldPackage.mSharedUserId);
14510                return;
14511            }
14512
14513            // In case of rollback, remember per-user/profile install state
14514            allUsers = sUserManager.getUserIds();
14515            installedUsers = ps.queryInstalledUsers(allUsers, true);
14516        }
14517
14518        // Update what is removed
14519        res.removedInfo = new PackageRemovedInfo();
14520        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14521        res.removedInfo.removedPackage = oldPackage.packageName;
14522        res.removedInfo.isUpdate = true;
14523        res.removedInfo.origUsers = installedUsers;
14524        final int childCount = (oldPackage.childPackages != null)
14525                ? oldPackage.childPackages.size() : 0;
14526        for (int i = 0; i < childCount; i++) {
14527            boolean childPackageUpdated = false;
14528            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14529            if (res.addedChildPackages != null) {
14530                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14531                if (childRes != null) {
14532                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14533                    childRes.removedInfo.removedPackage = childPkg.packageName;
14534                    childRes.removedInfo.isUpdate = true;
14535                    childPackageUpdated = true;
14536                }
14537            }
14538            if (!childPackageUpdated) {
14539                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14540                childRemovedRes.removedPackage = childPkg.packageName;
14541                childRemovedRes.isUpdate = false;
14542                childRemovedRes.dataRemoved = true;
14543                synchronized (mPackages) {
14544                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14545                    if (childPs != null) {
14546                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14547                    }
14548                }
14549                if (res.removedInfo.removedChildPackages == null) {
14550                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14551                }
14552                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14553            }
14554        }
14555
14556        boolean sysPkg = (isSystemApp(oldPackage));
14557        if (sysPkg) {
14558            // Set the system/privileged flags as needed
14559            final boolean privileged =
14560                    (oldPackage.applicationInfo.privateFlags
14561                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14562            final int systemPolicyFlags = policyFlags
14563                    | PackageParser.PARSE_IS_SYSTEM
14564                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14565
14566            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14567                    user, allUsers, installerPackageName, res);
14568        } else {
14569            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14570                    user, allUsers, installerPackageName, res);
14571        }
14572    }
14573
14574    public List<String> getPreviousCodePaths(String packageName) {
14575        final PackageSetting ps = mSettings.mPackages.get(packageName);
14576        final List<String> result = new ArrayList<String>();
14577        if (ps != null && ps.oldCodePaths != null) {
14578            result.addAll(ps.oldCodePaths);
14579        }
14580        return result;
14581    }
14582
14583    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14584            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14585            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14586        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14587                + deletedPackage);
14588
14589        String pkgName = deletedPackage.packageName;
14590        boolean deletedPkg = true;
14591        boolean addedPkg = false;
14592        boolean updatedSettings = false;
14593        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14594        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14595                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14596
14597        final long origUpdateTime = (pkg.mExtras != null)
14598                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14599
14600        // First delete the existing package while retaining the data directory
14601        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14602                res.removedInfo, true, pkg)) {
14603            // If the existing package wasn't successfully deleted
14604            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14605            deletedPkg = false;
14606        } else {
14607            // Successfully deleted the old package; proceed with replace.
14608
14609            // If deleted package lived in a container, give users a chance to
14610            // relinquish resources before killing.
14611            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14612                if (DEBUG_INSTALL) {
14613                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14614                }
14615                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14616                final ArrayList<String> pkgList = new ArrayList<String>(1);
14617                pkgList.add(deletedPackage.applicationInfo.packageName);
14618                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14619            }
14620
14621            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14622                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14623            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14624
14625            try {
14626                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14627                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14628                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14629
14630                // Update the in-memory copy of the previous code paths.
14631                PackageSetting ps = mSettings.mPackages.get(pkgName);
14632                if (!killApp) {
14633                    if (ps.oldCodePaths == null) {
14634                        ps.oldCodePaths = new ArraySet<>();
14635                    }
14636                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14637                    if (deletedPackage.splitCodePaths != null) {
14638                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14639                    }
14640                } else {
14641                    ps.oldCodePaths = null;
14642                }
14643                if (ps.childPackageNames != null) {
14644                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14645                        final String childPkgName = ps.childPackageNames.get(i);
14646                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14647                        childPs.oldCodePaths = ps.oldCodePaths;
14648                    }
14649                }
14650                prepareAppDataAfterInstallLIF(newPackage);
14651                addedPkg = true;
14652            } catch (PackageManagerException e) {
14653                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14654            }
14655        }
14656
14657        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14658            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14659
14660            // Revert all internal state mutations and added folders for the failed install
14661            if (addedPkg) {
14662                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14663                        res.removedInfo, true, null);
14664            }
14665
14666            // Restore the old package
14667            if (deletedPkg) {
14668                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14669                File restoreFile = new File(deletedPackage.codePath);
14670                // Parse old package
14671                boolean oldExternal = isExternal(deletedPackage);
14672                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14673                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14674                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14675                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14676                try {
14677                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14678                            null);
14679                } catch (PackageManagerException e) {
14680                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14681                            + e.getMessage());
14682                    return;
14683                }
14684
14685                synchronized (mPackages) {
14686                    // Ensure the installer package name up to date
14687                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14688
14689                    // Update permissions for restored package
14690                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14691
14692                    mSettings.writeLPr();
14693                }
14694
14695                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14696            }
14697        } else {
14698            synchronized (mPackages) {
14699                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14700                if (ps != null) {
14701                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14702                    if (res.removedInfo.removedChildPackages != null) {
14703                        final int childCount = res.removedInfo.removedChildPackages.size();
14704                        // Iterate in reverse as we may modify the collection
14705                        for (int i = childCount - 1; i >= 0; i--) {
14706                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14707                            if (res.addedChildPackages.containsKey(childPackageName)) {
14708                                res.removedInfo.removedChildPackages.removeAt(i);
14709                            } else {
14710                                PackageRemovedInfo childInfo = res.removedInfo
14711                                        .removedChildPackages.valueAt(i);
14712                                childInfo.removedForAllUsers = mPackages.get(
14713                                        childInfo.removedPackage) == null;
14714                            }
14715                        }
14716                    }
14717                }
14718            }
14719        }
14720    }
14721
14722    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14723            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14724            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14725        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14726                + ", old=" + deletedPackage);
14727
14728        final boolean disabledSystem;
14729
14730        // Remove existing system package
14731        removePackageLI(deletedPackage, true);
14732
14733        synchronized (mPackages) {
14734            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14735        }
14736        if (!disabledSystem) {
14737            // We didn't need to disable the .apk as a current system package,
14738            // which means we are replacing another update that is already
14739            // installed.  We need to make sure to delete the older one's .apk.
14740            res.removedInfo.args = createInstallArgsForExisting(0,
14741                    deletedPackage.applicationInfo.getCodePath(),
14742                    deletedPackage.applicationInfo.getResourcePath(),
14743                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14744        } else {
14745            res.removedInfo.args = null;
14746        }
14747
14748        // Successfully disabled the old package. Now proceed with re-installation
14749        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14750                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14751        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14752
14753        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14754        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14755                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14756
14757        PackageParser.Package newPackage = null;
14758        try {
14759            // Add the package to the internal data structures
14760            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14761
14762            // Set the update and install times
14763            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14764            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14765                    System.currentTimeMillis());
14766
14767            // Update the package dynamic state if succeeded
14768            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14769                // Now that the install succeeded make sure we remove data
14770                // directories for any child package the update removed.
14771                final int deletedChildCount = (deletedPackage.childPackages != null)
14772                        ? deletedPackage.childPackages.size() : 0;
14773                final int newChildCount = (newPackage.childPackages != null)
14774                        ? newPackage.childPackages.size() : 0;
14775                for (int i = 0; i < deletedChildCount; i++) {
14776                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14777                    boolean childPackageDeleted = true;
14778                    for (int j = 0; j < newChildCount; j++) {
14779                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14780                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14781                            childPackageDeleted = false;
14782                            break;
14783                        }
14784                    }
14785                    if (childPackageDeleted) {
14786                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14787                                deletedChildPkg.packageName);
14788                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14789                            PackageRemovedInfo removedChildRes = res.removedInfo
14790                                    .removedChildPackages.get(deletedChildPkg.packageName);
14791                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14792                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14793                        }
14794                    }
14795                }
14796
14797                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14798                prepareAppDataAfterInstallLIF(newPackage);
14799            }
14800        } catch (PackageManagerException e) {
14801            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14802            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14803        }
14804
14805        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14806            // Re installation failed. Restore old information
14807            // Remove new pkg information
14808            if (newPackage != null) {
14809                removeInstalledPackageLI(newPackage, true);
14810            }
14811            // Add back the old system package
14812            try {
14813                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14814            } catch (PackageManagerException e) {
14815                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14816            }
14817
14818            synchronized (mPackages) {
14819                if (disabledSystem) {
14820                    enableSystemPackageLPw(deletedPackage);
14821                }
14822
14823                // Ensure the installer package name up to date
14824                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14825
14826                // Update permissions for restored package
14827                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14828
14829                mSettings.writeLPr();
14830            }
14831
14832            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14833                    + " after failed upgrade");
14834        }
14835    }
14836
14837    /**
14838     * Checks whether the parent or any of the child packages have a change shared
14839     * user. For a package to be a valid update the shred users of the parent and
14840     * the children should match. We may later support changing child shared users.
14841     * @param oldPkg The updated package.
14842     * @param newPkg The update package.
14843     * @return The shared user that change between the versions.
14844     */
14845    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14846            PackageParser.Package newPkg) {
14847        // Check parent shared user
14848        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14849            return newPkg.packageName;
14850        }
14851        // Check child shared users
14852        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14853        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14854        for (int i = 0; i < newChildCount; i++) {
14855            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14856            // If this child was present, did it have the same shared user?
14857            for (int j = 0; j < oldChildCount; j++) {
14858                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14859                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14860                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14861                    return newChildPkg.packageName;
14862                }
14863            }
14864        }
14865        return null;
14866    }
14867
14868    private void removeNativeBinariesLI(PackageSetting ps) {
14869        // Remove the lib path for the parent package
14870        if (ps != null) {
14871            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14872            // Remove the lib path for the child packages
14873            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14874            for (int i = 0; i < childCount; i++) {
14875                PackageSetting childPs = null;
14876                synchronized (mPackages) {
14877                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14878                }
14879                if (childPs != null) {
14880                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14881                            .legacyNativeLibraryPathString);
14882                }
14883            }
14884        }
14885    }
14886
14887    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14888        // Enable the parent package
14889        mSettings.enableSystemPackageLPw(pkg.packageName);
14890        // Enable the child packages
14891        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14892        for (int i = 0; i < childCount; i++) {
14893            PackageParser.Package childPkg = pkg.childPackages.get(i);
14894            mSettings.enableSystemPackageLPw(childPkg.packageName);
14895        }
14896    }
14897
14898    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14899            PackageParser.Package newPkg) {
14900        // Disable the parent package (parent always replaced)
14901        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14902        // Disable the child packages
14903        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14904        for (int i = 0; i < childCount; i++) {
14905            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14906            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14907            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14908        }
14909        return disabled;
14910    }
14911
14912    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14913            String installerPackageName) {
14914        // Enable the parent package
14915        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14916        // Enable the child packages
14917        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14918        for (int i = 0; i < childCount; i++) {
14919            PackageParser.Package childPkg = pkg.childPackages.get(i);
14920            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14921        }
14922    }
14923
14924    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14925        // Collect all used permissions in the UID
14926        ArraySet<String> usedPermissions = new ArraySet<>();
14927        final int packageCount = su.packages.size();
14928        for (int i = 0; i < packageCount; i++) {
14929            PackageSetting ps = su.packages.valueAt(i);
14930            if (ps.pkg == null) {
14931                continue;
14932            }
14933            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14934            for (int j = 0; j < requestedPermCount; j++) {
14935                String permission = ps.pkg.requestedPermissions.get(j);
14936                BasePermission bp = mSettings.mPermissions.get(permission);
14937                if (bp != null) {
14938                    usedPermissions.add(permission);
14939                }
14940            }
14941        }
14942
14943        PermissionsState permissionsState = su.getPermissionsState();
14944        // Prune install permissions
14945        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14946        final int installPermCount = installPermStates.size();
14947        for (int i = installPermCount - 1; i >= 0;  i--) {
14948            PermissionState permissionState = installPermStates.get(i);
14949            if (!usedPermissions.contains(permissionState.getName())) {
14950                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14951                if (bp != null) {
14952                    permissionsState.revokeInstallPermission(bp);
14953                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14954                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14955                }
14956            }
14957        }
14958
14959        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14960
14961        // Prune runtime permissions
14962        for (int userId : allUserIds) {
14963            List<PermissionState> runtimePermStates = permissionsState
14964                    .getRuntimePermissionStates(userId);
14965            final int runtimePermCount = runtimePermStates.size();
14966            for (int i = runtimePermCount - 1; i >= 0; i--) {
14967                PermissionState permissionState = runtimePermStates.get(i);
14968                if (!usedPermissions.contains(permissionState.getName())) {
14969                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14970                    if (bp != null) {
14971                        permissionsState.revokeRuntimePermission(bp, userId);
14972                        permissionsState.updatePermissionFlags(bp, userId,
14973                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14974                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14975                                runtimePermissionChangedUserIds, userId);
14976                    }
14977                }
14978            }
14979        }
14980
14981        return runtimePermissionChangedUserIds;
14982    }
14983
14984    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14985            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14986        // Update the parent package setting
14987        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14988                res, user);
14989        // Update the child packages setting
14990        final int childCount = (newPackage.childPackages != null)
14991                ? newPackage.childPackages.size() : 0;
14992        for (int i = 0; i < childCount; i++) {
14993            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14994            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14995            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14996                    childRes.origUsers, childRes, user);
14997        }
14998    }
14999
15000    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15001            String installerPackageName, int[] allUsers, int[] installedForUsers,
15002            PackageInstalledInfo res, UserHandle user) {
15003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15004
15005        String pkgName = newPackage.packageName;
15006        synchronized (mPackages) {
15007            //write settings. the installStatus will be incomplete at this stage.
15008            //note that the new package setting would have already been
15009            //added to mPackages. It hasn't been persisted yet.
15010            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15011            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15012            mSettings.writeLPr();
15013            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15014        }
15015
15016        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15017        synchronized (mPackages) {
15018            updatePermissionsLPw(newPackage.packageName, newPackage,
15019                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15020                            ? UPDATE_PERMISSIONS_ALL : 0));
15021            // For system-bundled packages, we assume that installing an upgraded version
15022            // of the package implies that the user actually wants to run that new code,
15023            // so we enable the package.
15024            PackageSetting ps = mSettings.mPackages.get(pkgName);
15025            final int userId = user.getIdentifier();
15026            if (ps != null) {
15027                if (isSystemApp(newPackage)) {
15028                    if (DEBUG_INSTALL) {
15029                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15030                    }
15031                    // Enable system package for requested users
15032                    if (res.origUsers != null) {
15033                        for (int origUserId : res.origUsers) {
15034                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15035                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15036                                        origUserId, installerPackageName);
15037                            }
15038                        }
15039                    }
15040                    // Also convey the prior install/uninstall state
15041                    if (allUsers != null && installedForUsers != null) {
15042                        for (int currentUserId : allUsers) {
15043                            final boolean installed = ArrayUtils.contains(
15044                                    installedForUsers, currentUserId);
15045                            if (DEBUG_INSTALL) {
15046                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15047                            }
15048                            ps.setInstalled(installed, currentUserId);
15049                        }
15050                        // these install state changes will be persisted in the
15051                        // upcoming call to mSettings.writeLPr().
15052                    }
15053                }
15054                // It's implied that when a user requests installation, they want the app to be
15055                // installed and enabled.
15056                if (userId != UserHandle.USER_ALL) {
15057                    ps.setInstalled(true, userId);
15058                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15059                }
15060            }
15061            res.name = pkgName;
15062            res.uid = newPackage.applicationInfo.uid;
15063            res.pkg = newPackage;
15064            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15065            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15066            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15067            //to update install status
15068            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15069            mSettings.writeLPr();
15070            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15071        }
15072
15073        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15074    }
15075
15076    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15077        try {
15078            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15079            installPackageLI(args, res);
15080        } finally {
15081            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15082        }
15083    }
15084
15085    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15086        final int installFlags = args.installFlags;
15087        final String installerPackageName = args.installerPackageName;
15088        final String volumeUuid = args.volumeUuid;
15089        final File tmpPackageFile = new File(args.getCodePath());
15090        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15091        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15092                || (args.volumeUuid != null));
15093        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15094        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15095        boolean replace = false;
15096        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15097        if (args.move != null) {
15098            // moving a complete application; perform an initial scan on the new install location
15099            scanFlags |= SCAN_INITIAL;
15100        }
15101        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15102            scanFlags |= SCAN_DONT_KILL_APP;
15103        }
15104
15105        // Result object to be returned
15106        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15107
15108        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15109
15110        // Sanity check
15111        if (ephemeral && (forwardLocked || onExternal)) {
15112            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15113                    + " external=" + onExternal);
15114            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15115            return;
15116        }
15117
15118        // Retrieve PackageSettings and parse package
15119        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15120                | PackageParser.PARSE_ENFORCE_CODE
15121                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15122                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15123                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15124                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15125        PackageParser pp = new PackageParser();
15126        pp.setSeparateProcesses(mSeparateProcesses);
15127        pp.setDisplayMetrics(mMetrics);
15128
15129        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15130        final PackageParser.Package pkg;
15131        try {
15132            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15133        } catch (PackageParserException e) {
15134            res.setError("Failed parse during installPackageLI", e);
15135            return;
15136        } finally {
15137            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15138        }
15139
15140        // If we are installing a clustered package add results for the children
15141        if (pkg.childPackages != null) {
15142            synchronized (mPackages) {
15143                final int childCount = pkg.childPackages.size();
15144                for (int i = 0; i < childCount; i++) {
15145                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15146                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15147                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15148                    childRes.pkg = childPkg;
15149                    childRes.name = childPkg.packageName;
15150                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15151                    if (childPs != null) {
15152                        childRes.origUsers = childPs.queryInstalledUsers(
15153                                sUserManager.getUserIds(), true);
15154                    }
15155                    if ((mPackages.containsKey(childPkg.packageName))) {
15156                        childRes.removedInfo = new PackageRemovedInfo();
15157                        childRes.removedInfo.removedPackage = childPkg.packageName;
15158                    }
15159                    if (res.addedChildPackages == null) {
15160                        res.addedChildPackages = new ArrayMap<>();
15161                    }
15162                    res.addedChildPackages.put(childPkg.packageName, childRes);
15163                }
15164            }
15165        }
15166
15167        // If package doesn't declare API override, mark that we have an install
15168        // time CPU ABI override.
15169        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15170            pkg.cpuAbiOverride = args.abiOverride;
15171        }
15172
15173        String pkgName = res.name = pkg.packageName;
15174        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15175            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15176                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15177                return;
15178            }
15179        }
15180
15181        try {
15182            // either use what we've been given or parse directly from the APK
15183            if (args.certificates != null) {
15184                try {
15185                    PackageParser.populateCertificates(pkg, args.certificates);
15186                } catch (PackageParserException e) {
15187                    // there was something wrong with the certificates we were given;
15188                    // try to pull them from the APK
15189                    PackageParser.collectCertificates(pkg, parseFlags);
15190                }
15191            } else {
15192                PackageParser.collectCertificates(pkg, parseFlags);
15193            }
15194        } catch (PackageParserException e) {
15195            res.setError("Failed collect during installPackageLI", e);
15196            return;
15197        }
15198
15199        // Get rid of all references to package scan path via parser.
15200        pp = null;
15201        String oldCodePath = null;
15202        boolean systemApp = false;
15203        synchronized (mPackages) {
15204            // Check if installing already existing package
15205            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15206                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15207                if (pkg.mOriginalPackages != null
15208                        && pkg.mOriginalPackages.contains(oldName)
15209                        && mPackages.containsKey(oldName)) {
15210                    // This package is derived from an original package,
15211                    // and this device has been updating from that original
15212                    // name.  We must continue using the original name, so
15213                    // rename the new package here.
15214                    pkg.setPackageName(oldName);
15215                    pkgName = pkg.packageName;
15216                    replace = true;
15217                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15218                            + oldName + " pkgName=" + pkgName);
15219                } else if (mPackages.containsKey(pkgName)) {
15220                    // This package, under its official name, already exists
15221                    // on the device; we should replace it.
15222                    replace = true;
15223                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15224                }
15225
15226                // Child packages are installed through the parent package
15227                if (pkg.parentPackage != null) {
15228                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15229                            "Package " + pkg.packageName + " is child of package "
15230                                    + pkg.parentPackage.parentPackage + ". Child packages "
15231                                    + "can be updated only through the parent package.");
15232                    return;
15233                }
15234
15235                if (replace) {
15236                    // Prevent apps opting out from runtime permissions
15237                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15238                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15239                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15240                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15241                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15242                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15243                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15244                                        + " doesn't support runtime permissions but the old"
15245                                        + " target SDK " + oldTargetSdk + " does.");
15246                        return;
15247                    }
15248
15249                    // Prevent installing of child packages
15250                    if (oldPackage.parentPackage != null) {
15251                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15252                                "Package " + pkg.packageName + " is child of package "
15253                                        + oldPackage.parentPackage + ". Child packages "
15254                                        + "can be updated only through the parent package.");
15255                        return;
15256                    }
15257                }
15258            }
15259
15260            PackageSetting ps = mSettings.mPackages.get(pkgName);
15261            if (ps != null) {
15262                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15263
15264                // Quick sanity check that we're signed correctly if updating;
15265                // we'll check this again later when scanning, but we want to
15266                // bail early here before tripping over redefined permissions.
15267                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15268                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15269                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15270                                + pkg.packageName + " upgrade keys do not match the "
15271                                + "previously installed version");
15272                        return;
15273                    }
15274                } else {
15275                    try {
15276                        verifySignaturesLP(ps, pkg);
15277                    } catch (PackageManagerException e) {
15278                        res.setError(e.error, e.getMessage());
15279                        return;
15280                    }
15281                }
15282
15283                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15284                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15285                    systemApp = (ps.pkg.applicationInfo.flags &
15286                            ApplicationInfo.FLAG_SYSTEM) != 0;
15287                }
15288                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15289            }
15290
15291            // Check whether the newly-scanned package wants to define an already-defined perm
15292            int N = pkg.permissions.size();
15293            for (int i = N-1; i >= 0; i--) {
15294                PackageParser.Permission perm = pkg.permissions.get(i);
15295                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15296                if (bp != null) {
15297                    // If the defining package is signed with our cert, it's okay.  This
15298                    // also includes the "updating the same package" case, of course.
15299                    // "updating same package" could also involve key-rotation.
15300                    final boolean sigsOk;
15301                    if (bp.sourcePackage.equals(pkg.packageName)
15302                            && (bp.packageSetting instanceof PackageSetting)
15303                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15304                                    scanFlags))) {
15305                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15306                    } else {
15307                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15308                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15309                    }
15310                    if (!sigsOk) {
15311                        // If the owning package is the system itself, we log but allow
15312                        // install to proceed; we fail the install on all other permission
15313                        // redefinitions.
15314                        if (!bp.sourcePackage.equals("android")) {
15315                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15316                                    + pkg.packageName + " attempting to redeclare permission "
15317                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15318                            res.origPermission = perm.info.name;
15319                            res.origPackage = bp.sourcePackage;
15320                            return;
15321                        } else {
15322                            Slog.w(TAG, "Package " + pkg.packageName
15323                                    + " attempting to redeclare system permission "
15324                                    + perm.info.name + "; ignoring new declaration");
15325                            pkg.permissions.remove(i);
15326                        }
15327                    }
15328                }
15329            }
15330        }
15331
15332        if (systemApp) {
15333            if (onExternal) {
15334                // Abort update; system app can't be replaced with app on sdcard
15335                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15336                        "Cannot install updates to system apps on sdcard");
15337                return;
15338            } else if (ephemeral) {
15339                // Abort update; system app can't be replaced with an ephemeral app
15340                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15341                        "Cannot update a system app with an ephemeral app");
15342                return;
15343            }
15344        }
15345
15346        if (args.move != null) {
15347            // We did an in-place move, so dex is ready to roll
15348            scanFlags |= SCAN_NO_DEX;
15349            scanFlags |= SCAN_MOVE;
15350
15351            synchronized (mPackages) {
15352                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15353                if (ps == null) {
15354                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15355                            "Missing settings for moved package " + pkgName);
15356                }
15357
15358                // We moved the entire application as-is, so bring over the
15359                // previously derived ABI information.
15360                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15361                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15362            }
15363
15364        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15365            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15366            scanFlags |= SCAN_NO_DEX;
15367
15368            try {
15369                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15370                    args.abiOverride : pkg.cpuAbiOverride);
15371                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15372                        true /*extractLibs*/, mAppLib32InstallDir);
15373            } catch (PackageManagerException pme) {
15374                Slog.e(TAG, "Error deriving application ABI", pme);
15375                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15376                return;
15377            }
15378
15379            // Shared libraries for the package need to be updated.
15380            synchronized (mPackages) {
15381                try {
15382                    updateSharedLibrariesLPr(pkg, null);
15383                } catch (PackageManagerException e) {
15384                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15385                }
15386            }
15387            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15388            // Do not run PackageDexOptimizer through the local performDexOpt
15389            // method because `pkg` may not be in `mPackages` yet.
15390            //
15391            // Also, don't fail application installs if the dexopt step fails.
15392            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15393                    null /* instructionSets */, false /* checkProfiles */,
15394                    getCompilerFilterForReason(REASON_INSTALL),
15395                    getOrCreateCompilerPackageStats(pkg));
15396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15397
15398            // Notify BackgroundDexOptService that the package has been changed.
15399            // If this is an update of a package which used to fail to compile,
15400            // BDOS will remove it from its blacklist.
15401            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15402        }
15403
15404        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15405            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15406            return;
15407        }
15408
15409        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15410
15411        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15412                "installPackageLI")) {
15413            if (replace) {
15414                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15415                        installerPackageName, res);
15416            } else {
15417                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15418                        args.user, installerPackageName, volumeUuid, res);
15419            }
15420        }
15421        synchronized (mPackages) {
15422            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15423            if (ps != null) {
15424                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15425            }
15426
15427            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15428            for (int i = 0; i < childCount; i++) {
15429                PackageParser.Package childPkg = pkg.childPackages.get(i);
15430                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15431                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15432                if (childPs != null) {
15433                    childRes.newUsers = childPs.queryInstalledUsers(
15434                            sUserManager.getUserIds(), true);
15435                }
15436            }
15437        }
15438    }
15439
15440    private void startIntentFilterVerifications(int userId, boolean replacing,
15441            PackageParser.Package pkg) {
15442        if (mIntentFilterVerifierComponent == null) {
15443            Slog.w(TAG, "No IntentFilter verification will not be done as "
15444                    + "there is no IntentFilterVerifier available!");
15445            return;
15446        }
15447
15448        final int verifierUid = getPackageUid(
15449                mIntentFilterVerifierComponent.getPackageName(),
15450                MATCH_DEBUG_TRIAGED_MISSING,
15451                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15452
15453        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15454        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15455        mHandler.sendMessage(msg);
15456
15457        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15458        for (int i = 0; i < childCount; i++) {
15459            PackageParser.Package childPkg = pkg.childPackages.get(i);
15460            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15461            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15462            mHandler.sendMessage(msg);
15463        }
15464    }
15465
15466    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15467            PackageParser.Package pkg) {
15468        int size = pkg.activities.size();
15469        if (size == 0) {
15470            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15471                    "No activity, so no need to verify any IntentFilter!");
15472            return;
15473        }
15474
15475        final boolean hasDomainURLs = hasDomainURLs(pkg);
15476        if (!hasDomainURLs) {
15477            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15478                    "No domain URLs, so no need to verify any IntentFilter!");
15479            return;
15480        }
15481
15482        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15483                + " if any IntentFilter from the " + size
15484                + " Activities needs verification ...");
15485
15486        int count = 0;
15487        final String packageName = pkg.packageName;
15488
15489        synchronized (mPackages) {
15490            // If this is a new install and we see that we've already run verification for this
15491            // package, we have nothing to do: it means the state was restored from backup.
15492            if (!replacing) {
15493                IntentFilterVerificationInfo ivi =
15494                        mSettings.getIntentFilterVerificationLPr(packageName);
15495                if (ivi != null) {
15496                    if (DEBUG_DOMAIN_VERIFICATION) {
15497                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15498                                + ivi.getStatusString());
15499                    }
15500                    return;
15501                }
15502            }
15503
15504            // If any filters need to be verified, then all need to be.
15505            boolean needToVerify = false;
15506            for (PackageParser.Activity a : pkg.activities) {
15507                for (ActivityIntentInfo filter : a.intents) {
15508                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15509                        if (DEBUG_DOMAIN_VERIFICATION) {
15510                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15511                        }
15512                        needToVerify = true;
15513                        break;
15514                    }
15515                }
15516            }
15517
15518            if (needToVerify) {
15519                final int verificationId = mIntentFilterVerificationToken++;
15520                for (PackageParser.Activity a : pkg.activities) {
15521                    for (ActivityIntentInfo filter : a.intents) {
15522                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15523                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15524                                    "Verification needed for IntentFilter:" + filter.toString());
15525                            mIntentFilterVerifier.addOneIntentFilterVerification(
15526                                    verifierUid, userId, verificationId, filter, packageName);
15527                            count++;
15528                        }
15529                    }
15530                }
15531            }
15532        }
15533
15534        if (count > 0) {
15535            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15536                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15537                    +  " for userId:" + userId);
15538            mIntentFilterVerifier.startVerifications(userId);
15539        } else {
15540            if (DEBUG_DOMAIN_VERIFICATION) {
15541                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15542            }
15543        }
15544    }
15545
15546    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15547        final ComponentName cn  = filter.activity.getComponentName();
15548        final String packageName = cn.getPackageName();
15549
15550        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15551                packageName);
15552        if (ivi == null) {
15553            return true;
15554        }
15555        int status = ivi.getStatus();
15556        switch (status) {
15557            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15558            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15559                return true;
15560
15561            default:
15562                // Nothing to do
15563                return false;
15564        }
15565    }
15566
15567    private static boolean isMultiArch(ApplicationInfo info) {
15568        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15569    }
15570
15571    private static boolean isExternal(PackageParser.Package pkg) {
15572        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15573    }
15574
15575    private static boolean isExternal(PackageSetting ps) {
15576        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15577    }
15578
15579    private static boolean isEphemeral(PackageParser.Package pkg) {
15580        return pkg.applicationInfo.isEphemeralApp();
15581    }
15582
15583    private static boolean isEphemeral(PackageSetting ps) {
15584        return ps.pkg != null && isEphemeral(ps.pkg);
15585    }
15586
15587    private static boolean isSystemApp(PackageParser.Package pkg) {
15588        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15589    }
15590
15591    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15592        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15593    }
15594
15595    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15596        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15597    }
15598
15599    private static boolean isSystemApp(PackageSetting ps) {
15600        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15601    }
15602
15603    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15604        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15605    }
15606
15607    private int packageFlagsToInstallFlags(PackageSetting ps) {
15608        int installFlags = 0;
15609        if (isEphemeral(ps)) {
15610            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15611        }
15612        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15613            // This existing package was an external ASEC install when we have
15614            // the external flag without a UUID
15615            installFlags |= PackageManager.INSTALL_EXTERNAL;
15616        }
15617        if (ps.isForwardLocked()) {
15618            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15619        }
15620        return installFlags;
15621    }
15622
15623    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15624        if (isExternal(pkg)) {
15625            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15626                return StorageManager.UUID_PRIMARY_PHYSICAL;
15627            } else {
15628                return pkg.volumeUuid;
15629            }
15630        } else {
15631            return StorageManager.UUID_PRIVATE_INTERNAL;
15632        }
15633    }
15634
15635    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15636        if (isExternal(pkg)) {
15637            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15638                return mSettings.getExternalVersion();
15639            } else {
15640                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15641            }
15642        } else {
15643            return mSettings.getInternalVersion();
15644        }
15645    }
15646
15647    private void deleteTempPackageFiles() {
15648        final FilenameFilter filter = new FilenameFilter() {
15649            public boolean accept(File dir, String name) {
15650                return name.startsWith("vmdl") && name.endsWith(".tmp");
15651            }
15652        };
15653        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15654            file.delete();
15655        }
15656    }
15657
15658    @Override
15659    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15660            int flags) {
15661        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15662                flags);
15663    }
15664
15665    @Override
15666    public void deletePackage(final String packageName,
15667            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15668        mContext.enforceCallingOrSelfPermission(
15669                android.Manifest.permission.DELETE_PACKAGES, null);
15670        Preconditions.checkNotNull(packageName);
15671        Preconditions.checkNotNull(observer);
15672        final int uid = Binder.getCallingUid();
15673        if (!isOrphaned(packageName)
15674                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15675            try {
15676                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15677                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15678                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15679                observer.onUserActionRequired(intent);
15680            } catch (RemoteException re) {
15681            }
15682            return;
15683        }
15684        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15685        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15686        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15687            mContext.enforceCallingOrSelfPermission(
15688                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15689                    "deletePackage for user " + userId);
15690        }
15691
15692        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15693            try {
15694                observer.onPackageDeleted(packageName,
15695                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15696            } catch (RemoteException re) {
15697            }
15698            return;
15699        }
15700
15701        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15702            try {
15703                observer.onPackageDeleted(packageName,
15704                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15705            } catch (RemoteException re) {
15706            }
15707            return;
15708        }
15709
15710        if (DEBUG_REMOVE) {
15711            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15712                    + " deleteAllUsers: " + deleteAllUsers );
15713        }
15714        // Queue up an async operation since the package deletion may take a little while.
15715        mHandler.post(new Runnable() {
15716            public void run() {
15717                mHandler.removeCallbacks(this);
15718                int returnCode;
15719                if (!deleteAllUsers) {
15720                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15721                } else {
15722                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15723                    // If nobody is blocking uninstall, proceed with delete for all users
15724                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15725                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15726                    } else {
15727                        // Otherwise uninstall individually for users with blockUninstalls=false
15728                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15729                        for (int userId : users) {
15730                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15731                                returnCode = deletePackageX(packageName, userId, userFlags);
15732                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15733                                    Slog.w(TAG, "Package delete failed for user " + userId
15734                                            + ", returnCode " + returnCode);
15735                                }
15736                            }
15737                        }
15738                        // The app has only been marked uninstalled for certain users.
15739                        // We still need to report that delete was blocked
15740                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15741                    }
15742                }
15743                try {
15744                    observer.onPackageDeleted(packageName, returnCode, null);
15745                } catch (RemoteException e) {
15746                    Log.i(TAG, "Observer no longer exists.");
15747                } //end catch
15748            } //end run
15749        });
15750    }
15751
15752    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15753        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15754              || callingUid == Process.SYSTEM_UID) {
15755            return true;
15756        }
15757        final int callingUserId = UserHandle.getUserId(callingUid);
15758        // If the caller installed the pkgName, then allow it to silently uninstall.
15759        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15760            return true;
15761        }
15762
15763        // Allow package verifier to silently uninstall.
15764        if (mRequiredVerifierPackage != null &&
15765                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15766            return true;
15767        }
15768
15769        // Allow package uninstaller to silently uninstall.
15770        if (mRequiredUninstallerPackage != null &&
15771                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15772            return true;
15773        }
15774
15775        // Allow storage manager to silently uninstall.
15776        if (mStorageManagerPackage != null &&
15777                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15778            return true;
15779        }
15780        return false;
15781    }
15782
15783    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15784        int[] result = EMPTY_INT_ARRAY;
15785        for (int userId : userIds) {
15786            if (getBlockUninstallForUser(packageName, userId)) {
15787                result = ArrayUtils.appendInt(result, userId);
15788            }
15789        }
15790        return result;
15791    }
15792
15793    @Override
15794    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15795        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15796    }
15797
15798    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15799        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15800                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15801        try {
15802            if (dpm != null) {
15803                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15804                        /* callingUserOnly =*/ false);
15805                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15806                        : deviceOwnerComponentName.getPackageName();
15807                // Does the package contains the device owner?
15808                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15809                // this check is probably not needed, since DO should be registered as a device
15810                // admin on some user too. (Original bug for this: b/17657954)
15811                if (packageName.equals(deviceOwnerPackageName)) {
15812                    return true;
15813                }
15814                // Does it contain a device admin for any user?
15815                int[] users;
15816                if (userId == UserHandle.USER_ALL) {
15817                    users = sUserManager.getUserIds();
15818                } else {
15819                    users = new int[]{userId};
15820                }
15821                for (int i = 0; i < users.length; ++i) {
15822                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15823                        return true;
15824                    }
15825                }
15826            }
15827        } catch (RemoteException e) {
15828        }
15829        return false;
15830    }
15831
15832    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15833        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15834    }
15835
15836    /**
15837     *  This method is an internal method that could be get invoked either
15838     *  to delete an installed package or to clean up a failed installation.
15839     *  After deleting an installed package, a broadcast is sent to notify any
15840     *  listeners that the package has been removed. For cleaning up a failed
15841     *  installation, the broadcast is not necessary since the package's
15842     *  installation wouldn't have sent the initial broadcast either
15843     *  The key steps in deleting a package are
15844     *  deleting the package information in internal structures like mPackages,
15845     *  deleting the packages base directories through installd
15846     *  updating mSettings to reflect current status
15847     *  persisting settings for later use
15848     *  sending a broadcast if necessary
15849     */
15850    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15851        final PackageRemovedInfo info = new PackageRemovedInfo();
15852        final boolean res;
15853
15854        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15855                ? UserHandle.USER_ALL : userId;
15856
15857        if (isPackageDeviceAdmin(packageName, removeUser)) {
15858            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15859            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15860        }
15861
15862        PackageSetting uninstalledPs = null;
15863
15864        // for the uninstall-updates case and restricted profiles, remember the per-
15865        // user handle installed state
15866        int[] allUsers;
15867        synchronized (mPackages) {
15868            uninstalledPs = mSettings.mPackages.get(packageName);
15869            if (uninstalledPs == null) {
15870                Slog.w(TAG, "Not removing non-existent package " + packageName);
15871                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15872            }
15873            allUsers = sUserManager.getUserIds();
15874            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15875        }
15876
15877        final int freezeUser;
15878        if (isUpdatedSystemApp(uninstalledPs)
15879                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15880            // We're downgrading a system app, which will apply to all users, so
15881            // freeze them all during the downgrade
15882            freezeUser = UserHandle.USER_ALL;
15883        } else {
15884            freezeUser = removeUser;
15885        }
15886
15887        synchronized (mInstallLock) {
15888            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15889            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15890                    deleteFlags, "deletePackageX")) {
15891                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15892                        deleteFlags | REMOVE_CHATTY, info, true, null);
15893            }
15894            synchronized (mPackages) {
15895                if (res) {
15896                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15897                }
15898            }
15899        }
15900
15901        if (res) {
15902            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15903            info.sendPackageRemovedBroadcasts(killApp);
15904            info.sendSystemPackageUpdatedBroadcasts();
15905            info.sendSystemPackageAppearedBroadcasts();
15906        }
15907        // Force a gc here.
15908        Runtime.getRuntime().gc();
15909        // Delete the resources here after sending the broadcast to let
15910        // other processes clean up before deleting resources.
15911        if (info.args != null) {
15912            synchronized (mInstallLock) {
15913                info.args.doPostDeleteLI(true);
15914            }
15915        }
15916
15917        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15918    }
15919
15920    class PackageRemovedInfo {
15921        String removedPackage;
15922        int uid = -1;
15923        int removedAppId = -1;
15924        int[] origUsers;
15925        int[] removedUsers = null;
15926        boolean isRemovedPackageSystemUpdate = false;
15927        boolean isUpdate;
15928        boolean dataRemoved;
15929        boolean removedForAllUsers;
15930        // Clean up resources deleted packages.
15931        InstallArgs args = null;
15932        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15933        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15934
15935        void sendPackageRemovedBroadcasts(boolean killApp) {
15936            sendPackageRemovedBroadcastInternal(killApp);
15937            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15938            for (int i = 0; i < childCount; i++) {
15939                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15940                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15941            }
15942        }
15943
15944        void sendSystemPackageUpdatedBroadcasts() {
15945            if (isRemovedPackageSystemUpdate) {
15946                sendSystemPackageUpdatedBroadcastsInternal();
15947                final int childCount = (removedChildPackages != null)
15948                        ? removedChildPackages.size() : 0;
15949                for (int i = 0; i < childCount; i++) {
15950                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15951                    if (childInfo.isRemovedPackageSystemUpdate) {
15952                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15953                    }
15954                }
15955            }
15956        }
15957
15958        void sendSystemPackageAppearedBroadcasts() {
15959            final int packageCount = (appearedChildPackages != null)
15960                    ? appearedChildPackages.size() : 0;
15961            for (int i = 0; i < packageCount; i++) {
15962                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15963                sendPackageAddedForNewUsers(installedInfo.name, true,
15964                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
15965            }
15966        }
15967
15968        private void sendSystemPackageUpdatedBroadcastsInternal() {
15969            Bundle extras = new Bundle(2);
15970            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15971            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15972            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15973                    extras, 0, null, null, null);
15974            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15975                    extras, 0, null, null, null);
15976            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15977                    null, 0, removedPackage, null, null);
15978        }
15979
15980        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15981            Bundle extras = new Bundle(2);
15982            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15983            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15984            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15985            if (isUpdate || isRemovedPackageSystemUpdate) {
15986                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15987            }
15988            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15989            if (removedPackage != null) {
15990                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15991                        extras, 0, null, null, removedUsers);
15992                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15993                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15994                            removedPackage, extras, 0, null, null, removedUsers);
15995                }
15996            }
15997            if (removedAppId >= 0) {
15998                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15999                        removedUsers);
16000            }
16001        }
16002    }
16003
16004    /*
16005     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16006     * flag is not set, the data directory is removed as well.
16007     * make sure this flag is set for partially installed apps. If not its meaningless to
16008     * delete a partially installed application.
16009     */
16010    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16011            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16012        String packageName = ps.name;
16013        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16014        // Retrieve object to delete permissions for shared user later on
16015        final PackageParser.Package deletedPkg;
16016        final PackageSetting deletedPs;
16017        // reader
16018        synchronized (mPackages) {
16019            deletedPkg = mPackages.get(packageName);
16020            deletedPs = mSettings.mPackages.get(packageName);
16021            if (outInfo != null) {
16022                outInfo.removedPackage = packageName;
16023                outInfo.removedUsers = deletedPs != null
16024                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16025                        : null;
16026            }
16027        }
16028
16029        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16030
16031        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16032            final PackageParser.Package resolvedPkg;
16033            if (deletedPkg != null) {
16034                resolvedPkg = deletedPkg;
16035            } else {
16036                // We don't have a parsed package when it lives on an ejected
16037                // adopted storage device, so fake something together
16038                resolvedPkg = new PackageParser.Package(ps.name);
16039                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16040            }
16041            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16042                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16043            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16044            if (outInfo != null) {
16045                outInfo.dataRemoved = true;
16046            }
16047            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16048        }
16049
16050        // writer
16051        synchronized (mPackages) {
16052            if (deletedPs != null) {
16053                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16054                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16055                    clearDefaultBrowserIfNeeded(packageName);
16056                    if (outInfo != null) {
16057                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16058                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16059                    }
16060                    updatePermissionsLPw(deletedPs.name, null, 0);
16061                    if (deletedPs.sharedUser != null) {
16062                        // Remove permissions associated with package. Since runtime
16063                        // permissions are per user we have to kill the removed package
16064                        // or packages running under the shared user of the removed
16065                        // package if revoking the permissions requested only by the removed
16066                        // package is successful and this causes a change in gids.
16067                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16068                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16069                                    userId);
16070                            if (userIdToKill == UserHandle.USER_ALL
16071                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16072                                // If gids changed for this user, kill all affected packages.
16073                                mHandler.post(new Runnable() {
16074                                    @Override
16075                                    public void run() {
16076                                        // This has to happen with no lock held.
16077                                        killApplication(deletedPs.name, deletedPs.appId,
16078                                                KILL_APP_REASON_GIDS_CHANGED);
16079                                    }
16080                                });
16081                                break;
16082                            }
16083                        }
16084                    }
16085                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16086                }
16087                // make sure to preserve per-user disabled state if this removal was just
16088                // a downgrade of a system app to the factory package
16089                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16090                    if (DEBUG_REMOVE) {
16091                        Slog.d(TAG, "Propagating install state across downgrade");
16092                    }
16093                    for (int userId : allUserHandles) {
16094                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16095                        if (DEBUG_REMOVE) {
16096                            Slog.d(TAG, "    user " + userId + " => " + installed);
16097                        }
16098                        ps.setInstalled(installed, userId);
16099                    }
16100                }
16101            }
16102            // can downgrade to reader
16103            if (writeSettings) {
16104                // Save settings now
16105                mSettings.writeLPr();
16106            }
16107        }
16108        if (outInfo != null) {
16109            // A user ID was deleted here. Go through all users and remove it
16110            // from KeyStore.
16111            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16112        }
16113    }
16114
16115    static boolean locationIsPrivileged(File path) {
16116        try {
16117            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16118                    .getCanonicalPath();
16119            return path.getCanonicalPath().startsWith(privilegedAppDir);
16120        } catch (IOException e) {
16121            Slog.e(TAG, "Unable to access code path " + path);
16122        }
16123        return false;
16124    }
16125
16126    /*
16127     * Tries to delete system package.
16128     */
16129    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16130            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16131            boolean writeSettings) {
16132        if (deletedPs.parentPackageName != null) {
16133            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16134            return false;
16135        }
16136
16137        final boolean applyUserRestrictions
16138                = (allUserHandles != null) && (outInfo.origUsers != null);
16139        final PackageSetting disabledPs;
16140        // Confirm if the system package has been updated
16141        // An updated system app can be deleted. This will also have to restore
16142        // the system pkg from system partition
16143        // reader
16144        synchronized (mPackages) {
16145            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16146        }
16147
16148        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16149                + " disabledPs=" + disabledPs);
16150
16151        if (disabledPs == null) {
16152            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16153            return false;
16154        } else if (DEBUG_REMOVE) {
16155            Slog.d(TAG, "Deleting system pkg from data partition");
16156        }
16157
16158        if (DEBUG_REMOVE) {
16159            if (applyUserRestrictions) {
16160                Slog.d(TAG, "Remembering install states:");
16161                for (int userId : allUserHandles) {
16162                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16163                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16164                }
16165            }
16166        }
16167
16168        // Delete the updated package
16169        outInfo.isRemovedPackageSystemUpdate = true;
16170        if (outInfo.removedChildPackages != null) {
16171            final int childCount = (deletedPs.childPackageNames != null)
16172                    ? deletedPs.childPackageNames.size() : 0;
16173            for (int i = 0; i < childCount; i++) {
16174                String childPackageName = deletedPs.childPackageNames.get(i);
16175                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16176                        .contains(childPackageName)) {
16177                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16178                            childPackageName);
16179                    if (childInfo != null) {
16180                        childInfo.isRemovedPackageSystemUpdate = true;
16181                    }
16182                }
16183            }
16184        }
16185
16186        if (disabledPs.versionCode < deletedPs.versionCode) {
16187            // Delete data for downgrades
16188            flags &= ~PackageManager.DELETE_KEEP_DATA;
16189        } else {
16190            // Preserve data by setting flag
16191            flags |= PackageManager.DELETE_KEEP_DATA;
16192        }
16193
16194        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16195                outInfo, writeSettings, disabledPs.pkg);
16196        if (!ret) {
16197            return false;
16198        }
16199
16200        // writer
16201        synchronized (mPackages) {
16202            // Reinstate the old system package
16203            enableSystemPackageLPw(disabledPs.pkg);
16204            // Remove any native libraries from the upgraded package.
16205            removeNativeBinariesLI(deletedPs);
16206        }
16207
16208        // Install the system package
16209        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16210        int parseFlags = mDefParseFlags
16211                | PackageParser.PARSE_MUST_BE_APK
16212                | PackageParser.PARSE_IS_SYSTEM
16213                | PackageParser.PARSE_IS_SYSTEM_DIR;
16214        if (locationIsPrivileged(disabledPs.codePath)) {
16215            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16216        }
16217
16218        final PackageParser.Package newPkg;
16219        try {
16220            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16221        } catch (PackageManagerException e) {
16222            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16223                    + e.getMessage());
16224            return false;
16225        }
16226        try {
16227            // update shared libraries for the newly re-installed system package
16228            updateSharedLibrariesLPr(newPkg, null);
16229        } catch (PackageManagerException e) {
16230            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16231        }
16232
16233        prepareAppDataAfterInstallLIF(newPkg);
16234
16235        // writer
16236        synchronized (mPackages) {
16237            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16238
16239            // Propagate the permissions state as we do not want to drop on the floor
16240            // runtime permissions. The update permissions method below will take
16241            // care of removing obsolete permissions and grant install permissions.
16242            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16243            updatePermissionsLPw(newPkg.packageName, newPkg,
16244                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16245
16246            if (applyUserRestrictions) {
16247                if (DEBUG_REMOVE) {
16248                    Slog.d(TAG, "Propagating install state across reinstall");
16249                }
16250                for (int userId : allUserHandles) {
16251                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16252                    if (DEBUG_REMOVE) {
16253                        Slog.d(TAG, "    user " + userId + " => " + installed);
16254                    }
16255                    ps.setInstalled(installed, userId);
16256
16257                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16258                }
16259                // Regardless of writeSettings we need to ensure that this restriction
16260                // state propagation is persisted
16261                mSettings.writeAllUsersPackageRestrictionsLPr();
16262            }
16263            // can downgrade to reader here
16264            if (writeSettings) {
16265                mSettings.writeLPr();
16266            }
16267        }
16268        return true;
16269    }
16270
16271    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16272            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16273            PackageRemovedInfo outInfo, boolean writeSettings,
16274            PackageParser.Package replacingPackage) {
16275        synchronized (mPackages) {
16276            if (outInfo != null) {
16277                outInfo.uid = ps.appId;
16278            }
16279
16280            if (outInfo != null && outInfo.removedChildPackages != null) {
16281                final int childCount = (ps.childPackageNames != null)
16282                        ? ps.childPackageNames.size() : 0;
16283                for (int i = 0; i < childCount; i++) {
16284                    String childPackageName = ps.childPackageNames.get(i);
16285                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16286                    if (childPs == null) {
16287                        return false;
16288                    }
16289                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16290                            childPackageName);
16291                    if (childInfo != null) {
16292                        childInfo.uid = childPs.appId;
16293                    }
16294                }
16295            }
16296        }
16297
16298        // Delete package data from internal structures and also remove data if flag is set
16299        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16300
16301        // Delete the child packages data
16302        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16303        for (int i = 0; i < childCount; i++) {
16304            PackageSetting childPs;
16305            synchronized (mPackages) {
16306                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16307            }
16308            if (childPs != null) {
16309                PackageRemovedInfo childOutInfo = (outInfo != null
16310                        && outInfo.removedChildPackages != null)
16311                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16312                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16313                        && (replacingPackage != null
16314                        && !replacingPackage.hasChildPackage(childPs.name))
16315                        ? flags & ~DELETE_KEEP_DATA : flags;
16316                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16317                        deleteFlags, writeSettings);
16318            }
16319        }
16320
16321        // Delete application code and resources only for parent packages
16322        if (ps.parentPackageName == null) {
16323            if (deleteCodeAndResources && (outInfo != null)) {
16324                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16325                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16326                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16327            }
16328        }
16329
16330        return true;
16331    }
16332
16333    @Override
16334    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16335            int userId) {
16336        mContext.enforceCallingOrSelfPermission(
16337                android.Manifest.permission.DELETE_PACKAGES, null);
16338        synchronized (mPackages) {
16339            PackageSetting ps = mSettings.mPackages.get(packageName);
16340            if (ps == null) {
16341                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16342                return false;
16343            }
16344            if (!ps.getInstalled(userId)) {
16345                // Can't block uninstall for an app that is not installed or enabled.
16346                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16347                return false;
16348            }
16349            ps.setBlockUninstall(blockUninstall, userId);
16350            mSettings.writePackageRestrictionsLPr(userId);
16351        }
16352        return true;
16353    }
16354
16355    @Override
16356    public boolean getBlockUninstallForUser(String packageName, int userId) {
16357        synchronized (mPackages) {
16358            PackageSetting ps = mSettings.mPackages.get(packageName);
16359            if (ps == null) {
16360                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16361                return false;
16362            }
16363            return ps.getBlockUninstall(userId);
16364        }
16365    }
16366
16367    @Override
16368    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16369        int callingUid = Binder.getCallingUid();
16370        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16371            throw new SecurityException(
16372                    "setRequiredForSystemUser can only be run by the system or root");
16373        }
16374        synchronized (mPackages) {
16375            PackageSetting ps = mSettings.mPackages.get(packageName);
16376            if (ps == null) {
16377                Log.w(TAG, "Package doesn't exist: " + packageName);
16378                return false;
16379            }
16380            if (systemUserApp) {
16381                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16382            } else {
16383                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16384            }
16385            mSettings.writeLPr();
16386        }
16387        return true;
16388    }
16389
16390    /*
16391     * This method handles package deletion in general
16392     */
16393    private boolean deletePackageLIF(String packageName, UserHandle user,
16394            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16395            PackageRemovedInfo outInfo, boolean writeSettings,
16396            PackageParser.Package replacingPackage) {
16397        if (packageName == null) {
16398            Slog.w(TAG, "Attempt to delete null packageName.");
16399            return false;
16400        }
16401
16402        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16403
16404        PackageSetting ps;
16405
16406        synchronized (mPackages) {
16407            ps = mSettings.mPackages.get(packageName);
16408            if (ps == null) {
16409                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16410                return false;
16411            }
16412
16413            if (ps.parentPackageName != null && (!isSystemApp(ps)
16414                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16415                if (DEBUG_REMOVE) {
16416                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16417                            + ((user == null) ? UserHandle.USER_ALL : user));
16418                }
16419                final int removedUserId = (user != null) ? user.getIdentifier()
16420                        : UserHandle.USER_ALL;
16421                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16422                    return false;
16423                }
16424                markPackageUninstalledForUserLPw(ps, user);
16425                scheduleWritePackageRestrictionsLocked(user);
16426                return true;
16427            }
16428        }
16429
16430        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16431                && user.getIdentifier() != UserHandle.USER_ALL)) {
16432            // The caller is asking that the package only be deleted for a single
16433            // user.  To do this, we just mark its uninstalled state and delete
16434            // its data. If this is a system app, we only allow this to happen if
16435            // they have set the special DELETE_SYSTEM_APP which requests different
16436            // semantics than normal for uninstalling system apps.
16437            markPackageUninstalledForUserLPw(ps, user);
16438
16439            if (!isSystemApp(ps)) {
16440                // Do not uninstall the APK if an app should be cached
16441                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16442                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16443                    // Other user still have this package installed, so all
16444                    // we need to do is clear this user's data and save that
16445                    // it is uninstalled.
16446                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16447                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16448                        return false;
16449                    }
16450                    scheduleWritePackageRestrictionsLocked(user);
16451                    return true;
16452                } else {
16453                    // We need to set it back to 'installed' so the uninstall
16454                    // broadcasts will be sent correctly.
16455                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16456                    ps.setInstalled(true, user.getIdentifier());
16457                }
16458            } else {
16459                // This is a system app, so we assume that the
16460                // other users still have this package installed, so all
16461                // we need to do is clear this user's data and save that
16462                // it is uninstalled.
16463                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16464                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16465                    return false;
16466                }
16467                scheduleWritePackageRestrictionsLocked(user);
16468                return true;
16469            }
16470        }
16471
16472        // If we are deleting a composite package for all users, keep track
16473        // of result for each child.
16474        if (ps.childPackageNames != null && outInfo != null) {
16475            synchronized (mPackages) {
16476                final int childCount = ps.childPackageNames.size();
16477                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16478                for (int i = 0; i < childCount; i++) {
16479                    String childPackageName = ps.childPackageNames.get(i);
16480                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16481                    childInfo.removedPackage = childPackageName;
16482                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16483                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16484                    if (childPs != null) {
16485                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16486                    }
16487                }
16488            }
16489        }
16490
16491        boolean ret = false;
16492        if (isSystemApp(ps)) {
16493            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16494            // When an updated system application is deleted we delete the existing resources
16495            // as well and fall back to existing code in system partition
16496            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16497        } else {
16498            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16499            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16500                    outInfo, writeSettings, replacingPackage);
16501        }
16502
16503        // Take a note whether we deleted the package for all users
16504        if (outInfo != null) {
16505            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16506            if (outInfo.removedChildPackages != null) {
16507                synchronized (mPackages) {
16508                    final int childCount = outInfo.removedChildPackages.size();
16509                    for (int i = 0; i < childCount; i++) {
16510                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16511                        if (childInfo != null) {
16512                            childInfo.removedForAllUsers = mPackages.get(
16513                                    childInfo.removedPackage) == null;
16514                        }
16515                    }
16516                }
16517            }
16518            // If we uninstalled an update to a system app there may be some
16519            // child packages that appeared as they are declared in the system
16520            // app but were not declared in the update.
16521            if (isSystemApp(ps)) {
16522                synchronized (mPackages) {
16523                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16524                    final int childCount = (updatedPs.childPackageNames != null)
16525                            ? updatedPs.childPackageNames.size() : 0;
16526                    for (int i = 0; i < childCount; i++) {
16527                        String childPackageName = updatedPs.childPackageNames.get(i);
16528                        if (outInfo.removedChildPackages == null
16529                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16530                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16531                            if (childPs == null) {
16532                                continue;
16533                            }
16534                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16535                            installRes.name = childPackageName;
16536                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16537                            installRes.pkg = mPackages.get(childPackageName);
16538                            installRes.uid = childPs.pkg.applicationInfo.uid;
16539                            if (outInfo.appearedChildPackages == null) {
16540                                outInfo.appearedChildPackages = new ArrayMap<>();
16541                            }
16542                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16543                        }
16544                    }
16545                }
16546            }
16547        }
16548
16549        return ret;
16550    }
16551
16552    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16553        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16554                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16555        for (int nextUserId : userIds) {
16556            if (DEBUG_REMOVE) {
16557                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16558            }
16559            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16560                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16561                    false /*hidden*/, false /*suspended*/, null, null, null,
16562                    false /*blockUninstall*/,
16563                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16564        }
16565    }
16566
16567    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16568            PackageRemovedInfo outInfo) {
16569        final PackageParser.Package pkg;
16570        synchronized (mPackages) {
16571            pkg = mPackages.get(ps.name);
16572        }
16573
16574        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16575                : new int[] {userId};
16576        for (int nextUserId : userIds) {
16577            if (DEBUG_REMOVE) {
16578                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16579                        + nextUserId);
16580            }
16581
16582            destroyAppDataLIF(pkg, userId,
16583                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16584            destroyAppProfilesLIF(pkg, userId);
16585            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16586            schedulePackageCleaning(ps.name, nextUserId, false);
16587            synchronized (mPackages) {
16588                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16589                    scheduleWritePackageRestrictionsLocked(nextUserId);
16590                }
16591                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16592            }
16593        }
16594
16595        if (outInfo != null) {
16596            outInfo.removedPackage = ps.name;
16597            outInfo.removedAppId = ps.appId;
16598            outInfo.removedUsers = userIds;
16599        }
16600
16601        return true;
16602    }
16603
16604    private final class ClearStorageConnection implements ServiceConnection {
16605        IMediaContainerService mContainerService;
16606
16607        @Override
16608        public void onServiceConnected(ComponentName name, IBinder service) {
16609            synchronized (this) {
16610                mContainerService = IMediaContainerService.Stub.asInterface(service);
16611                notifyAll();
16612            }
16613        }
16614
16615        @Override
16616        public void onServiceDisconnected(ComponentName name) {
16617        }
16618    }
16619
16620    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16621        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16622
16623        final boolean mounted;
16624        if (Environment.isExternalStorageEmulated()) {
16625            mounted = true;
16626        } else {
16627            final String status = Environment.getExternalStorageState();
16628
16629            mounted = status.equals(Environment.MEDIA_MOUNTED)
16630                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16631        }
16632
16633        if (!mounted) {
16634            return;
16635        }
16636
16637        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16638        int[] users;
16639        if (userId == UserHandle.USER_ALL) {
16640            users = sUserManager.getUserIds();
16641        } else {
16642            users = new int[] { userId };
16643        }
16644        final ClearStorageConnection conn = new ClearStorageConnection();
16645        if (mContext.bindServiceAsUser(
16646                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16647            try {
16648                for (int curUser : users) {
16649                    long timeout = SystemClock.uptimeMillis() + 5000;
16650                    synchronized (conn) {
16651                        long now;
16652                        while (conn.mContainerService == null &&
16653                                (now = SystemClock.uptimeMillis()) < timeout) {
16654                            try {
16655                                conn.wait(timeout - now);
16656                            } catch (InterruptedException e) {
16657                            }
16658                        }
16659                    }
16660                    if (conn.mContainerService == null) {
16661                        return;
16662                    }
16663
16664                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16665                    clearDirectory(conn.mContainerService,
16666                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16667                    if (allData) {
16668                        clearDirectory(conn.mContainerService,
16669                                userEnv.buildExternalStorageAppDataDirs(packageName));
16670                        clearDirectory(conn.mContainerService,
16671                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16672                    }
16673                }
16674            } finally {
16675                mContext.unbindService(conn);
16676            }
16677        }
16678    }
16679
16680    @Override
16681    public void clearApplicationProfileData(String packageName) {
16682        enforceSystemOrRoot("Only the system can clear all profile data");
16683
16684        final PackageParser.Package pkg;
16685        synchronized (mPackages) {
16686            pkg = mPackages.get(packageName);
16687        }
16688
16689        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16690            synchronized (mInstallLock) {
16691                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16692                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16693                        true /* removeBaseMarker */);
16694            }
16695        }
16696    }
16697
16698    @Override
16699    public void clearApplicationUserData(final String packageName,
16700            final IPackageDataObserver observer, final int userId) {
16701        mContext.enforceCallingOrSelfPermission(
16702                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16703
16704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16705                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16706
16707        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16708            throw new SecurityException("Cannot clear data for a protected package: "
16709                    + packageName);
16710        }
16711        // Queue up an async operation since the package deletion may take a little while.
16712        mHandler.post(new Runnable() {
16713            public void run() {
16714                mHandler.removeCallbacks(this);
16715                final boolean succeeded;
16716                try (PackageFreezer freezer = freezePackage(packageName,
16717                        "clearApplicationUserData")) {
16718                    synchronized (mInstallLock) {
16719                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16720                    }
16721                    clearExternalStorageDataSync(packageName, userId, true);
16722                }
16723                if (succeeded) {
16724                    // invoke DeviceStorageMonitor's update method to clear any notifications
16725                    DeviceStorageMonitorInternal dsm = LocalServices
16726                            .getService(DeviceStorageMonitorInternal.class);
16727                    if (dsm != null) {
16728                        dsm.checkMemory();
16729                    }
16730                }
16731                if(observer != null) {
16732                    try {
16733                        observer.onRemoveCompleted(packageName, succeeded);
16734                    } catch (RemoteException e) {
16735                        Log.i(TAG, "Observer no longer exists.");
16736                    }
16737                } //end if observer
16738            } //end run
16739        });
16740    }
16741
16742    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16743        if (packageName == null) {
16744            Slog.w(TAG, "Attempt to delete null packageName.");
16745            return false;
16746        }
16747
16748        // Try finding details about the requested package
16749        PackageParser.Package pkg;
16750        synchronized (mPackages) {
16751            pkg = mPackages.get(packageName);
16752            if (pkg == null) {
16753                final PackageSetting ps = mSettings.mPackages.get(packageName);
16754                if (ps != null) {
16755                    pkg = ps.pkg;
16756                }
16757            }
16758
16759            if (pkg == null) {
16760                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16761                return false;
16762            }
16763
16764            PackageSetting ps = (PackageSetting) pkg.mExtras;
16765            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16766        }
16767
16768        clearAppDataLIF(pkg, userId,
16769                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16770
16771        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16772        removeKeystoreDataIfNeeded(userId, appId);
16773
16774        UserManagerInternal umInternal = getUserManagerInternal();
16775        final int flags;
16776        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16777            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16778        } else if (umInternal.isUserRunning(userId)) {
16779            flags = StorageManager.FLAG_STORAGE_DE;
16780        } else {
16781            flags = 0;
16782        }
16783        prepareAppDataContentsLIF(pkg, userId, flags);
16784
16785        return true;
16786    }
16787
16788    /**
16789     * Reverts user permission state changes (permissions and flags) in
16790     * all packages for a given user.
16791     *
16792     * @param userId The device user for which to do a reset.
16793     */
16794    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16795        final int packageCount = mPackages.size();
16796        for (int i = 0; i < packageCount; i++) {
16797            PackageParser.Package pkg = mPackages.valueAt(i);
16798            PackageSetting ps = (PackageSetting) pkg.mExtras;
16799            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16800        }
16801    }
16802
16803    private void resetNetworkPolicies(int userId) {
16804        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16805    }
16806
16807    /**
16808     * Reverts user permission state changes (permissions and flags).
16809     *
16810     * @param ps The package for which to reset.
16811     * @param userId The device user for which to do a reset.
16812     */
16813    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16814            final PackageSetting ps, final int userId) {
16815        if (ps.pkg == null) {
16816            return;
16817        }
16818
16819        // These are flags that can change base on user actions.
16820        final int userSettableMask = FLAG_PERMISSION_USER_SET
16821                | FLAG_PERMISSION_USER_FIXED
16822                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16823                | FLAG_PERMISSION_REVIEW_REQUIRED;
16824
16825        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16826                | FLAG_PERMISSION_POLICY_FIXED;
16827
16828        boolean writeInstallPermissions = false;
16829        boolean writeRuntimePermissions = false;
16830
16831        final int permissionCount = ps.pkg.requestedPermissions.size();
16832        for (int i = 0; i < permissionCount; i++) {
16833            String permission = ps.pkg.requestedPermissions.get(i);
16834
16835            BasePermission bp = mSettings.mPermissions.get(permission);
16836            if (bp == null) {
16837                continue;
16838            }
16839
16840            // If shared user we just reset the state to which only this app contributed.
16841            if (ps.sharedUser != null) {
16842                boolean used = false;
16843                final int packageCount = ps.sharedUser.packages.size();
16844                for (int j = 0; j < packageCount; j++) {
16845                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16846                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16847                            && pkg.pkg.requestedPermissions.contains(permission)) {
16848                        used = true;
16849                        break;
16850                    }
16851                }
16852                if (used) {
16853                    continue;
16854                }
16855            }
16856
16857            PermissionsState permissionsState = ps.getPermissionsState();
16858
16859            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16860
16861            // Always clear the user settable flags.
16862            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16863                    bp.name) != null;
16864            // If permission review is enabled and this is a legacy app, mark the
16865            // permission as requiring a review as this is the initial state.
16866            int flags = 0;
16867            if (mPermissionReviewRequired
16868                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16869                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16870            }
16871            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16872                if (hasInstallState) {
16873                    writeInstallPermissions = true;
16874                } else {
16875                    writeRuntimePermissions = true;
16876                }
16877            }
16878
16879            // Below is only runtime permission handling.
16880            if (!bp.isRuntime()) {
16881                continue;
16882            }
16883
16884            // Never clobber system or policy.
16885            if ((oldFlags & policyOrSystemFlags) != 0) {
16886                continue;
16887            }
16888
16889            // If this permission was granted by default, make sure it is.
16890            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16891                if (permissionsState.grantRuntimePermission(bp, userId)
16892                        != PERMISSION_OPERATION_FAILURE) {
16893                    writeRuntimePermissions = true;
16894                }
16895            // If permission review is enabled the permissions for a legacy apps
16896            // are represented as constantly granted runtime ones, so don't revoke.
16897            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16898                // Otherwise, reset the permission.
16899                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16900                switch (revokeResult) {
16901                    case PERMISSION_OPERATION_SUCCESS:
16902                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16903                        writeRuntimePermissions = true;
16904                        final int appId = ps.appId;
16905                        mHandler.post(new Runnable() {
16906                            @Override
16907                            public void run() {
16908                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16909                            }
16910                        });
16911                    } break;
16912                }
16913            }
16914        }
16915
16916        // Synchronously write as we are taking permissions away.
16917        if (writeRuntimePermissions) {
16918            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16919        }
16920
16921        // Synchronously write as we are taking permissions away.
16922        if (writeInstallPermissions) {
16923            mSettings.writeLPr();
16924        }
16925    }
16926
16927    /**
16928     * Remove entries from the keystore daemon. Will only remove it if the
16929     * {@code appId} is valid.
16930     */
16931    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16932        if (appId < 0) {
16933            return;
16934        }
16935
16936        final KeyStore keyStore = KeyStore.getInstance();
16937        if (keyStore != null) {
16938            if (userId == UserHandle.USER_ALL) {
16939                for (final int individual : sUserManager.getUserIds()) {
16940                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16941                }
16942            } else {
16943                keyStore.clearUid(UserHandle.getUid(userId, appId));
16944            }
16945        } else {
16946            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16947        }
16948    }
16949
16950    @Override
16951    public void deleteApplicationCacheFiles(final String packageName,
16952            final IPackageDataObserver observer) {
16953        final int userId = UserHandle.getCallingUserId();
16954        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16955    }
16956
16957    @Override
16958    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16959            final IPackageDataObserver observer) {
16960        mContext.enforceCallingOrSelfPermission(
16961                android.Manifest.permission.DELETE_CACHE_FILES, null);
16962        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16963                /* requireFullPermission= */ true, /* checkShell= */ false,
16964                "delete application cache files");
16965
16966        final PackageParser.Package pkg;
16967        synchronized (mPackages) {
16968            pkg = mPackages.get(packageName);
16969        }
16970
16971        // Queue up an async operation since the package deletion may take a little while.
16972        mHandler.post(new Runnable() {
16973            public void run() {
16974                synchronized (mInstallLock) {
16975                    final int flags = StorageManager.FLAG_STORAGE_DE
16976                            | StorageManager.FLAG_STORAGE_CE;
16977                    // We're only clearing cache files, so we don't care if the
16978                    // app is unfrozen and still able to run
16979                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16980                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16981                }
16982                clearExternalStorageDataSync(packageName, userId, false);
16983                if (observer != null) {
16984                    try {
16985                        observer.onRemoveCompleted(packageName, true);
16986                    } catch (RemoteException e) {
16987                        Log.i(TAG, "Observer no longer exists.");
16988                    }
16989                }
16990            }
16991        });
16992    }
16993
16994    @Override
16995    public void getPackageSizeInfo(final String packageName, int userHandle,
16996            final IPackageStatsObserver observer) {
16997        mContext.enforceCallingOrSelfPermission(
16998                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16999        if (packageName == null) {
17000            throw new IllegalArgumentException("Attempt to get size of null packageName");
17001        }
17002
17003        PackageStats stats = new PackageStats(packageName, userHandle);
17004
17005        /*
17006         * Queue up an async operation since the package measurement may take a
17007         * little while.
17008         */
17009        Message msg = mHandler.obtainMessage(INIT_COPY);
17010        msg.obj = new MeasureParams(stats, observer);
17011        mHandler.sendMessage(msg);
17012    }
17013
17014    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17015        final PackageSetting ps;
17016        synchronized (mPackages) {
17017            ps = mSettings.mPackages.get(packageName);
17018            if (ps == null) {
17019                Slog.w(TAG, "Failed to find settings for " + packageName);
17020                return false;
17021            }
17022        }
17023        try {
17024            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17025                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17026                    ps.getCeDataInode(userId), ps.codePathString, stats);
17027        } catch (InstallerException e) {
17028            Slog.w(TAG, String.valueOf(e));
17029            return false;
17030        }
17031
17032        // For now, ignore code size of packages on system partition
17033        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17034            stats.codeSize = 0;
17035        }
17036
17037        return true;
17038    }
17039
17040    private int getUidTargetSdkVersionLockedLPr(int uid) {
17041        Object obj = mSettings.getUserIdLPr(uid);
17042        if (obj instanceof SharedUserSetting) {
17043            final SharedUserSetting sus = (SharedUserSetting) obj;
17044            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17045            final Iterator<PackageSetting> it = sus.packages.iterator();
17046            while (it.hasNext()) {
17047                final PackageSetting ps = it.next();
17048                if (ps.pkg != null) {
17049                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17050                    if (v < vers) vers = v;
17051                }
17052            }
17053            return vers;
17054        } else if (obj instanceof PackageSetting) {
17055            final PackageSetting ps = (PackageSetting) obj;
17056            if (ps.pkg != null) {
17057                return ps.pkg.applicationInfo.targetSdkVersion;
17058            }
17059        }
17060        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17061    }
17062
17063    @Override
17064    public void addPreferredActivity(IntentFilter filter, int match,
17065            ComponentName[] set, ComponentName activity, int userId) {
17066        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17067                "Adding preferred");
17068    }
17069
17070    private void addPreferredActivityInternal(IntentFilter filter, int match,
17071            ComponentName[] set, ComponentName activity, boolean always, int userId,
17072            String opname) {
17073        // writer
17074        int callingUid = Binder.getCallingUid();
17075        enforceCrossUserPermission(callingUid, userId,
17076                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17077        if (filter.countActions() == 0) {
17078            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17079            return;
17080        }
17081        synchronized (mPackages) {
17082            if (mContext.checkCallingOrSelfPermission(
17083                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17084                    != PackageManager.PERMISSION_GRANTED) {
17085                if (getUidTargetSdkVersionLockedLPr(callingUid)
17086                        < Build.VERSION_CODES.FROYO) {
17087                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17088                            + callingUid);
17089                    return;
17090                }
17091                mContext.enforceCallingOrSelfPermission(
17092                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17093            }
17094
17095            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17096            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17097                    + userId + ":");
17098            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17099            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17100            scheduleWritePackageRestrictionsLocked(userId);
17101            postPreferredActivityChangedBroadcast(userId);
17102        }
17103    }
17104
17105    private void postPreferredActivityChangedBroadcast(int userId) {
17106        mHandler.post(() -> {
17107            final IActivityManager am = ActivityManagerNative.getDefault();
17108            if (am == null) {
17109                return;
17110            }
17111
17112            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17113            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17114            try {
17115                am.broadcastIntent(null, intent, null, null,
17116                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17117                        null, false, false, userId);
17118            } catch (RemoteException e) {
17119            }
17120        });
17121    }
17122
17123    @Override
17124    public void replacePreferredActivity(IntentFilter filter, int match,
17125            ComponentName[] set, ComponentName activity, int userId) {
17126        if (filter.countActions() != 1) {
17127            throw new IllegalArgumentException(
17128                    "replacePreferredActivity expects filter to have only 1 action.");
17129        }
17130        if (filter.countDataAuthorities() != 0
17131                || filter.countDataPaths() != 0
17132                || filter.countDataSchemes() > 1
17133                || filter.countDataTypes() != 0) {
17134            throw new IllegalArgumentException(
17135                    "replacePreferredActivity expects filter to have no data authorities, " +
17136                    "paths, or types; and at most one scheme.");
17137        }
17138
17139        final int callingUid = Binder.getCallingUid();
17140        enforceCrossUserPermission(callingUid, userId,
17141                true /* requireFullPermission */, false /* checkShell */,
17142                "replace preferred activity");
17143        synchronized (mPackages) {
17144            if (mContext.checkCallingOrSelfPermission(
17145                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17146                    != PackageManager.PERMISSION_GRANTED) {
17147                if (getUidTargetSdkVersionLockedLPr(callingUid)
17148                        < Build.VERSION_CODES.FROYO) {
17149                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17150                            + Binder.getCallingUid());
17151                    return;
17152                }
17153                mContext.enforceCallingOrSelfPermission(
17154                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17155            }
17156
17157            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17158            if (pir != null) {
17159                // Get all of the existing entries that exactly match this filter.
17160                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17161                if (existing != null && existing.size() == 1) {
17162                    PreferredActivity cur = existing.get(0);
17163                    if (DEBUG_PREFERRED) {
17164                        Slog.i(TAG, "Checking replace of preferred:");
17165                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17166                        if (!cur.mPref.mAlways) {
17167                            Slog.i(TAG, "  -- CUR; not mAlways!");
17168                        } else {
17169                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17170                            Slog.i(TAG, "  -- CUR: mSet="
17171                                    + Arrays.toString(cur.mPref.mSetComponents));
17172                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17173                            Slog.i(TAG, "  -- NEW: mMatch="
17174                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17175                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17176                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17177                        }
17178                    }
17179                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17180                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17181                            && cur.mPref.sameSet(set)) {
17182                        // Setting the preferred activity to what it happens to be already
17183                        if (DEBUG_PREFERRED) {
17184                            Slog.i(TAG, "Replacing with same preferred activity "
17185                                    + cur.mPref.mShortComponent + " for user "
17186                                    + userId + ":");
17187                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17188                        }
17189                        return;
17190                    }
17191                }
17192
17193                if (existing != null) {
17194                    if (DEBUG_PREFERRED) {
17195                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17196                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17197                    }
17198                    for (int i = 0; i < existing.size(); i++) {
17199                        PreferredActivity pa = existing.get(i);
17200                        if (DEBUG_PREFERRED) {
17201                            Slog.i(TAG, "Removing existing preferred activity "
17202                                    + pa.mPref.mComponent + ":");
17203                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17204                        }
17205                        pir.removeFilter(pa);
17206                    }
17207                }
17208            }
17209            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17210                    "Replacing preferred");
17211        }
17212    }
17213
17214    @Override
17215    public void clearPackagePreferredActivities(String packageName) {
17216        final int uid = Binder.getCallingUid();
17217        // writer
17218        synchronized (mPackages) {
17219            PackageParser.Package pkg = mPackages.get(packageName);
17220            if (pkg == null || pkg.applicationInfo.uid != uid) {
17221                if (mContext.checkCallingOrSelfPermission(
17222                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17223                        != PackageManager.PERMISSION_GRANTED) {
17224                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17225                            < Build.VERSION_CODES.FROYO) {
17226                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17227                                + Binder.getCallingUid());
17228                        return;
17229                    }
17230                    mContext.enforceCallingOrSelfPermission(
17231                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17232                }
17233            }
17234
17235            int user = UserHandle.getCallingUserId();
17236            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17237                scheduleWritePackageRestrictionsLocked(user);
17238            }
17239        }
17240    }
17241
17242    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17243    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17244        ArrayList<PreferredActivity> removed = null;
17245        boolean changed = false;
17246        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17247            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17248            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17249            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17250                continue;
17251            }
17252            Iterator<PreferredActivity> it = pir.filterIterator();
17253            while (it.hasNext()) {
17254                PreferredActivity pa = it.next();
17255                // Mark entry for removal only if it matches the package name
17256                // and the entry is of type "always".
17257                if (packageName == null ||
17258                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17259                                && pa.mPref.mAlways)) {
17260                    if (removed == null) {
17261                        removed = new ArrayList<PreferredActivity>();
17262                    }
17263                    removed.add(pa);
17264                }
17265            }
17266            if (removed != null) {
17267                for (int j=0; j<removed.size(); j++) {
17268                    PreferredActivity pa = removed.get(j);
17269                    pir.removeFilter(pa);
17270                }
17271                changed = true;
17272            }
17273        }
17274        if (changed) {
17275            postPreferredActivityChangedBroadcast(userId);
17276        }
17277        return changed;
17278    }
17279
17280    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17281    private void clearIntentFilterVerificationsLPw(int userId) {
17282        final int packageCount = mPackages.size();
17283        for (int i = 0; i < packageCount; i++) {
17284            PackageParser.Package pkg = mPackages.valueAt(i);
17285            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17286        }
17287    }
17288
17289    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17290    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17291        if (userId == UserHandle.USER_ALL) {
17292            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17293                    sUserManager.getUserIds())) {
17294                for (int oneUserId : sUserManager.getUserIds()) {
17295                    scheduleWritePackageRestrictionsLocked(oneUserId);
17296                }
17297            }
17298        } else {
17299            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17300                scheduleWritePackageRestrictionsLocked(userId);
17301            }
17302        }
17303    }
17304
17305    void clearDefaultBrowserIfNeeded(String packageName) {
17306        for (int oneUserId : sUserManager.getUserIds()) {
17307            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17308            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17309            if (packageName.equals(defaultBrowserPackageName)) {
17310                setDefaultBrowserPackageName(null, oneUserId);
17311            }
17312        }
17313    }
17314
17315    @Override
17316    public void resetApplicationPreferences(int userId) {
17317        mContext.enforceCallingOrSelfPermission(
17318                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17319        final long identity = Binder.clearCallingIdentity();
17320        // writer
17321        try {
17322            synchronized (mPackages) {
17323                clearPackagePreferredActivitiesLPw(null, userId);
17324                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17325                // TODO: We have to reset the default SMS and Phone. This requires
17326                // significant refactoring to keep all default apps in the package
17327                // manager (cleaner but more work) or have the services provide
17328                // callbacks to the package manager to request a default app reset.
17329                applyFactoryDefaultBrowserLPw(userId);
17330                clearIntentFilterVerificationsLPw(userId);
17331                primeDomainVerificationsLPw(userId);
17332                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17333                scheduleWritePackageRestrictionsLocked(userId);
17334            }
17335            resetNetworkPolicies(userId);
17336        } finally {
17337            Binder.restoreCallingIdentity(identity);
17338        }
17339    }
17340
17341    @Override
17342    public int getPreferredActivities(List<IntentFilter> outFilters,
17343            List<ComponentName> outActivities, String packageName) {
17344
17345        int num = 0;
17346        final int userId = UserHandle.getCallingUserId();
17347        // reader
17348        synchronized (mPackages) {
17349            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17350            if (pir != null) {
17351                final Iterator<PreferredActivity> it = pir.filterIterator();
17352                while (it.hasNext()) {
17353                    final PreferredActivity pa = it.next();
17354                    if (packageName == null
17355                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17356                                    && pa.mPref.mAlways)) {
17357                        if (outFilters != null) {
17358                            outFilters.add(new IntentFilter(pa));
17359                        }
17360                        if (outActivities != null) {
17361                            outActivities.add(pa.mPref.mComponent);
17362                        }
17363                    }
17364                }
17365            }
17366        }
17367
17368        return num;
17369    }
17370
17371    @Override
17372    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17373            int userId) {
17374        int callingUid = Binder.getCallingUid();
17375        if (callingUid != Process.SYSTEM_UID) {
17376            throw new SecurityException(
17377                    "addPersistentPreferredActivity can only be run by the system");
17378        }
17379        if (filter.countActions() == 0) {
17380            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17381            return;
17382        }
17383        synchronized (mPackages) {
17384            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17385                    ":");
17386            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17387            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17388                    new PersistentPreferredActivity(filter, activity));
17389            scheduleWritePackageRestrictionsLocked(userId);
17390            postPreferredActivityChangedBroadcast(userId);
17391        }
17392    }
17393
17394    @Override
17395    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17396        int callingUid = Binder.getCallingUid();
17397        if (callingUid != Process.SYSTEM_UID) {
17398            throw new SecurityException(
17399                    "clearPackagePersistentPreferredActivities can only be run by the system");
17400        }
17401        ArrayList<PersistentPreferredActivity> removed = null;
17402        boolean changed = false;
17403        synchronized (mPackages) {
17404            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17405                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17406                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17407                        .valueAt(i);
17408                if (userId != thisUserId) {
17409                    continue;
17410                }
17411                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17412                while (it.hasNext()) {
17413                    PersistentPreferredActivity ppa = it.next();
17414                    // Mark entry for removal only if it matches the package name.
17415                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17416                        if (removed == null) {
17417                            removed = new ArrayList<PersistentPreferredActivity>();
17418                        }
17419                        removed.add(ppa);
17420                    }
17421                }
17422                if (removed != null) {
17423                    for (int j=0; j<removed.size(); j++) {
17424                        PersistentPreferredActivity ppa = removed.get(j);
17425                        ppir.removeFilter(ppa);
17426                    }
17427                    changed = true;
17428                }
17429            }
17430
17431            if (changed) {
17432                scheduleWritePackageRestrictionsLocked(userId);
17433                postPreferredActivityChangedBroadcast(userId);
17434            }
17435        }
17436    }
17437
17438    /**
17439     * Common machinery for picking apart a restored XML blob and passing
17440     * it to a caller-supplied functor to be applied to the running system.
17441     */
17442    private void restoreFromXml(XmlPullParser parser, int userId,
17443            String expectedStartTag, BlobXmlRestorer functor)
17444            throws IOException, XmlPullParserException {
17445        int type;
17446        while ((type = parser.next()) != XmlPullParser.START_TAG
17447                && type != XmlPullParser.END_DOCUMENT) {
17448        }
17449        if (type != XmlPullParser.START_TAG) {
17450            // oops didn't find a start tag?!
17451            if (DEBUG_BACKUP) {
17452                Slog.e(TAG, "Didn't find start tag during restore");
17453            }
17454            return;
17455        }
17456Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17457        // this is supposed to be TAG_PREFERRED_BACKUP
17458        if (!expectedStartTag.equals(parser.getName())) {
17459            if (DEBUG_BACKUP) {
17460                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17461            }
17462            return;
17463        }
17464
17465        // skip interfering stuff, then we're aligned with the backing implementation
17466        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17467Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17468        functor.apply(parser, userId);
17469    }
17470
17471    private interface BlobXmlRestorer {
17472        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17473    }
17474
17475    /**
17476     * Non-Binder method, support for the backup/restore mechanism: write the
17477     * full set of preferred activities in its canonical XML format.  Returns the
17478     * XML output as a byte array, or null if there is none.
17479     */
17480    @Override
17481    public byte[] getPreferredActivityBackup(int userId) {
17482        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17483            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17484        }
17485
17486        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17487        try {
17488            final XmlSerializer serializer = new FastXmlSerializer();
17489            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17490            serializer.startDocument(null, true);
17491            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17492
17493            synchronized (mPackages) {
17494                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17495            }
17496
17497            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17498            serializer.endDocument();
17499            serializer.flush();
17500        } catch (Exception e) {
17501            if (DEBUG_BACKUP) {
17502                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17503            }
17504            return null;
17505        }
17506
17507        return dataStream.toByteArray();
17508    }
17509
17510    @Override
17511    public void restorePreferredActivities(byte[] backup, int userId) {
17512        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17513            throw new SecurityException("Only the system may call restorePreferredActivities()");
17514        }
17515
17516        try {
17517            final XmlPullParser parser = Xml.newPullParser();
17518            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17519            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17520                    new BlobXmlRestorer() {
17521                        @Override
17522                        public void apply(XmlPullParser parser, int userId)
17523                                throws XmlPullParserException, IOException {
17524                            synchronized (mPackages) {
17525                                mSettings.readPreferredActivitiesLPw(parser, userId);
17526                            }
17527                        }
17528                    } );
17529        } catch (Exception e) {
17530            if (DEBUG_BACKUP) {
17531                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17532            }
17533        }
17534    }
17535
17536    /**
17537     * Non-Binder method, support for the backup/restore mechanism: write the
17538     * default browser (etc) settings in its canonical XML format.  Returns the default
17539     * browser XML representation as a byte array, or null if there is none.
17540     */
17541    @Override
17542    public byte[] getDefaultAppsBackup(int userId) {
17543        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17544            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17545        }
17546
17547        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17548        try {
17549            final XmlSerializer serializer = new FastXmlSerializer();
17550            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17551            serializer.startDocument(null, true);
17552            serializer.startTag(null, TAG_DEFAULT_APPS);
17553
17554            synchronized (mPackages) {
17555                mSettings.writeDefaultAppsLPr(serializer, userId);
17556            }
17557
17558            serializer.endTag(null, TAG_DEFAULT_APPS);
17559            serializer.endDocument();
17560            serializer.flush();
17561        } catch (Exception e) {
17562            if (DEBUG_BACKUP) {
17563                Slog.e(TAG, "Unable to write default apps for backup", e);
17564            }
17565            return null;
17566        }
17567
17568        return dataStream.toByteArray();
17569    }
17570
17571    @Override
17572    public void restoreDefaultApps(byte[] backup, int userId) {
17573        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17574            throw new SecurityException("Only the system may call restoreDefaultApps()");
17575        }
17576
17577        try {
17578            final XmlPullParser parser = Xml.newPullParser();
17579            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17580            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17581                    new BlobXmlRestorer() {
17582                        @Override
17583                        public void apply(XmlPullParser parser, int userId)
17584                                throws XmlPullParserException, IOException {
17585                            synchronized (mPackages) {
17586                                mSettings.readDefaultAppsLPw(parser, userId);
17587                            }
17588                        }
17589                    } );
17590        } catch (Exception e) {
17591            if (DEBUG_BACKUP) {
17592                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17593            }
17594        }
17595    }
17596
17597    @Override
17598    public byte[] getIntentFilterVerificationBackup(int userId) {
17599        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17600            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17601        }
17602
17603        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17604        try {
17605            final XmlSerializer serializer = new FastXmlSerializer();
17606            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17607            serializer.startDocument(null, true);
17608            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17609
17610            synchronized (mPackages) {
17611                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17612            }
17613
17614            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17615            serializer.endDocument();
17616            serializer.flush();
17617        } catch (Exception e) {
17618            if (DEBUG_BACKUP) {
17619                Slog.e(TAG, "Unable to write default apps for backup", e);
17620            }
17621            return null;
17622        }
17623
17624        return dataStream.toByteArray();
17625    }
17626
17627    @Override
17628    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17629        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17630            throw new SecurityException("Only the system may call restorePreferredActivities()");
17631        }
17632
17633        try {
17634            final XmlPullParser parser = Xml.newPullParser();
17635            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17636            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17637                    new BlobXmlRestorer() {
17638                        @Override
17639                        public void apply(XmlPullParser parser, int userId)
17640                                throws XmlPullParserException, IOException {
17641                            synchronized (mPackages) {
17642                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17643                                mSettings.writeLPr();
17644                            }
17645                        }
17646                    } );
17647        } catch (Exception e) {
17648            if (DEBUG_BACKUP) {
17649                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17650            }
17651        }
17652    }
17653
17654    @Override
17655    public byte[] getPermissionGrantBackup(int userId) {
17656        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17657            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17658        }
17659
17660        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17661        try {
17662            final XmlSerializer serializer = new FastXmlSerializer();
17663            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17664            serializer.startDocument(null, true);
17665            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17666
17667            synchronized (mPackages) {
17668                serializeRuntimePermissionGrantsLPr(serializer, userId);
17669            }
17670
17671            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17672            serializer.endDocument();
17673            serializer.flush();
17674        } catch (Exception e) {
17675            if (DEBUG_BACKUP) {
17676                Slog.e(TAG, "Unable to write default apps for backup", e);
17677            }
17678            return null;
17679        }
17680
17681        return dataStream.toByteArray();
17682    }
17683
17684    @Override
17685    public void restorePermissionGrants(byte[] backup, int userId) {
17686        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17687            throw new SecurityException("Only the system may call restorePermissionGrants()");
17688        }
17689
17690        try {
17691            final XmlPullParser parser = Xml.newPullParser();
17692            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17693            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17694                    new BlobXmlRestorer() {
17695                        @Override
17696                        public void apply(XmlPullParser parser, int userId)
17697                                throws XmlPullParserException, IOException {
17698                            synchronized (mPackages) {
17699                                processRestoredPermissionGrantsLPr(parser, userId);
17700                            }
17701                        }
17702                    } );
17703        } catch (Exception e) {
17704            if (DEBUG_BACKUP) {
17705                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17706            }
17707        }
17708    }
17709
17710    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17711            throws IOException {
17712        serializer.startTag(null, TAG_ALL_GRANTS);
17713
17714        final int N = mSettings.mPackages.size();
17715        for (int i = 0; i < N; i++) {
17716            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17717            boolean pkgGrantsKnown = false;
17718
17719            PermissionsState packagePerms = ps.getPermissionsState();
17720
17721            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17722                final int grantFlags = state.getFlags();
17723                // only look at grants that are not system/policy fixed
17724                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17725                    final boolean isGranted = state.isGranted();
17726                    // And only back up the user-twiddled state bits
17727                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17728                        final String packageName = mSettings.mPackages.keyAt(i);
17729                        if (!pkgGrantsKnown) {
17730                            serializer.startTag(null, TAG_GRANT);
17731                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17732                            pkgGrantsKnown = true;
17733                        }
17734
17735                        final boolean userSet =
17736                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17737                        final boolean userFixed =
17738                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17739                        final boolean revoke =
17740                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17741
17742                        serializer.startTag(null, TAG_PERMISSION);
17743                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17744                        if (isGranted) {
17745                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17746                        }
17747                        if (userSet) {
17748                            serializer.attribute(null, ATTR_USER_SET, "true");
17749                        }
17750                        if (userFixed) {
17751                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17752                        }
17753                        if (revoke) {
17754                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17755                        }
17756                        serializer.endTag(null, TAG_PERMISSION);
17757                    }
17758                }
17759            }
17760
17761            if (pkgGrantsKnown) {
17762                serializer.endTag(null, TAG_GRANT);
17763            }
17764        }
17765
17766        serializer.endTag(null, TAG_ALL_GRANTS);
17767    }
17768
17769    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17770            throws XmlPullParserException, IOException {
17771        String pkgName = null;
17772        int outerDepth = parser.getDepth();
17773        int type;
17774        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17775                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17776            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17777                continue;
17778            }
17779
17780            final String tagName = parser.getName();
17781            if (tagName.equals(TAG_GRANT)) {
17782                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17783                if (DEBUG_BACKUP) {
17784                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17785                }
17786            } else if (tagName.equals(TAG_PERMISSION)) {
17787
17788                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17789                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17790
17791                int newFlagSet = 0;
17792                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17793                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17794                }
17795                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17796                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17797                }
17798                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17799                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17800                }
17801                if (DEBUG_BACKUP) {
17802                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17803                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17804                }
17805                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17806                if (ps != null) {
17807                    // Already installed so we apply the grant immediately
17808                    if (DEBUG_BACKUP) {
17809                        Slog.v(TAG, "        + already installed; applying");
17810                    }
17811                    PermissionsState perms = ps.getPermissionsState();
17812                    BasePermission bp = mSettings.mPermissions.get(permName);
17813                    if (bp != null) {
17814                        if (isGranted) {
17815                            perms.grantRuntimePermission(bp, userId);
17816                        }
17817                        if (newFlagSet != 0) {
17818                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17819                        }
17820                    }
17821                } else {
17822                    // Need to wait for post-restore install to apply the grant
17823                    if (DEBUG_BACKUP) {
17824                        Slog.v(TAG, "        - not yet installed; saving for later");
17825                    }
17826                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17827                            isGranted, newFlagSet, userId);
17828                }
17829            } else {
17830                PackageManagerService.reportSettingsProblem(Log.WARN,
17831                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17832                XmlUtils.skipCurrentTag(parser);
17833            }
17834        }
17835
17836        scheduleWriteSettingsLocked();
17837        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17838    }
17839
17840    @Override
17841    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17842            int sourceUserId, int targetUserId, int flags) {
17843        mContext.enforceCallingOrSelfPermission(
17844                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17845        int callingUid = Binder.getCallingUid();
17846        enforceOwnerRights(ownerPackage, callingUid);
17847        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17848        if (intentFilter.countActions() == 0) {
17849            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17850            return;
17851        }
17852        synchronized (mPackages) {
17853            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17854                    ownerPackage, targetUserId, flags);
17855            CrossProfileIntentResolver resolver =
17856                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17857            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17858            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17859            if (existing != null) {
17860                int size = existing.size();
17861                for (int i = 0; i < size; i++) {
17862                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17863                        return;
17864                    }
17865                }
17866            }
17867            resolver.addFilter(newFilter);
17868            scheduleWritePackageRestrictionsLocked(sourceUserId);
17869        }
17870    }
17871
17872    @Override
17873    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17874        mContext.enforceCallingOrSelfPermission(
17875                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17876        int callingUid = Binder.getCallingUid();
17877        enforceOwnerRights(ownerPackage, callingUid);
17878        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17879        synchronized (mPackages) {
17880            CrossProfileIntentResolver resolver =
17881                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17882            ArraySet<CrossProfileIntentFilter> set =
17883                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17884            for (CrossProfileIntentFilter filter : set) {
17885                if (filter.getOwnerPackage().equals(ownerPackage)) {
17886                    resolver.removeFilter(filter);
17887                }
17888            }
17889            scheduleWritePackageRestrictionsLocked(sourceUserId);
17890        }
17891    }
17892
17893    // Enforcing that callingUid is owning pkg on userId
17894    private void enforceOwnerRights(String pkg, int callingUid) {
17895        // The system owns everything.
17896        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17897            return;
17898        }
17899        int callingUserId = UserHandle.getUserId(callingUid);
17900        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17901        if (pi == null) {
17902            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17903                    + callingUserId);
17904        }
17905        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17906            throw new SecurityException("Calling uid " + callingUid
17907                    + " does not own package " + pkg);
17908        }
17909    }
17910
17911    @Override
17912    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17913        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17914    }
17915
17916    private Intent getHomeIntent() {
17917        Intent intent = new Intent(Intent.ACTION_MAIN);
17918        intent.addCategory(Intent.CATEGORY_HOME);
17919        intent.addCategory(Intent.CATEGORY_DEFAULT);
17920        return intent;
17921    }
17922
17923    private IntentFilter getHomeFilter() {
17924        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17925        filter.addCategory(Intent.CATEGORY_HOME);
17926        filter.addCategory(Intent.CATEGORY_DEFAULT);
17927        return filter;
17928    }
17929
17930    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17931            int userId) {
17932        Intent intent  = getHomeIntent();
17933        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17934                PackageManager.GET_META_DATA, userId);
17935        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17936                true, false, false, userId);
17937
17938        allHomeCandidates.clear();
17939        if (list != null) {
17940            for (ResolveInfo ri : list) {
17941                allHomeCandidates.add(ri);
17942            }
17943        }
17944        return (preferred == null || preferred.activityInfo == null)
17945                ? null
17946                : new ComponentName(preferred.activityInfo.packageName,
17947                        preferred.activityInfo.name);
17948    }
17949
17950    @Override
17951    public void setHomeActivity(ComponentName comp, int userId) {
17952        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17953        getHomeActivitiesAsUser(homeActivities, userId);
17954
17955        boolean found = false;
17956
17957        final int size = homeActivities.size();
17958        final ComponentName[] set = new ComponentName[size];
17959        for (int i = 0; i < size; i++) {
17960            final ResolveInfo candidate = homeActivities.get(i);
17961            final ActivityInfo info = candidate.activityInfo;
17962            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17963            set[i] = activityName;
17964            if (!found && activityName.equals(comp)) {
17965                found = true;
17966            }
17967        }
17968        if (!found) {
17969            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17970                    + userId);
17971        }
17972        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17973                set, comp, userId);
17974    }
17975
17976    private @Nullable String getSetupWizardPackageName() {
17977        final Intent intent = new Intent(Intent.ACTION_MAIN);
17978        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17979
17980        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17981                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17982                        | MATCH_DISABLED_COMPONENTS,
17983                UserHandle.myUserId());
17984        if (matches.size() == 1) {
17985            return matches.get(0).getComponentInfo().packageName;
17986        } else {
17987            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17988                    + ": matches=" + matches);
17989            return null;
17990        }
17991    }
17992
17993    private @Nullable String getStorageManagerPackageName() {
17994        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17995
17996        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17997                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17998                        | MATCH_DISABLED_COMPONENTS,
17999                UserHandle.myUserId());
18000        if (matches.size() == 1) {
18001            return matches.get(0).getComponentInfo().packageName;
18002        } else {
18003            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18004                    + matches.size() + ": matches=" + matches);
18005            return null;
18006        }
18007    }
18008
18009    @Override
18010    public void setApplicationEnabledSetting(String appPackageName,
18011            int newState, int flags, int userId, String callingPackage) {
18012        if (!sUserManager.exists(userId)) return;
18013        if (callingPackage == null) {
18014            callingPackage = Integer.toString(Binder.getCallingUid());
18015        }
18016        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18017    }
18018
18019    @Override
18020    public void setComponentEnabledSetting(ComponentName componentName,
18021            int newState, int flags, int userId) {
18022        if (!sUserManager.exists(userId)) return;
18023        setEnabledSetting(componentName.getPackageName(),
18024                componentName.getClassName(), newState, flags, userId, null);
18025    }
18026
18027    private void setEnabledSetting(final String packageName, String className, int newState,
18028            final int flags, int userId, String callingPackage) {
18029        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18030              || newState == COMPONENT_ENABLED_STATE_ENABLED
18031              || newState == COMPONENT_ENABLED_STATE_DISABLED
18032              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18033              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18034            throw new IllegalArgumentException("Invalid new component state: "
18035                    + newState);
18036        }
18037        PackageSetting pkgSetting;
18038        final int uid = Binder.getCallingUid();
18039        final int permission;
18040        if (uid == Process.SYSTEM_UID) {
18041            permission = PackageManager.PERMISSION_GRANTED;
18042        } else {
18043            permission = mContext.checkCallingOrSelfPermission(
18044                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18045        }
18046        enforceCrossUserPermission(uid, userId,
18047                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18048        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18049        boolean sendNow = false;
18050        boolean isApp = (className == null);
18051        String componentName = isApp ? packageName : className;
18052        int packageUid = -1;
18053        ArrayList<String> components;
18054
18055        // writer
18056        synchronized (mPackages) {
18057            pkgSetting = mSettings.mPackages.get(packageName);
18058            if (pkgSetting == null) {
18059                if (className == null) {
18060                    throw new IllegalArgumentException("Unknown package: " + packageName);
18061                }
18062                throw new IllegalArgumentException(
18063                        "Unknown component: " + packageName + "/" + className);
18064            }
18065        }
18066
18067        // Limit who can change which apps
18068        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18069            // Don't allow apps that don't have permission to modify other apps
18070            if (!allowedByPermission) {
18071                throw new SecurityException(
18072                        "Permission Denial: attempt to change component state from pid="
18073                        + Binder.getCallingPid()
18074                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18075            }
18076            // Don't allow changing protected packages.
18077            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18078                throw new SecurityException("Cannot disable a protected package: " + packageName);
18079            }
18080        }
18081
18082        synchronized (mPackages) {
18083            if (uid == Process.SHELL_UID) {
18084                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18085                int oldState = pkgSetting.getEnabled(userId);
18086                if (className == null
18087                    &&
18088                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18089                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18090                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18091                    &&
18092                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18093                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18094                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18095                    // ok
18096                } else {
18097                    throw new SecurityException(
18098                            "Shell cannot change component state for " + packageName + "/"
18099                            + className + " to " + newState);
18100                }
18101            }
18102            if (className == null) {
18103                // We're dealing with an application/package level state change
18104                if (pkgSetting.getEnabled(userId) == newState) {
18105                    // Nothing to do
18106                    return;
18107                }
18108                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18109                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18110                    // Don't care about who enables an app.
18111                    callingPackage = null;
18112                }
18113                pkgSetting.setEnabled(newState, userId, callingPackage);
18114                // pkgSetting.pkg.mSetEnabled = newState;
18115            } else {
18116                // We're dealing with a component level state change
18117                // First, verify that this is a valid class name.
18118                PackageParser.Package pkg = pkgSetting.pkg;
18119                if (pkg == null || !pkg.hasComponentClassName(className)) {
18120                    if (pkg != null &&
18121                            pkg.applicationInfo.targetSdkVersion >=
18122                                    Build.VERSION_CODES.JELLY_BEAN) {
18123                        throw new IllegalArgumentException("Component class " + className
18124                                + " does not exist in " + packageName);
18125                    } else {
18126                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18127                                + className + " does not exist in " + packageName);
18128                    }
18129                }
18130                switch (newState) {
18131                case COMPONENT_ENABLED_STATE_ENABLED:
18132                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18133                        return;
18134                    }
18135                    break;
18136                case COMPONENT_ENABLED_STATE_DISABLED:
18137                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18138                        return;
18139                    }
18140                    break;
18141                case COMPONENT_ENABLED_STATE_DEFAULT:
18142                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18143                        return;
18144                    }
18145                    break;
18146                default:
18147                    Slog.e(TAG, "Invalid new component state: " + newState);
18148                    return;
18149                }
18150            }
18151            scheduleWritePackageRestrictionsLocked(userId);
18152            components = mPendingBroadcasts.get(userId, packageName);
18153            final boolean newPackage = components == null;
18154            if (newPackage) {
18155                components = new ArrayList<String>();
18156            }
18157            if (!components.contains(componentName)) {
18158                components.add(componentName);
18159            }
18160            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18161                sendNow = true;
18162                // Purge entry from pending broadcast list if another one exists already
18163                // since we are sending one right away.
18164                mPendingBroadcasts.remove(userId, packageName);
18165            } else {
18166                if (newPackage) {
18167                    mPendingBroadcasts.put(userId, packageName, components);
18168                }
18169                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18170                    // Schedule a message
18171                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18172                }
18173            }
18174        }
18175
18176        long callingId = Binder.clearCallingIdentity();
18177        try {
18178            if (sendNow) {
18179                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18180                sendPackageChangedBroadcast(packageName,
18181                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18182            }
18183        } finally {
18184            Binder.restoreCallingIdentity(callingId);
18185        }
18186    }
18187
18188    @Override
18189    public void flushPackageRestrictionsAsUser(int userId) {
18190        if (!sUserManager.exists(userId)) {
18191            return;
18192        }
18193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18194                false /* checkShell */, "flushPackageRestrictions");
18195        synchronized (mPackages) {
18196            mSettings.writePackageRestrictionsLPr(userId);
18197            mDirtyUsers.remove(userId);
18198            if (mDirtyUsers.isEmpty()) {
18199                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18200            }
18201        }
18202    }
18203
18204    private void sendPackageChangedBroadcast(String packageName,
18205            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18206        if (DEBUG_INSTALL)
18207            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18208                    + componentNames);
18209        Bundle extras = new Bundle(4);
18210        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18211        String nameList[] = new String[componentNames.size()];
18212        componentNames.toArray(nameList);
18213        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18214        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18215        extras.putInt(Intent.EXTRA_UID, packageUid);
18216        // If this is not reporting a change of the overall package, then only send it
18217        // to registered receivers.  We don't want to launch a swath of apps for every
18218        // little component state change.
18219        final int flags = !componentNames.contains(packageName)
18220                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18221        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18222                new int[] {UserHandle.getUserId(packageUid)});
18223    }
18224
18225    @Override
18226    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18227        if (!sUserManager.exists(userId)) return;
18228        final int uid = Binder.getCallingUid();
18229        final int permission = mContext.checkCallingOrSelfPermission(
18230                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18231        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18232        enforceCrossUserPermission(uid, userId,
18233                true /* requireFullPermission */, true /* checkShell */, "stop package");
18234        // writer
18235        synchronized (mPackages) {
18236            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18237                    allowedByPermission, uid, userId)) {
18238                scheduleWritePackageRestrictionsLocked(userId);
18239            }
18240        }
18241    }
18242
18243    @Override
18244    public String getInstallerPackageName(String packageName) {
18245        // reader
18246        synchronized (mPackages) {
18247            return mSettings.getInstallerPackageNameLPr(packageName);
18248        }
18249    }
18250
18251    public boolean isOrphaned(String packageName) {
18252        // reader
18253        synchronized (mPackages) {
18254            return mSettings.isOrphaned(packageName);
18255        }
18256    }
18257
18258    @Override
18259    public int getApplicationEnabledSetting(String packageName, int userId) {
18260        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18261        int uid = Binder.getCallingUid();
18262        enforceCrossUserPermission(uid, userId,
18263                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18264        // reader
18265        synchronized (mPackages) {
18266            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18267        }
18268    }
18269
18270    @Override
18271    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18272        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18273        int uid = Binder.getCallingUid();
18274        enforceCrossUserPermission(uid, userId,
18275                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18276        // reader
18277        synchronized (mPackages) {
18278            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18279        }
18280    }
18281
18282    @Override
18283    public void enterSafeMode() {
18284        enforceSystemOrRoot("Only the system can request entering safe mode");
18285
18286        if (!mSystemReady) {
18287            mSafeMode = true;
18288        }
18289    }
18290
18291    @Override
18292    public void systemReady() {
18293        mSystemReady = true;
18294
18295        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18296        // disabled after already being started.
18297        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18298                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18299
18300        // Read the compatibilty setting when the system is ready.
18301        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18302                mContext.getContentResolver(),
18303                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18304        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18305        if (DEBUG_SETTINGS) {
18306            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18307        }
18308
18309        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18310
18311        synchronized (mPackages) {
18312            // Verify that all of the preferred activity components actually
18313            // exist.  It is possible for applications to be updated and at
18314            // that point remove a previously declared activity component that
18315            // had been set as a preferred activity.  We try to clean this up
18316            // the next time we encounter that preferred activity, but it is
18317            // possible for the user flow to never be able to return to that
18318            // situation so here we do a sanity check to make sure we haven't
18319            // left any junk around.
18320            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18321            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18322                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18323                removed.clear();
18324                for (PreferredActivity pa : pir.filterSet()) {
18325                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18326                        removed.add(pa);
18327                    }
18328                }
18329                if (removed.size() > 0) {
18330                    for (int r=0; r<removed.size(); r++) {
18331                        PreferredActivity pa = removed.get(r);
18332                        Slog.w(TAG, "Removing dangling preferred activity: "
18333                                + pa.mPref.mComponent);
18334                        pir.removeFilter(pa);
18335                    }
18336                    mSettings.writePackageRestrictionsLPr(
18337                            mSettings.mPreferredActivities.keyAt(i));
18338                }
18339            }
18340
18341            for (int userId : UserManagerService.getInstance().getUserIds()) {
18342                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18343                    grantPermissionsUserIds = ArrayUtils.appendInt(
18344                            grantPermissionsUserIds, userId);
18345                }
18346            }
18347        }
18348        sUserManager.systemReady();
18349
18350        // If we upgraded grant all default permissions before kicking off.
18351        for (int userId : grantPermissionsUserIds) {
18352            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18353        }
18354
18355        // If we did not grant default permissions, we preload from this the
18356        // default permission exceptions lazily to ensure we don't hit the
18357        // disk on a new user creation.
18358        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18359            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18360        }
18361
18362        // Kick off any messages waiting for system ready
18363        if (mPostSystemReadyMessages != null) {
18364            for (Message msg : mPostSystemReadyMessages) {
18365                msg.sendToTarget();
18366            }
18367            mPostSystemReadyMessages = null;
18368        }
18369
18370        // Watch for external volumes that come and go over time
18371        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18372        storage.registerListener(mStorageListener);
18373
18374        mInstallerService.systemReady();
18375        mPackageDexOptimizer.systemReady();
18376
18377        MountServiceInternal mountServiceInternal = LocalServices.getService(
18378                MountServiceInternal.class);
18379        mountServiceInternal.addExternalStoragePolicy(
18380                new MountServiceInternal.ExternalStorageMountPolicy() {
18381            @Override
18382            public int getMountMode(int uid, String packageName) {
18383                if (Process.isIsolated(uid)) {
18384                    return Zygote.MOUNT_EXTERNAL_NONE;
18385                }
18386                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18387                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18388                }
18389                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18390                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18391                }
18392                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18393                    return Zygote.MOUNT_EXTERNAL_READ;
18394                }
18395                return Zygote.MOUNT_EXTERNAL_WRITE;
18396            }
18397
18398            @Override
18399            public boolean hasExternalStorage(int uid, String packageName) {
18400                return true;
18401            }
18402        });
18403
18404        // Now that we're mostly running, clean up stale users and apps
18405        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18406        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18407    }
18408
18409    @Override
18410    public boolean isSafeMode() {
18411        return mSafeMode;
18412    }
18413
18414    @Override
18415    public boolean hasSystemUidErrors() {
18416        return mHasSystemUidErrors;
18417    }
18418
18419    static String arrayToString(int[] array) {
18420        StringBuffer buf = new StringBuffer(128);
18421        buf.append('[');
18422        if (array != null) {
18423            for (int i=0; i<array.length; i++) {
18424                if (i > 0) buf.append(", ");
18425                buf.append(array[i]);
18426            }
18427        }
18428        buf.append(']');
18429        return buf.toString();
18430    }
18431
18432    static class DumpState {
18433        public static final int DUMP_LIBS = 1 << 0;
18434        public static final int DUMP_FEATURES = 1 << 1;
18435        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18436        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18437        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18438        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18439        public static final int DUMP_PERMISSIONS = 1 << 6;
18440        public static final int DUMP_PACKAGES = 1 << 7;
18441        public static final int DUMP_SHARED_USERS = 1 << 8;
18442        public static final int DUMP_MESSAGES = 1 << 9;
18443        public static final int DUMP_PROVIDERS = 1 << 10;
18444        public static final int DUMP_VERIFIERS = 1 << 11;
18445        public static final int DUMP_PREFERRED = 1 << 12;
18446        public static final int DUMP_PREFERRED_XML = 1 << 13;
18447        public static final int DUMP_KEYSETS = 1 << 14;
18448        public static final int DUMP_VERSION = 1 << 15;
18449        public static final int DUMP_INSTALLS = 1 << 16;
18450        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18451        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18452        public static final int DUMP_FROZEN = 1 << 19;
18453        public static final int DUMP_DEXOPT = 1 << 20;
18454        public static final int DUMP_COMPILER_STATS = 1 << 21;
18455
18456        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18457
18458        private int mTypes;
18459
18460        private int mOptions;
18461
18462        private boolean mTitlePrinted;
18463
18464        private SharedUserSetting mSharedUser;
18465
18466        public boolean isDumping(int type) {
18467            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18468                return true;
18469            }
18470
18471            return (mTypes & type) != 0;
18472        }
18473
18474        public void setDump(int type) {
18475            mTypes |= type;
18476        }
18477
18478        public boolean isOptionEnabled(int option) {
18479            return (mOptions & option) != 0;
18480        }
18481
18482        public void setOptionEnabled(int option) {
18483            mOptions |= option;
18484        }
18485
18486        public boolean onTitlePrinted() {
18487            final boolean printed = mTitlePrinted;
18488            mTitlePrinted = true;
18489            return printed;
18490        }
18491
18492        public boolean getTitlePrinted() {
18493            return mTitlePrinted;
18494        }
18495
18496        public void setTitlePrinted(boolean enabled) {
18497            mTitlePrinted = enabled;
18498        }
18499
18500        public SharedUserSetting getSharedUser() {
18501            return mSharedUser;
18502        }
18503
18504        public void setSharedUser(SharedUserSetting user) {
18505            mSharedUser = user;
18506        }
18507    }
18508
18509    @Override
18510    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18511            FileDescriptor err, String[] args, ShellCallback callback,
18512            ResultReceiver resultReceiver) {
18513        (new PackageManagerShellCommand(this)).exec(
18514                this, in, out, err, args, callback, resultReceiver);
18515    }
18516
18517    @Override
18518    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18519        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18520                != PackageManager.PERMISSION_GRANTED) {
18521            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18522                    + Binder.getCallingPid()
18523                    + ", uid=" + Binder.getCallingUid()
18524                    + " without permission "
18525                    + android.Manifest.permission.DUMP);
18526            return;
18527        }
18528
18529        DumpState dumpState = new DumpState();
18530        boolean fullPreferred = false;
18531        boolean checkin = false;
18532
18533        String packageName = null;
18534        ArraySet<String> permissionNames = null;
18535
18536        int opti = 0;
18537        while (opti < args.length) {
18538            String opt = args[opti];
18539            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18540                break;
18541            }
18542            opti++;
18543
18544            if ("-a".equals(opt)) {
18545                // Right now we only know how to print all.
18546            } else if ("-h".equals(opt)) {
18547                pw.println("Package manager dump options:");
18548                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18549                pw.println("    --checkin: dump for a checkin");
18550                pw.println("    -f: print details of intent filters");
18551                pw.println("    -h: print this help");
18552                pw.println("  cmd may be one of:");
18553                pw.println("    l[ibraries]: list known shared libraries");
18554                pw.println("    f[eatures]: list device features");
18555                pw.println("    k[eysets]: print known keysets");
18556                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18557                pw.println("    perm[issions]: dump permissions");
18558                pw.println("    permission [name ...]: dump declaration and use of given permission");
18559                pw.println("    pref[erred]: print preferred package settings");
18560                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18561                pw.println("    prov[iders]: dump content providers");
18562                pw.println("    p[ackages]: dump installed packages");
18563                pw.println("    s[hared-users]: dump shared user IDs");
18564                pw.println("    m[essages]: print collected runtime messages");
18565                pw.println("    v[erifiers]: print package verifier info");
18566                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18567                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18568                pw.println("    version: print database version info");
18569                pw.println("    write: write current settings now");
18570                pw.println("    installs: details about install sessions");
18571                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18572                pw.println("    dexopt: dump dexopt state");
18573                pw.println("    compiler-stats: dump compiler statistics");
18574                pw.println("    <package.name>: info about given package");
18575                return;
18576            } else if ("--checkin".equals(opt)) {
18577                checkin = true;
18578            } else if ("-f".equals(opt)) {
18579                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18580            } else {
18581                pw.println("Unknown argument: " + opt + "; use -h for help");
18582            }
18583        }
18584
18585        // Is the caller requesting to dump a particular piece of data?
18586        if (opti < args.length) {
18587            String cmd = args[opti];
18588            opti++;
18589            // Is this a package name?
18590            if ("android".equals(cmd) || cmd.contains(".")) {
18591                packageName = cmd;
18592                // When dumping a single package, we always dump all of its
18593                // filter information since the amount of data will be reasonable.
18594                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18595            } else if ("check-permission".equals(cmd)) {
18596                if (opti >= args.length) {
18597                    pw.println("Error: check-permission missing permission argument");
18598                    return;
18599                }
18600                String perm = args[opti];
18601                opti++;
18602                if (opti >= args.length) {
18603                    pw.println("Error: check-permission missing package argument");
18604                    return;
18605                }
18606                String pkg = args[opti];
18607                opti++;
18608                int user = UserHandle.getUserId(Binder.getCallingUid());
18609                if (opti < args.length) {
18610                    try {
18611                        user = Integer.parseInt(args[opti]);
18612                    } catch (NumberFormatException e) {
18613                        pw.println("Error: check-permission user argument is not a number: "
18614                                + args[opti]);
18615                        return;
18616                    }
18617                }
18618                pw.println(checkPermission(perm, pkg, user));
18619                return;
18620            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18621                dumpState.setDump(DumpState.DUMP_LIBS);
18622            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18623                dumpState.setDump(DumpState.DUMP_FEATURES);
18624            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18625                if (opti >= args.length) {
18626                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18627                            | DumpState.DUMP_SERVICE_RESOLVERS
18628                            | DumpState.DUMP_RECEIVER_RESOLVERS
18629                            | DumpState.DUMP_CONTENT_RESOLVERS);
18630                } else {
18631                    while (opti < args.length) {
18632                        String name = args[opti];
18633                        if ("a".equals(name) || "activity".equals(name)) {
18634                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18635                        } else if ("s".equals(name) || "service".equals(name)) {
18636                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18637                        } else if ("r".equals(name) || "receiver".equals(name)) {
18638                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18639                        } else if ("c".equals(name) || "content".equals(name)) {
18640                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18641                        } else {
18642                            pw.println("Error: unknown resolver table type: " + name);
18643                            return;
18644                        }
18645                        opti++;
18646                    }
18647                }
18648            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18649                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18650            } else if ("permission".equals(cmd)) {
18651                if (opti >= args.length) {
18652                    pw.println("Error: permission requires permission name");
18653                    return;
18654                }
18655                permissionNames = new ArraySet<>();
18656                while (opti < args.length) {
18657                    permissionNames.add(args[opti]);
18658                    opti++;
18659                }
18660                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18661                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18662            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18663                dumpState.setDump(DumpState.DUMP_PREFERRED);
18664            } else if ("preferred-xml".equals(cmd)) {
18665                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18666                if (opti < args.length && "--full".equals(args[opti])) {
18667                    fullPreferred = true;
18668                    opti++;
18669                }
18670            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18671                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18672            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18673                dumpState.setDump(DumpState.DUMP_PACKAGES);
18674            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18675                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18676            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18677                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18678            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18679                dumpState.setDump(DumpState.DUMP_MESSAGES);
18680            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18681                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18682            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18683                    || "intent-filter-verifiers".equals(cmd)) {
18684                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18685            } else if ("version".equals(cmd)) {
18686                dumpState.setDump(DumpState.DUMP_VERSION);
18687            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18688                dumpState.setDump(DumpState.DUMP_KEYSETS);
18689            } else if ("installs".equals(cmd)) {
18690                dumpState.setDump(DumpState.DUMP_INSTALLS);
18691            } else if ("frozen".equals(cmd)) {
18692                dumpState.setDump(DumpState.DUMP_FROZEN);
18693            } else if ("dexopt".equals(cmd)) {
18694                dumpState.setDump(DumpState.DUMP_DEXOPT);
18695            } else if ("compiler-stats".equals(cmd)) {
18696                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18697            } else if ("write".equals(cmd)) {
18698                synchronized (mPackages) {
18699                    mSettings.writeLPr();
18700                    pw.println("Settings written.");
18701                    return;
18702                }
18703            }
18704        }
18705
18706        if (checkin) {
18707            pw.println("vers,1");
18708        }
18709
18710        // reader
18711        synchronized (mPackages) {
18712            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18713                if (!checkin) {
18714                    if (dumpState.onTitlePrinted())
18715                        pw.println();
18716                    pw.println("Database versions:");
18717                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18718                }
18719            }
18720
18721            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18722                if (!checkin) {
18723                    if (dumpState.onTitlePrinted())
18724                        pw.println();
18725                    pw.println("Verifiers:");
18726                    pw.print("  Required: ");
18727                    pw.print(mRequiredVerifierPackage);
18728                    pw.print(" (uid=");
18729                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18730                            UserHandle.USER_SYSTEM));
18731                    pw.println(")");
18732                } else if (mRequiredVerifierPackage != null) {
18733                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18734                    pw.print(",");
18735                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18736                            UserHandle.USER_SYSTEM));
18737                }
18738            }
18739
18740            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18741                    packageName == null) {
18742                if (mIntentFilterVerifierComponent != null) {
18743                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18744                    if (!checkin) {
18745                        if (dumpState.onTitlePrinted())
18746                            pw.println();
18747                        pw.println("Intent Filter Verifier:");
18748                        pw.print("  Using: ");
18749                        pw.print(verifierPackageName);
18750                        pw.print(" (uid=");
18751                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18752                                UserHandle.USER_SYSTEM));
18753                        pw.println(")");
18754                    } else if (verifierPackageName != null) {
18755                        pw.print("ifv,"); pw.print(verifierPackageName);
18756                        pw.print(",");
18757                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18758                                UserHandle.USER_SYSTEM));
18759                    }
18760                } else {
18761                    pw.println();
18762                    pw.println("No Intent Filter Verifier available!");
18763                }
18764            }
18765
18766            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18767                boolean printedHeader = false;
18768                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18769                while (it.hasNext()) {
18770                    String name = it.next();
18771                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18772                    if (!checkin) {
18773                        if (!printedHeader) {
18774                            if (dumpState.onTitlePrinted())
18775                                pw.println();
18776                            pw.println("Libraries:");
18777                            printedHeader = true;
18778                        }
18779                        pw.print("  ");
18780                    } else {
18781                        pw.print("lib,");
18782                    }
18783                    pw.print(name);
18784                    if (!checkin) {
18785                        pw.print(" -> ");
18786                    }
18787                    if (ent.path != null) {
18788                        if (!checkin) {
18789                            pw.print("(jar) ");
18790                            pw.print(ent.path);
18791                        } else {
18792                            pw.print(",jar,");
18793                            pw.print(ent.path);
18794                        }
18795                    } else {
18796                        if (!checkin) {
18797                            pw.print("(apk) ");
18798                            pw.print(ent.apk);
18799                        } else {
18800                            pw.print(",apk,");
18801                            pw.print(ent.apk);
18802                        }
18803                    }
18804                    pw.println();
18805                }
18806            }
18807
18808            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18809                if (dumpState.onTitlePrinted())
18810                    pw.println();
18811                if (!checkin) {
18812                    pw.println("Features:");
18813                }
18814
18815                for (FeatureInfo feat : mAvailableFeatures.values()) {
18816                    if (checkin) {
18817                        pw.print("feat,");
18818                        pw.print(feat.name);
18819                        pw.print(",");
18820                        pw.println(feat.version);
18821                    } else {
18822                        pw.print("  ");
18823                        pw.print(feat.name);
18824                        if (feat.version > 0) {
18825                            pw.print(" version=");
18826                            pw.print(feat.version);
18827                        }
18828                        pw.println();
18829                    }
18830                }
18831            }
18832
18833            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18834                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18835                        : "Activity Resolver Table:", "  ", packageName,
18836                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18837                    dumpState.setTitlePrinted(true);
18838                }
18839            }
18840            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18841                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18842                        : "Receiver Resolver Table:", "  ", packageName,
18843                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18844                    dumpState.setTitlePrinted(true);
18845                }
18846            }
18847            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18848                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18849                        : "Service Resolver Table:", "  ", packageName,
18850                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18851                    dumpState.setTitlePrinted(true);
18852                }
18853            }
18854            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18855                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18856                        : "Provider Resolver Table:", "  ", packageName,
18857                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18858                    dumpState.setTitlePrinted(true);
18859                }
18860            }
18861
18862            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18863                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18864                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18865                    int user = mSettings.mPreferredActivities.keyAt(i);
18866                    if (pir.dump(pw,
18867                            dumpState.getTitlePrinted()
18868                                ? "\nPreferred Activities User " + user + ":"
18869                                : "Preferred Activities User " + user + ":", "  ",
18870                            packageName, true, false)) {
18871                        dumpState.setTitlePrinted(true);
18872                    }
18873                }
18874            }
18875
18876            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18877                pw.flush();
18878                FileOutputStream fout = new FileOutputStream(fd);
18879                BufferedOutputStream str = new BufferedOutputStream(fout);
18880                XmlSerializer serializer = new FastXmlSerializer();
18881                try {
18882                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18883                    serializer.startDocument(null, true);
18884                    serializer.setFeature(
18885                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18886                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18887                    serializer.endDocument();
18888                    serializer.flush();
18889                } catch (IllegalArgumentException e) {
18890                    pw.println("Failed writing: " + e);
18891                } catch (IllegalStateException e) {
18892                    pw.println("Failed writing: " + e);
18893                } catch (IOException e) {
18894                    pw.println("Failed writing: " + e);
18895                }
18896            }
18897
18898            if (!checkin
18899                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18900                    && packageName == null) {
18901                pw.println();
18902                int count = mSettings.mPackages.size();
18903                if (count == 0) {
18904                    pw.println("No applications!");
18905                    pw.println();
18906                } else {
18907                    final String prefix = "  ";
18908                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18909                    if (allPackageSettings.size() == 0) {
18910                        pw.println("No domain preferred apps!");
18911                        pw.println();
18912                    } else {
18913                        pw.println("App verification status:");
18914                        pw.println();
18915                        count = 0;
18916                        for (PackageSetting ps : allPackageSettings) {
18917                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18918                            if (ivi == null || ivi.getPackageName() == null) continue;
18919                            pw.println(prefix + "Package: " + ivi.getPackageName());
18920                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18921                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18922                            pw.println();
18923                            count++;
18924                        }
18925                        if (count == 0) {
18926                            pw.println(prefix + "No app verification established.");
18927                            pw.println();
18928                        }
18929                        for (int userId : sUserManager.getUserIds()) {
18930                            pw.println("App linkages for user " + userId + ":");
18931                            pw.println();
18932                            count = 0;
18933                            for (PackageSetting ps : allPackageSettings) {
18934                                final long status = ps.getDomainVerificationStatusForUser(userId);
18935                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18936                                    continue;
18937                                }
18938                                pw.println(prefix + "Package: " + ps.name);
18939                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18940                                String statusStr = IntentFilterVerificationInfo.
18941                                        getStatusStringFromValue(status);
18942                                pw.println(prefix + "Status:  " + statusStr);
18943                                pw.println();
18944                                count++;
18945                            }
18946                            if (count == 0) {
18947                                pw.println(prefix + "No configured app linkages.");
18948                                pw.println();
18949                            }
18950                        }
18951                    }
18952                }
18953            }
18954
18955            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18956                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18957                if (packageName == null && permissionNames == null) {
18958                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18959                        if (iperm == 0) {
18960                            if (dumpState.onTitlePrinted())
18961                                pw.println();
18962                            pw.println("AppOp Permissions:");
18963                        }
18964                        pw.print("  AppOp Permission ");
18965                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18966                        pw.println(":");
18967                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18968                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18969                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18970                        }
18971                    }
18972                }
18973            }
18974
18975            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18976                boolean printedSomething = false;
18977                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18978                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18979                        continue;
18980                    }
18981                    if (!printedSomething) {
18982                        if (dumpState.onTitlePrinted())
18983                            pw.println();
18984                        pw.println("Registered ContentProviders:");
18985                        printedSomething = true;
18986                    }
18987                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18988                    pw.print("    "); pw.println(p.toString());
18989                }
18990                printedSomething = false;
18991                for (Map.Entry<String, PackageParser.Provider> entry :
18992                        mProvidersByAuthority.entrySet()) {
18993                    PackageParser.Provider p = entry.getValue();
18994                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18995                        continue;
18996                    }
18997                    if (!printedSomething) {
18998                        if (dumpState.onTitlePrinted())
18999                            pw.println();
19000                        pw.println("ContentProvider Authorities:");
19001                        printedSomething = true;
19002                    }
19003                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19004                    pw.print("    "); pw.println(p.toString());
19005                    if (p.info != null && p.info.applicationInfo != null) {
19006                        final String appInfo = p.info.applicationInfo.toString();
19007                        pw.print("      applicationInfo="); pw.println(appInfo);
19008                    }
19009                }
19010            }
19011
19012            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19013                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19014            }
19015
19016            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19017                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19018            }
19019
19020            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19021                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19022            }
19023
19024            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19025                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19026            }
19027
19028            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19029                // XXX should handle packageName != null by dumping only install data that
19030                // the given package is involved with.
19031                if (dumpState.onTitlePrinted()) pw.println();
19032                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19033            }
19034
19035            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19036                // XXX should handle packageName != null by dumping only install data that
19037                // the given package is involved with.
19038                if (dumpState.onTitlePrinted()) pw.println();
19039
19040                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19041                ipw.println();
19042                ipw.println("Frozen packages:");
19043                ipw.increaseIndent();
19044                if (mFrozenPackages.size() == 0) {
19045                    ipw.println("(none)");
19046                } else {
19047                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19048                        ipw.println(mFrozenPackages.valueAt(i));
19049                    }
19050                }
19051                ipw.decreaseIndent();
19052            }
19053
19054            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19055                if (dumpState.onTitlePrinted()) pw.println();
19056                dumpDexoptStateLPr(pw, packageName);
19057            }
19058
19059            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19060                if (dumpState.onTitlePrinted()) pw.println();
19061                dumpCompilerStatsLPr(pw, packageName);
19062            }
19063
19064            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19065                if (dumpState.onTitlePrinted()) pw.println();
19066                mSettings.dumpReadMessagesLPr(pw, dumpState);
19067
19068                pw.println();
19069                pw.println("Package warning messages:");
19070                BufferedReader in = null;
19071                String line = null;
19072                try {
19073                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19074                    while ((line = in.readLine()) != null) {
19075                        if (line.contains("ignored: updated version")) continue;
19076                        pw.println(line);
19077                    }
19078                } catch (IOException ignored) {
19079                } finally {
19080                    IoUtils.closeQuietly(in);
19081                }
19082            }
19083
19084            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19085                BufferedReader in = null;
19086                String line = null;
19087                try {
19088                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19089                    while ((line = in.readLine()) != null) {
19090                        if (line.contains("ignored: updated version")) continue;
19091                        pw.print("msg,");
19092                        pw.println(line);
19093                    }
19094                } catch (IOException ignored) {
19095                } finally {
19096                    IoUtils.closeQuietly(in);
19097                }
19098            }
19099        }
19100    }
19101
19102    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19103        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19104        ipw.println();
19105        ipw.println("Dexopt state:");
19106        ipw.increaseIndent();
19107        Collection<PackageParser.Package> packages = null;
19108        if (packageName != null) {
19109            PackageParser.Package targetPackage = mPackages.get(packageName);
19110            if (targetPackage != null) {
19111                packages = Collections.singletonList(targetPackage);
19112            } else {
19113                ipw.println("Unable to find package: " + packageName);
19114                return;
19115            }
19116        } else {
19117            packages = mPackages.values();
19118        }
19119
19120        for (PackageParser.Package pkg : packages) {
19121            ipw.println("[" + pkg.packageName + "]");
19122            ipw.increaseIndent();
19123            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19124            ipw.decreaseIndent();
19125        }
19126    }
19127
19128    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19129        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19130        ipw.println();
19131        ipw.println("Compiler stats:");
19132        ipw.increaseIndent();
19133        Collection<PackageParser.Package> packages = null;
19134        if (packageName != null) {
19135            PackageParser.Package targetPackage = mPackages.get(packageName);
19136            if (targetPackage != null) {
19137                packages = Collections.singletonList(targetPackage);
19138            } else {
19139                ipw.println("Unable to find package: " + packageName);
19140                return;
19141            }
19142        } else {
19143            packages = mPackages.values();
19144        }
19145
19146        for (PackageParser.Package pkg : packages) {
19147            ipw.println("[" + pkg.packageName + "]");
19148            ipw.increaseIndent();
19149
19150            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19151            if (stats == null) {
19152                ipw.println("(No recorded stats)");
19153            } else {
19154                stats.dump(ipw);
19155            }
19156            ipw.decreaseIndent();
19157        }
19158    }
19159
19160    private String dumpDomainString(String packageName) {
19161        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19162                .getList();
19163        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19164
19165        ArraySet<String> result = new ArraySet<>();
19166        if (iviList.size() > 0) {
19167            for (IntentFilterVerificationInfo ivi : iviList) {
19168                for (String host : ivi.getDomains()) {
19169                    result.add(host);
19170                }
19171            }
19172        }
19173        if (filters != null && filters.size() > 0) {
19174            for (IntentFilter filter : filters) {
19175                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19176                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19177                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19178                    result.addAll(filter.getHostsList());
19179                }
19180            }
19181        }
19182
19183        StringBuilder sb = new StringBuilder(result.size() * 16);
19184        for (String domain : result) {
19185            if (sb.length() > 0) sb.append(" ");
19186            sb.append(domain);
19187        }
19188        return sb.toString();
19189    }
19190
19191    // ------- apps on sdcard specific code -------
19192    static final boolean DEBUG_SD_INSTALL = false;
19193
19194    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19195
19196    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19197
19198    private boolean mMediaMounted = false;
19199
19200    static String getEncryptKey() {
19201        try {
19202            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19203                    SD_ENCRYPTION_KEYSTORE_NAME);
19204            if (sdEncKey == null) {
19205                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19206                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19207                if (sdEncKey == null) {
19208                    Slog.e(TAG, "Failed to create encryption keys");
19209                    return null;
19210                }
19211            }
19212            return sdEncKey;
19213        } catch (NoSuchAlgorithmException nsae) {
19214            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19215            return null;
19216        } catch (IOException ioe) {
19217            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19218            return null;
19219        }
19220    }
19221
19222    /*
19223     * Update media status on PackageManager.
19224     */
19225    @Override
19226    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19227        int callingUid = Binder.getCallingUid();
19228        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19229            throw new SecurityException("Media status can only be updated by the system");
19230        }
19231        // reader; this apparently protects mMediaMounted, but should probably
19232        // be a different lock in that case.
19233        synchronized (mPackages) {
19234            Log.i(TAG, "Updating external media status from "
19235                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19236                    + (mediaStatus ? "mounted" : "unmounted"));
19237            if (DEBUG_SD_INSTALL)
19238                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19239                        + ", mMediaMounted=" + mMediaMounted);
19240            if (mediaStatus == mMediaMounted) {
19241                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19242                        : 0, -1);
19243                mHandler.sendMessage(msg);
19244                return;
19245            }
19246            mMediaMounted = mediaStatus;
19247        }
19248        // Queue up an async operation since the package installation may take a
19249        // little while.
19250        mHandler.post(new Runnable() {
19251            public void run() {
19252                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19253            }
19254        });
19255    }
19256
19257    /**
19258     * Called by MountService when the initial ASECs to scan are available.
19259     * Should block until all the ASEC containers are finished being scanned.
19260     */
19261    public void scanAvailableAsecs() {
19262        updateExternalMediaStatusInner(true, false, false);
19263    }
19264
19265    /*
19266     * Collect information of applications on external media, map them against
19267     * existing containers and update information based on current mount status.
19268     * Please note that we always have to report status if reportStatus has been
19269     * set to true especially when unloading packages.
19270     */
19271    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19272            boolean externalStorage) {
19273        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19274        int[] uidArr = EmptyArray.INT;
19275
19276        final String[] list = PackageHelper.getSecureContainerList();
19277        if (ArrayUtils.isEmpty(list)) {
19278            Log.i(TAG, "No secure containers found");
19279        } else {
19280            // Process list of secure containers and categorize them
19281            // as active or stale based on their package internal state.
19282
19283            // reader
19284            synchronized (mPackages) {
19285                for (String cid : list) {
19286                    // Leave stages untouched for now; installer service owns them
19287                    if (PackageInstallerService.isStageName(cid)) continue;
19288
19289                    if (DEBUG_SD_INSTALL)
19290                        Log.i(TAG, "Processing container " + cid);
19291                    String pkgName = getAsecPackageName(cid);
19292                    if (pkgName == null) {
19293                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19294                        continue;
19295                    }
19296                    if (DEBUG_SD_INSTALL)
19297                        Log.i(TAG, "Looking for pkg : " + pkgName);
19298
19299                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19300                    if (ps == null) {
19301                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19302                        continue;
19303                    }
19304
19305                    /*
19306                     * Skip packages that are not external if we're unmounting
19307                     * external storage.
19308                     */
19309                    if (externalStorage && !isMounted && !isExternal(ps)) {
19310                        continue;
19311                    }
19312
19313                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19314                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19315                    // The package status is changed only if the code path
19316                    // matches between settings and the container id.
19317                    if (ps.codePathString != null
19318                            && ps.codePathString.startsWith(args.getCodePath())) {
19319                        if (DEBUG_SD_INSTALL) {
19320                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19321                                    + " at code path: " + ps.codePathString);
19322                        }
19323
19324                        // We do have a valid package installed on sdcard
19325                        processCids.put(args, ps.codePathString);
19326                        final int uid = ps.appId;
19327                        if (uid != -1) {
19328                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19329                        }
19330                    } else {
19331                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19332                                + ps.codePathString);
19333                    }
19334                }
19335            }
19336
19337            Arrays.sort(uidArr);
19338        }
19339
19340        // Process packages with valid entries.
19341        if (isMounted) {
19342            if (DEBUG_SD_INSTALL)
19343                Log.i(TAG, "Loading packages");
19344            loadMediaPackages(processCids, uidArr, externalStorage);
19345            startCleaningPackages();
19346            mInstallerService.onSecureContainersAvailable();
19347        } else {
19348            if (DEBUG_SD_INSTALL)
19349                Log.i(TAG, "Unloading packages");
19350            unloadMediaPackages(processCids, uidArr, reportStatus);
19351        }
19352    }
19353
19354    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19355            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19356        final int size = infos.size();
19357        final String[] packageNames = new String[size];
19358        final int[] packageUids = new int[size];
19359        for (int i = 0; i < size; i++) {
19360            final ApplicationInfo info = infos.get(i);
19361            packageNames[i] = info.packageName;
19362            packageUids[i] = info.uid;
19363        }
19364        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19365                finishedReceiver);
19366    }
19367
19368    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19369            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19370        sendResourcesChangedBroadcast(mediaStatus, replacing,
19371                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19372    }
19373
19374    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19375            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19376        int size = pkgList.length;
19377        if (size > 0) {
19378            // Send broadcasts here
19379            Bundle extras = new Bundle();
19380            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19381            if (uidArr != null) {
19382                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19383            }
19384            if (replacing) {
19385                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19386            }
19387            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19388                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19389            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19390        }
19391    }
19392
19393   /*
19394     * Look at potentially valid container ids from processCids If package
19395     * information doesn't match the one on record or package scanning fails,
19396     * the cid is added to list of removeCids. We currently don't delete stale
19397     * containers.
19398     */
19399    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19400            boolean externalStorage) {
19401        ArrayList<String> pkgList = new ArrayList<String>();
19402        Set<AsecInstallArgs> keys = processCids.keySet();
19403
19404        for (AsecInstallArgs args : keys) {
19405            String codePath = processCids.get(args);
19406            if (DEBUG_SD_INSTALL)
19407                Log.i(TAG, "Loading container : " + args.cid);
19408            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19409            try {
19410                // Make sure there are no container errors first.
19411                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19412                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19413                            + " when installing from sdcard");
19414                    continue;
19415                }
19416                // Check code path here.
19417                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19418                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19419                            + " does not match one in settings " + codePath);
19420                    continue;
19421                }
19422                // Parse package
19423                int parseFlags = mDefParseFlags;
19424                if (args.isExternalAsec()) {
19425                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19426                }
19427                if (args.isFwdLocked()) {
19428                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19429                }
19430
19431                synchronized (mInstallLock) {
19432                    PackageParser.Package pkg = null;
19433                    try {
19434                        // Sadly we don't know the package name yet to freeze it
19435                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19436                                SCAN_IGNORE_FROZEN, 0, null);
19437                    } catch (PackageManagerException e) {
19438                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19439                    }
19440                    // Scan the package
19441                    if (pkg != null) {
19442                        /*
19443                         * TODO why is the lock being held? doPostInstall is
19444                         * called in other places without the lock. This needs
19445                         * to be straightened out.
19446                         */
19447                        // writer
19448                        synchronized (mPackages) {
19449                            retCode = PackageManager.INSTALL_SUCCEEDED;
19450                            pkgList.add(pkg.packageName);
19451                            // Post process args
19452                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19453                                    pkg.applicationInfo.uid);
19454                        }
19455                    } else {
19456                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19457                    }
19458                }
19459
19460            } finally {
19461                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19462                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19463                }
19464            }
19465        }
19466        // writer
19467        synchronized (mPackages) {
19468            // If the platform SDK has changed since the last time we booted,
19469            // we need to re-grant app permission to catch any new ones that
19470            // appear. This is really a hack, and means that apps can in some
19471            // cases get permissions that the user didn't initially explicitly
19472            // allow... it would be nice to have some better way to handle
19473            // this situation.
19474            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19475                    : mSettings.getInternalVersion();
19476            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19477                    : StorageManager.UUID_PRIVATE_INTERNAL;
19478
19479            int updateFlags = UPDATE_PERMISSIONS_ALL;
19480            if (ver.sdkVersion != mSdkVersion) {
19481                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19482                        + mSdkVersion + "; regranting permissions for external");
19483                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19484            }
19485            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19486
19487            // Yay, everything is now upgraded
19488            ver.forceCurrent();
19489
19490            // can downgrade to reader
19491            // Persist settings
19492            mSettings.writeLPr();
19493        }
19494        // Send a broadcast to let everyone know we are done processing
19495        if (pkgList.size() > 0) {
19496            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19497        }
19498    }
19499
19500   /*
19501     * Utility method to unload a list of specified containers
19502     */
19503    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19504        // Just unmount all valid containers.
19505        for (AsecInstallArgs arg : cidArgs) {
19506            synchronized (mInstallLock) {
19507                arg.doPostDeleteLI(false);
19508           }
19509       }
19510   }
19511
19512    /*
19513     * Unload packages mounted on external media. This involves deleting package
19514     * data from internal structures, sending broadcasts about disabled packages,
19515     * gc'ing to free up references, unmounting all secure containers
19516     * corresponding to packages on external media, and posting a
19517     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19518     * that we always have to post this message if status has been requested no
19519     * matter what.
19520     */
19521    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19522            final boolean reportStatus) {
19523        if (DEBUG_SD_INSTALL)
19524            Log.i(TAG, "unloading media packages");
19525        ArrayList<String> pkgList = new ArrayList<String>();
19526        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19527        final Set<AsecInstallArgs> keys = processCids.keySet();
19528        for (AsecInstallArgs args : keys) {
19529            String pkgName = args.getPackageName();
19530            if (DEBUG_SD_INSTALL)
19531                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19532            // Delete package internally
19533            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19534            synchronized (mInstallLock) {
19535                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19536                final boolean res;
19537                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19538                        "unloadMediaPackages")) {
19539                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19540                            null);
19541                }
19542                if (res) {
19543                    pkgList.add(pkgName);
19544                } else {
19545                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19546                    failedList.add(args);
19547                }
19548            }
19549        }
19550
19551        // reader
19552        synchronized (mPackages) {
19553            // We didn't update the settings after removing each package;
19554            // write them now for all packages.
19555            mSettings.writeLPr();
19556        }
19557
19558        // We have to absolutely send UPDATED_MEDIA_STATUS only
19559        // after confirming that all the receivers processed the ordered
19560        // broadcast when packages get disabled, force a gc to clean things up.
19561        // and unload all the containers.
19562        if (pkgList.size() > 0) {
19563            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19564                    new IIntentReceiver.Stub() {
19565                public void performReceive(Intent intent, int resultCode, String data,
19566                        Bundle extras, boolean ordered, boolean sticky,
19567                        int sendingUser) throws RemoteException {
19568                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19569                            reportStatus ? 1 : 0, 1, keys);
19570                    mHandler.sendMessage(msg);
19571                }
19572            });
19573        } else {
19574            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19575                    keys);
19576            mHandler.sendMessage(msg);
19577        }
19578    }
19579
19580    private void loadPrivatePackages(final VolumeInfo vol) {
19581        mHandler.post(new Runnable() {
19582            @Override
19583            public void run() {
19584                loadPrivatePackagesInner(vol);
19585            }
19586        });
19587    }
19588
19589    private void loadPrivatePackagesInner(VolumeInfo vol) {
19590        final String volumeUuid = vol.fsUuid;
19591        if (TextUtils.isEmpty(volumeUuid)) {
19592            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19593            return;
19594        }
19595
19596        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19597        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19598        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19599
19600        final VersionInfo ver;
19601        final List<PackageSetting> packages;
19602        synchronized (mPackages) {
19603            ver = mSettings.findOrCreateVersion(volumeUuid);
19604            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19605        }
19606
19607        for (PackageSetting ps : packages) {
19608            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19609            synchronized (mInstallLock) {
19610                final PackageParser.Package pkg;
19611                try {
19612                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19613                    loaded.add(pkg.applicationInfo);
19614
19615                } catch (PackageManagerException e) {
19616                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19617                }
19618
19619                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19620                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19621                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19622                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19623                }
19624            }
19625        }
19626
19627        // Reconcile app data for all started/unlocked users
19628        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19629        final UserManager um = mContext.getSystemService(UserManager.class);
19630        UserManagerInternal umInternal = getUserManagerInternal();
19631        for (UserInfo user : um.getUsers()) {
19632            final int flags;
19633            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19634                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19635            } else if (umInternal.isUserRunning(user.id)) {
19636                flags = StorageManager.FLAG_STORAGE_DE;
19637            } else {
19638                continue;
19639            }
19640
19641            try {
19642                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19643                synchronized (mInstallLock) {
19644                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19645                }
19646            } catch (IllegalStateException e) {
19647                // Device was probably ejected, and we'll process that event momentarily
19648                Slog.w(TAG, "Failed to prepare storage: " + e);
19649            }
19650        }
19651
19652        synchronized (mPackages) {
19653            int updateFlags = UPDATE_PERMISSIONS_ALL;
19654            if (ver.sdkVersion != mSdkVersion) {
19655                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19656                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19657                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19658            }
19659            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19660
19661            // Yay, everything is now upgraded
19662            ver.forceCurrent();
19663
19664            mSettings.writeLPr();
19665        }
19666
19667        for (PackageFreezer freezer : freezers) {
19668            freezer.close();
19669        }
19670
19671        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19672        sendResourcesChangedBroadcast(true, false, loaded, null);
19673    }
19674
19675    private void unloadPrivatePackages(final VolumeInfo vol) {
19676        mHandler.post(new Runnable() {
19677            @Override
19678            public void run() {
19679                unloadPrivatePackagesInner(vol);
19680            }
19681        });
19682    }
19683
19684    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19685        final String volumeUuid = vol.fsUuid;
19686        if (TextUtils.isEmpty(volumeUuid)) {
19687            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19688            return;
19689        }
19690
19691        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19692        synchronized (mInstallLock) {
19693        synchronized (mPackages) {
19694            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19695            for (PackageSetting ps : packages) {
19696                if (ps.pkg == null) continue;
19697
19698                final ApplicationInfo info = ps.pkg.applicationInfo;
19699                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19700                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19701
19702                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19703                        "unloadPrivatePackagesInner")) {
19704                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19705                            false, null)) {
19706                        unloaded.add(info);
19707                    } else {
19708                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19709                    }
19710                }
19711
19712                // Try very hard to release any references to this package
19713                // so we don't risk the system server being killed due to
19714                // open FDs
19715                AttributeCache.instance().removePackage(ps.name);
19716            }
19717
19718            mSettings.writeLPr();
19719        }
19720        }
19721
19722        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19723        sendResourcesChangedBroadcast(false, false, unloaded, null);
19724
19725        // Try very hard to release any references to this path so we don't risk
19726        // the system server being killed due to open FDs
19727        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19728
19729        for (int i = 0; i < 3; i++) {
19730            System.gc();
19731            System.runFinalization();
19732        }
19733    }
19734
19735    /**
19736     * Prepare storage areas for given user on all mounted devices.
19737     */
19738    void prepareUserData(int userId, int userSerial, int flags) {
19739        synchronized (mInstallLock) {
19740            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19741            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19742                final String volumeUuid = vol.getFsUuid();
19743                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19744            }
19745        }
19746    }
19747
19748    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19749            boolean allowRecover) {
19750        // Prepare storage and verify that serial numbers are consistent; if
19751        // there's a mismatch we need to destroy to avoid leaking data
19752        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19753        try {
19754            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19755
19756            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19757                UserManagerService.enforceSerialNumber(
19758                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19759                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19760                    UserManagerService.enforceSerialNumber(
19761                            Environment.getDataSystemDeDirectory(userId), userSerial);
19762                }
19763            }
19764            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19765                UserManagerService.enforceSerialNumber(
19766                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19767                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19768                    UserManagerService.enforceSerialNumber(
19769                            Environment.getDataSystemCeDirectory(userId), userSerial);
19770                }
19771            }
19772
19773            synchronized (mInstallLock) {
19774                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19775            }
19776        } catch (Exception e) {
19777            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19778                    + " because we failed to prepare: " + e);
19779            destroyUserDataLI(volumeUuid, userId,
19780                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19781
19782            if (allowRecover) {
19783                // Try one last time; if we fail again we're really in trouble
19784                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19785            }
19786        }
19787    }
19788
19789    /**
19790     * Destroy storage areas for given user on all mounted devices.
19791     */
19792    void destroyUserData(int userId, int flags) {
19793        synchronized (mInstallLock) {
19794            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19795            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19796                final String volumeUuid = vol.getFsUuid();
19797                destroyUserDataLI(volumeUuid, userId, flags);
19798            }
19799        }
19800    }
19801
19802    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19803        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19804        try {
19805            // Clean up app data, profile data, and media data
19806            mInstaller.destroyUserData(volumeUuid, userId, flags);
19807
19808            // Clean up system data
19809            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19810                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19811                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19812                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19813                }
19814                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19815                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19816                }
19817            }
19818
19819            // Data with special labels is now gone, so finish the job
19820            storage.destroyUserStorage(volumeUuid, userId, flags);
19821
19822        } catch (Exception e) {
19823            logCriticalInfo(Log.WARN,
19824                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19825        }
19826    }
19827
19828    /**
19829     * Examine all users present on given mounted volume, and destroy data
19830     * belonging to users that are no longer valid, or whose user ID has been
19831     * recycled.
19832     */
19833    private void reconcileUsers(String volumeUuid) {
19834        final List<File> files = new ArrayList<>();
19835        Collections.addAll(files, FileUtils
19836                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19837        Collections.addAll(files, FileUtils
19838                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19839        Collections.addAll(files, FileUtils
19840                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19841        Collections.addAll(files, FileUtils
19842                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19843        for (File file : files) {
19844            if (!file.isDirectory()) continue;
19845
19846            final int userId;
19847            final UserInfo info;
19848            try {
19849                userId = Integer.parseInt(file.getName());
19850                info = sUserManager.getUserInfo(userId);
19851            } catch (NumberFormatException e) {
19852                Slog.w(TAG, "Invalid user directory " + file);
19853                continue;
19854            }
19855
19856            boolean destroyUser = false;
19857            if (info == null) {
19858                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19859                        + " because no matching user was found");
19860                destroyUser = true;
19861            } else if (!mOnlyCore) {
19862                try {
19863                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19864                } catch (IOException e) {
19865                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19866                            + " because we failed to enforce serial number: " + e);
19867                    destroyUser = true;
19868                }
19869            }
19870
19871            if (destroyUser) {
19872                synchronized (mInstallLock) {
19873                    destroyUserDataLI(volumeUuid, userId,
19874                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19875                }
19876            }
19877        }
19878    }
19879
19880    private void assertPackageKnown(String volumeUuid, String packageName)
19881            throws PackageManagerException {
19882        synchronized (mPackages) {
19883            final PackageSetting ps = mSettings.mPackages.get(packageName);
19884            if (ps == null) {
19885                throw new PackageManagerException("Package " + packageName + " is unknown");
19886            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19887                throw new PackageManagerException(
19888                        "Package " + packageName + " found on unknown volume " + volumeUuid
19889                                + "; expected volume " + ps.volumeUuid);
19890            }
19891        }
19892    }
19893
19894    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19895            throws PackageManagerException {
19896        synchronized (mPackages) {
19897            final PackageSetting ps = mSettings.mPackages.get(packageName);
19898            if (ps == null) {
19899                throw new PackageManagerException("Package " + packageName + " is unknown");
19900            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19901                throw new PackageManagerException(
19902                        "Package " + packageName + " found on unknown volume " + volumeUuid
19903                                + "; expected volume " + ps.volumeUuid);
19904            } else if (!ps.getInstalled(userId)) {
19905                throw new PackageManagerException(
19906                        "Package " + packageName + " not installed for user " + userId);
19907            }
19908        }
19909    }
19910
19911    /**
19912     * Examine all apps present on given mounted volume, and destroy apps that
19913     * aren't expected, either due to uninstallation or reinstallation on
19914     * another volume.
19915     */
19916    private void reconcileApps(String volumeUuid) {
19917        final File[] files = FileUtils
19918                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19919        for (File file : files) {
19920            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19921                    && !PackageInstallerService.isStageName(file.getName());
19922            if (!isPackage) {
19923                // Ignore entries which are not packages
19924                continue;
19925            }
19926
19927            try {
19928                final PackageLite pkg = PackageParser.parsePackageLite(file,
19929                        PackageParser.PARSE_MUST_BE_APK);
19930                assertPackageKnown(volumeUuid, pkg.packageName);
19931
19932            } catch (PackageParserException | PackageManagerException e) {
19933                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19934                synchronized (mInstallLock) {
19935                    removeCodePathLI(file);
19936                }
19937            }
19938        }
19939    }
19940
19941    /**
19942     * Reconcile all app data for the given user.
19943     * <p>
19944     * Verifies that directories exist and that ownership and labeling is
19945     * correct for all installed apps on all mounted volumes.
19946     */
19947    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19948        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19949        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19950            final String volumeUuid = vol.getFsUuid();
19951            synchronized (mInstallLock) {
19952                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19953            }
19954        }
19955    }
19956
19957    /**
19958     * Reconcile all app data on given mounted volume.
19959     * <p>
19960     * Destroys app data that isn't expected, either due to uninstallation or
19961     * reinstallation on another volume.
19962     * <p>
19963     * Verifies that directories exist and that ownership and labeling is
19964     * correct for all installed apps.
19965     */
19966    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19967            boolean migrateAppData) {
19968        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19969                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19970
19971        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19972        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19973
19974        // First look for stale data that doesn't belong, and check if things
19975        // have changed since we did our last restorecon
19976        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19977            if (StorageManager.isFileEncryptedNativeOrEmulated()
19978                    && !StorageManager.isUserKeyUnlocked(userId)) {
19979                throw new RuntimeException(
19980                        "Yikes, someone asked us to reconcile CE storage while " + userId
19981                                + " was still locked; this would have caused massive data loss!");
19982            }
19983
19984            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19985            for (File file : files) {
19986                final String packageName = file.getName();
19987                try {
19988                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19989                } catch (PackageManagerException e) {
19990                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19991                    try {
19992                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19993                                StorageManager.FLAG_STORAGE_CE, 0);
19994                    } catch (InstallerException e2) {
19995                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19996                    }
19997                }
19998            }
19999        }
20000        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20001            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20002            for (File file : files) {
20003                final String packageName = file.getName();
20004                try {
20005                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20006                } catch (PackageManagerException e) {
20007                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20008                    try {
20009                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20010                                StorageManager.FLAG_STORAGE_DE, 0);
20011                    } catch (InstallerException e2) {
20012                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20013                    }
20014                }
20015            }
20016        }
20017
20018        // Ensure that data directories are ready to roll for all packages
20019        // installed for this volume and user
20020        final List<PackageSetting> packages;
20021        synchronized (mPackages) {
20022            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20023        }
20024        int preparedCount = 0;
20025        for (PackageSetting ps : packages) {
20026            final String packageName = ps.name;
20027            if (ps.pkg == null) {
20028                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20029                // TODO: might be due to legacy ASEC apps; we should circle back
20030                // and reconcile again once they're scanned
20031                continue;
20032            }
20033
20034            if (ps.getInstalled(userId)) {
20035                prepareAppDataLIF(ps.pkg, userId, flags);
20036
20037                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20038                    // We may have just shuffled around app data directories, so
20039                    // prepare them one more time
20040                    prepareAppDataLIF(ps.pkg, userId, flags);
20041                }
20042
20043                preparedCount++;
20044            }
20045        }
20046
20047        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20048    }
20049
20050    /**
20051     * Prepare app data for the given app just after it was installed or
20052     * upgraded. This method carefully only touches users that it's installed
20053     * for, and it forces a restorecon to handle any seinfo changes.
20054     * <p>
20055     * Verifies that directories exist and that ownership and labeling is
20056     * correct for all installed apps. If there is an ownership mismatch, it
20057     * will try recovering system apps by wiping data; third-party app data is
20058     * left intact.
20059     * <p>
20060     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20061     */
20062    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20063        final PackageSetting ps;
20064        synchronized (mPackages) {
20065            ps = mSettings.mPackages.get(pkg.packageName);
20066            mSettings.writeKernelMappingLPr(ps);
20067        }
20068
20069        final UserManager um = mContext.getSystemService(UserManager.class);
20070        UserManagerInternal umInternal = getUserManagerInternal();
20071        for (UserInfo user : um.getUsers()) {
20072            final int flags;
20073            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20074                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20075            } else if (umInternal.isUserRunning(user.id)) {
20076                flags = StorageManager.FLAG_STORAGE_DE;
20077            } else {
20078                continue;
20079            }
20080
20081            if (ps.getInstalled(user.id)) {
20082                // TODO: when user data is locked, mark that we're still dirty
20083                prepareAppDataLIF(pkg, user.id, flags);
20084            }
20085        }
20086    }
20087
20088    /**
20089     * Prepare app data for the given app.
20090     * <p>
20091     * Verifies that directories exist and that ownership and labeling is
20092     * correct for all installed apps. If there is an ownership mismatch, this
20093     * will try recovering system apps by wiping data; third-party app data is
20094     * left intact.
20095     */
20096    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20097        if (pkg == null) {
20098            Slog.wtf(TAG, "Package was null!", new Throwable());
20099            return;
20100        }
20101        prepareAppDataLeafLIF(pkg, userId, flags);
20102        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20103        for (int i = 0; i < childCount; i++) {
20104            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20105        }
20106    }
20107
20108    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20109        if (DEBUG_APP_DATA) {
20110            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20111                    + Integer.toHexString(flags));
20112        }
20113
20114        final String volumeUuid = pkg.volumeUuid;
20115        final String packageName = pkg.packageName;
20116        final ApplicationInfo app = pkg.applicationInfo;
20117        final int appId = UserHandle.getAppId(app.uid);
20118
20119        Preconditions.checkNotNull(app.seinfo);
20120
20121        try {
20122            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20123                    appId, app.seinfo, app.targetSdkVersion);
20124        } catch (InstallerException e) {
20125            if (app.isSystemApp()) {
20126                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20127                        + ", but trying to recover: " + e);
20128                destroyAppDataLeafLIF(pkg, userId, flags);
20129                try {
20130                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20131                            appId, app.seinfo, app.targetSdkVersion);
20132                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20133                } catch (InstallerException e2) {
20134                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20135                }
20136            } else {
20137                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20138            }
20139        }
20140
20141        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20142            try {
20143                // CE storage is unlocked right now, so read out the inode and
20144                // remember for use later when it's locked
20145                // TODO: mark this structure as dirty so we persist it!
20146                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20147                        StorageManager.FLAG_STORAGE_CE);
20148                synchronized (mPackages) {
20149                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20150                    if (ps != null) {
20151                        ps.setCeDataInode(ceDataInode, userId);
20152                    }
20153                }
20154            } catch (InstallerException e) {
20155                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20156            }
20157        }
20158
20159        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20160    }
20161
20162    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20163        if (pkg == null) {
20164            Slog.wtf(TAG, "Package was null!", new Throwable());
20165            return;
20166        }
20167        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20168        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20169        for (int i = 0; i < childCount; i++) {
20170            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20171        }
20172    }
20173
20174    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20175        final String volumeUuid = pkg.volumeUuid;
20176        final String packageName = pkg.packageName;
20177        final ApplicationInfo app = pkg.applicationInfo;
20178
20179        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20180            // Create a native library symlink only if we have native libraries
20181            // and if the native libraries are 32 bit libraries. We do not provide
20182            // this symlink for 64 bit libraries.
20183            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20184                final String nativeLibPath = app.nativeLibraryDir;
20185                try {
20186                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20187                            nativeLibPath, userId);
20188                } catch (InstallerException e) {
20189                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20190                }
20191            }
20192        }
20193    }
20194
20195    /**
20196     * For system apps on non-FBE devices, this method migrates any existing
20197     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20198     * requested by the app.
20199     */
20200    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20201        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20202                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20203            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20204                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20205            try {
20206                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20207                        storageTarget);
20208            } catch (InstallerException e) {
20209                logCriticalInfo(Log.WARN,
20210                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20211            }
20212            return true;
20213        } else {
20214            return false;
20215        }
20216    }
20217
20218    public PackageFreezer freezePackage(String packageName, String killReason) {
20219        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20220    }
20221
20222    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20223        return new PackageFreezer(packageName, userId, killReason);
20224    }
20225
20226    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20227            String killReason) {
20228        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20229    }
20230
20231    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20232            String killReason) {
20233        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20234            return new PackageFreezer();
20235        } else {
20236            return freezePackage(packageName, userId, killReason);
20237        }
20238    }
20239
20240    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20241            String killReason) {
20242        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20243    }
20244
20245    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20246            String killReason) {
20247        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20248            return new PackageFreezer();
20249        } else {
20250            return freezePackage(packageName, userId, killReason);
20251        }
20252    }
20253
20254    /**
20255     * Class that freezes and kills the given package upon creation, and
20256     * unfreezes it upon closing. This is typically used when doing surgery on
20257     * app code/data to prevent the app from running while you're working.
20258     */
20259    private class PackageFreezer implements AutoCloseable {
20260        private final String mPackageName;
20261        private final PackageFreezer[] mChildren;
20262
20263        private final boolean mWeFroze;
20264
20265        private final AtomicBoolean mClosed = new AtomicBoolean();
20266        private final CloseGuard mCloseGuard = CloseGuard.get();
20267
20268        /**
20269         * Create and return a stub freezer that doesn't actually do anything,
20270         * typically used when someone requested
20271         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20272         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20273         */
20274        public PackageFreezer() {
20275            mPackageName = null;
20276            mChildren = null;
20277            mWeFroze = false;
20278            mCloseGuard.open("close");
20279        }
20280
20281        public PackageFreezer(String packageName, int userId, String killReason) {
20282            synchronized (mPackages) {
20283                mPackageName = packageName;
20284                mWeFroze = mFrozenPackages.add(mPackageName);
20285
20286                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20287                if (ps != null) {
20288                    killApplication(ps.name, ps.appId, userId, killReason);
20289                }
20290
20291                final PackageParser.Package p = mPackages.get(packageName);
20292                if (p != null && p.childPackages != null) {
20293                    final int N = p.childPackages.size();
20294                    mChildren = new PackageFreezer[N];
20295                    for (int i = 0; i < N; i++) {
20296                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20297                                userId, killReason);
20298                    }
20299                } else {
20300                    mChildren = null;
20301                }
20302            }
20303            mCloseGuard.open("close");
20304        }
20305
20306        @Override
20307        protected void finalize() throws Throwable {
20308            try {
20309                mCloseGuard.warnIfOpen();
20310                close();
20311            } finally {
20312                super.finalize();
20313            }
20314        }
20315
20316        @Override
20317        public void close() {
20318            mCloseGuard.close();
20319            if (mClosed.compareAndSet(false, true)) {
20320                synchronized (mPackages) {
20321                    if (mWeFroze) {
20322                        mFrozenPackages.remove(mPackageName);
20323                    }
20324
20325                    if (mChildren != null) {
20326                        for (PackageFreezer freezer : mChildren) {
20327                            freezer.close();
20328                        }
20329                    }
20330                }
20331            }
20332        }
20333    }
20334
20335    /**
20336     * Verify that given package is currently frozen.
20337     */
20338    private void checkPackageFrozen(String packageName) {
20339        synchronized (mPackages) {
20340            if (!mFrozenPackages.contains(packageName)) {
20341                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20342            }
20343        }
20344    }
20345
20346    @Override
20347    public int movePackage(final String packageName, final String volumeUuid) {
20348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20349
20350        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20351        final int moveId = mNextMoveId.getAndIncrement();
20352        mHandler.post(new Runnable() {
20353            @Override
20354            public void run() {
20355                try {
20356                    movePackageInternal(packageName, volumeUuid, moveId, user);
20357                } catch (PackageManagerException e) {
20358                    Slog.w(TAG, "Failed to move " + packageName, e);
20359                    mMoveCallbacks.notifyStatusChanged(moveId,
20360                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20361                }
20362            }
20363        });
20364        return moveId;
20365    }
20366
20367    private void movePackageInternal(final String packageName, final String volumeUuid,
20368            final int moveId, UserHandle user) throws PackageManagerException {
20369        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20370        final PackageManager pm = mContext.getPackageManager();
20371
20372        final boolean currentAsec;
20373        final String currentVolumeUuid;
20374        final File codeFile;
20375        final String installerPackageName;
20376        final String packageAbiOverride;
20377        final int appId;
20378        final String seinfo;
20379        final String label;
20380        final int targetSdkVersion;
20381        final PackageFreezer freezer;
20382        final int[] installedUserIds;
20383
20384        // reader
20385        synchronized (mPackages) {
20386            final PackageParser.Package pkg = mPackages.get(packageName);
20387            final PackageSetting ps = mSettings.mPackages.get(packageName);
20388            if (pkg == null || ps == null) {
20389                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20390            }
20391
20392            if (pkg.applicationInfo.isSystemApp()) {
20393                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20394                        "Cannot move system application");
20395            }
20396
20397            if (pkg.applicationInfo.isExternalAsec()) {
20398                currentAsec = true;
20399                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20400            } else if (pkg.applicationInfo.isForwardLocked()) {
20401                currentAsec = true;
20402                currentVolumeUuid = "forward_locked";
20403            } else {
20404                currentAsec = false;
20405                currentVolumeUuid = ps.volumeUuid;
20406
20407                final File probe = new File(pkg.codePath);
20408                final File probeOat = new File(probe, "oat");
20409                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20410                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20411                            "Move only supported for modern cluster style installs");
20412                }
20413            }
20414
20415            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20416                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20417                        "Package already moved to " + volumeUuid);
20418            }
20419            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20420                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20421                        "Device admin cannot be moved");
20422            }
20423
20424            if (mFrozenPackages.contains(packageName)) {
20425                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20426                        "Failed to move already frozen package");
20427            }
20428
20429            codeFile = new File(pkg.codePath);
20430            installerPackageName = ps.installerPackageName;
20431            packageAbiOverride = ps.cpuAbiOverrideString;
20432            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20433            seinfo = pkg.applicationInfo.seinfo;
20434            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20435            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20436            freezer = freezePackage(packageName, "movePackageInternal");
20437            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20438        }
20439
20440        final Bundle extras = new Bundle();
20441        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20442        extras.putString(Intent.EXTRA_TITLE, label);
20443        mMoveCallbacks.notifyCreated(moveId, extras);
20444
20445        int installFlags;
20446        final boolean moveCompleteApp;
20447        final File measurePath;
20448
20449        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20450            installFlags = INSTALL_INTERNAL;
20451            moveCompleteApp = !currentAsec;
20452            measurePath = Environment.getDataAppDirectory(volumeUuid);
20453        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20454            installFlags = INSTALL_EXTERNAL;
20455            moveCompleteApp = false;
20456            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20457        } else {
20458            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20459            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20460                    || !volume.isMountedWritable()) {
20461                freezer.close();
20462                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20463                        "Move location not mounted private volume");
20464            }
20465
20466            Preconditions.checkState(!currentAsec);
20467
20468            installFlags = INSTALL_INTERNAL;
20469            moveCompleteApp = true;
20470            measurePath = Environment.getDataAppDirectory(volumeUuid);
20471        }
20472
20473        final PackageStats stats = new PackageStats(null, -1);
20474        synchronized (mInstaller) {
20475            for (int userId : installedUserIds) {
20476                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20477                    freezer.close();
20478                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20479                            "Failed to measure package size");
20480                }
20481            }
20482        }
20483
20484        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20485                + stats.dataSize);
20486
20487        final long startFreeBytes = measurePath.getFreeSpace();
20488        final long sizeBytes;
20489        if (moveCompleteApp) {
20490            sizeBytes = stats.codeSize + stats.dataSize;
20491        } else {
20492            sizeBytes = stats.codeSize;
20493        }
20494
20495        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20496            freezer.close();
20497            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20498                    "Not enough free space to move");
20499        }
20500
20501        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20502
20503        final CountDownLatch installedLatch = new CountDownLatch(1);
20504        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20505            @Override
20506            public void onUserActionRequired(Intent intent) throws RemoteException {
20507                throw new IllegalStateException();
20508            }
20509
20510            @Override
20511            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20512                    Bundle extras) throws RemoteException {
20513                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20514                        + PackageManager.installStatusToString(returnCode, msg));
20515
20516                installedLatch.countDown();
20517                freezer.close();
20518
20519                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20520                switch (status) {
20521                    case PackageInstaller.STATUS_SUCCESS:
20522                        mMoveCallbacks.notifyStatusChanged(moveId,
20523                                PackageManager.MOVE_SUCCEEDED);
20524                        break;
20525                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20526                        mMoveCallbacks.notifyStatusChanged(moveId,
20527                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20528                        break;
20529                    default:
20530                        mMoveCallbacks.notifyStatusChanged(moveId,
20531                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20532                        break;
20533                }
20534            }
20535        };
20536
20537        final MoveInfo move;
20538        if (moveCompleteApp) {
20539            // Kick off a thread to report progress estimates
20540            new Thread() {
20541                @Override
20542                public void run() {
20543                    while (true) {
20544                        try {
20545                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20546                                break;
20547                            }
20548                        } catch (InterruptedException ignored) {
20549                        }
20550
20551                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20552                        final int progress = 10 + (int) MathUtils.constrain(
20553                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20554                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20555                    }
20556                }
20557            }.start();
20558
20559            final String dataAppName = codeFile.getName();
20560            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20561                    dataAppName, appId, seinfo, targetSdkVersion);
20562        } else {
20563            move = null;
20564        }
20565
20566        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20567
20568        final Message msg = mHandler.obtainMessage(INIT_COPY);
20569        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20570        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20571                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20572                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20573        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20574        msg.obj = params;
20575
20576        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20577                System.identityHashCode(msg.obj));
20578        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20579                System.identityHashCode(msg.obj));
20580
20581        mHandler.sendMessage(msg);
20582    }
20583
20584    @Override
20585    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20586        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20587
20588        final int realMoveId = mNextMoveId.getAndIncrement();
20589        final Bundle extras = new Bundle();
20590        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20591        mMoveCallbacks.notifyCreated(realMoveId, extras);
20592
20593        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20594            @Override
20595            public void onCreated(int moveId, Bundle extras) {
20596                // Ignored
20597            }
20598
20599            @Override
20600            public void onStatusChanged(int moveId, int status, long estMillis) {
20601                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20602            }
20603        };
20604
20605        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20606        storage.setPrimaryStorageUuid(volumeUuid, callback);
20607        return realMoveId;
20608    }
20609
20610    @Override
20611    public int getMoveStatus(int moveId) {
20612        mContext.enforceCallingOrSelfPermission(
20613                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20614        return mMoveCallbacks.mLastStatus.get(moveId);
20615    }
20616
20617    @Override
20618    public void registerMoveCallback(IPackageMoveObserver callback) {
20619        mContext.enforceCallingOrSelfPermission(
20620                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20621        mMoveCallbacks.register(callback);
20622    }
20623
20624    @Override
20625    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20626        mContext.enforceCallingOrSelfPermission(
20627                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20628        mMoveCallbacks.unregister(callback);
20629    }
20630
20631    @Override
20632    public boolean setInstallLocation(int loc) {
20633        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20634                null);
20635        if (getInstallLocation() == loc) {
20636            return true;
20637        }
20638        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20639                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20640            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20641                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20642            return true;
20643        }
20644        return false;
20645   }
20646
20647    @Override
20648    public int getInstallLocation() {
20649        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20650                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20651                PackageHelper.APP_INSTALL_AUTO);
20652    }
20653
20654    /** Called by UserManagerService */
20655    void cleanUpUser(UserManagerService userManager, int userHandle) {
20656        synchronized (mPackages) {
20657            mDirtyUsers.remove(userHandle);
20658            mUserNeedsBadging.delete(userHandle);
20659            mSettings.removeUserLPw(userHandle);
20660            mPendingBroadcasts.remove(userHandle);
20661            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20662            removeUnusedPackagesLPw(userManager, userHandle);
20663        }
20664    }
20665
20666    /**
20667     * We're removing userHandle and would like to remove any downloaded packages
20668     * that are no longer in use by any other user.
20669     * @param userHandle the user being removed
20670     */
20671    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20672        final boolean DEBUG_CLEAN_APKS = false;
20673        int [] users = userManager.getUserIds();
20674        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20675        while (psit.hasNext()) {
20676            PackageSetting ps = psit.next();
20677            if (ps.pkg == null) {
20678                continue;
20679            }
20680            final String packageName = ps.pkg.packageName;
20681            // Skip over if system app
20682            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20683                continue;
20684            }
20685            if (DEBUG_CLEAN_APKS) {
20686                Slog.i(TAG, "Checking package " + packageName);
20687            }
20688            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20689            if (keep) {
20690                if (DEBUG_CLEAN_APKS) {
20691                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20692                }
20693            } else {
20694                for (int i = 0; i < users.length; i++) {
20695                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20696                        keep = true;
20697                        if (DEBUG_CLEAN_APKS) {
20698                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20699                                    + users[i]);
20700                        }
20701                        break;
20702                    }
20703                }
20704            }
20705            if (!keep) {
20706                if (DEBUG_CLEAN_APKS) {
20707                    Slog.i(TAG, "  Removing package " + packageName);
20708                }
20709                mHandler.post(new Runnable() {
20710                    public void run() {
20711                        deletePackageX(packageName, userHandle, 0);
20712                    } //end run
20713                });
20714            }
20715        }
20716    }
20717
20718    /** Called by UserManagerService */
20719    void createNewUser(int userId, String[] disallowedPackages) {
20720        synchronized (mInstallLock) {
20721            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20722        }
20723        synchronized (mPackages) {
20724            scheduleWritePackageRestrictionsLocked(userId);
20725            scheduleWritePackageListLocked(userId);
20726            applyFactoryDefaultBrowserLPw(userId);
20727            primeDomainVerificationsLPw(userId);
20728        }
20729    }
20730
20731    void onNewUserCreated(final int userId) {
20732        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20733        // If permission review for legacy apps is required, we represent
20734        // dagerous permissions for such apps as always granted runtime
20735        // permissions to keep per user flag state whether review is needed.
20736        // Hence, if a new user is added we have to propagate dangerous
20737        // permission grants for these legacy apps.
20738        if (mPermissionReviewRequired) {
20739            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20740                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20741        }
20742    }
20743
20744    @Override
20745    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20746        mContext.enforceCallingOrSelfPermission(
20747                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20748                "Only package verification agents can read the verifier device identity");
20749
20750        synchronized (mPackages) {
20751            return mSettings.getVerifierDeviceIdentityLPw();
20752        }
20753    }
20754
20755    @Override
20756    public void setPermissionEnforced(String permission, boolean enforced) {
20757        // TODO: Now that we no longer change GID for storage, this should to away.
20758        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20759                "setPermissionEnforced");
20760        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20761            synchronized (mPackages) {
20762                if (mSettings.mReadExternalStorageEnforced == null
20763                        || mSettings.mReadExternalStorageEnforced != enforced) {
20764                    mSettings.mReadExternalStorageEnforced = enforced;
20765                    mSettings.writeLPr();
20766                }
20767            }
20768            // kill any non-foreground processes so we restart them and
20769            // grant/revoke the GID.
20770            final IActivityManager am = ActivityManagerNative.getDefault();
20771            if (am != null) {
20772                final long token = Binder.clearCallingIdentity();
20773                try {
20774                    am.killProcessesBelowForeground("setPermissionEnforcement");
20775                } catch (RemoteException e) {
20776                } finally {
20777                    Binder.restoreCallingIdentity(token);
20778                }
20779            }
20780        } else {
20781            throw new IllegalArgumentException("No selective enforcement for " + permission);
20782        }
20783    }
20784
20785    @Override
20786    @Deprecated
20787    public boolean isPermissionEnforced(String permission) {
20788        return true;
20789    }
20790
20791    @Override
20792    public boolean isStorageLow() {
20793        final long token = Binder.clearCallingIdentity();
20794        try {
20795            final DeviceStorageMonitorInternal
20796                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20797            if (dsm != null) {
20798                return dsm.isMemoryLow();
20799            } else {
20800                return false;
20801            }
20802        } finally {
20803            Binder.restoreCallingIdentity(token);
20804        }
20805    }
20806
20807    @Override
20808    public IPackageInstaller getPackageInstaller() {
20809        return mInstallerService;
20810    }
20811
20812    private boolean userNeedsBadging(int userId) {
20813        int index = mUserNeedsBadging.indexOfKey(userId);
20814        if (index < 0) {
20815            final UserInfo userInfo;
20816            final long token = Binder.clearCallingIdentity();
20817            try {
20818                userInfo = sUserManager.getUserInfo(userId);
20819            } finally {
20820                Binder.restoreCallingIdentity(token);
20821            }
20822            final boolean b;
20823            if (userInfo != null && userInfo.isManagedProfile()) {
20824                b = true;
20825            } else {
20826                b = false;
20827            }
20828            mUserNeedsBadging.put(userId, b);
20829            return b;
20830        }
20831        return mUserNeedsBadging.valueAt(index);
20832    }
20833
20834    @Override
20835    public KeySet getKeySetByAlias(String packageName, String alias) {
20836        if (packageName == null || alias == null) {
20837            return null;
20838        }
20839        synchronized(mPackages) {
20840            final PackageParser.Package pkg = mPackages.get(packageName);
20841            if (pkg == null) {
20842                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20843                throw new IllegalArgumentException("Unknown package: " + packageName);
20844            }
20845            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20846            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20847        }
20848    }
20849
20850    @Override
20851    public KeySet getSigningKeySet(String packageName) {
20852        if (packageName == null) {
20853            return null;
20854        }
20855        synchronized(mPackages) {
20856            final PackageParser.Package pkg = mPackages.get(packageName);
20857            if (pkg == null) {
20858                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20859                throw new IllegalArgumentException("Unknown package: " + packageName);
20860            }
20861            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20862                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20863                throw new SecurityException("May not access signing KeySet of other apps.");
20864            }
20865            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20866            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20867        }
20868    }
20869
20870    @Override
20871    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20872        if (packageName == null || ks == null) {
20873            return false;
20874        }
20875        synchronized(mPackages) {
20876            final PackageParser.Package pkg = mPackages.get(packageName);
20877            if (pkg == null) {
20878                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20879                throw new IllegalArgumentException("Unknown package: " + packageName);
20880            }
20881            IBinder ksh = ks.getToken();
20882            if (ksh instanceof KeySetHandle) {
20883                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20884                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20885            }
20886            return false;
20887        }
20888    }
20889
20890    @Override
20891    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20892        if (packageName == null || ks == null) {
20893            return false;
20894        }
20895        synchronized(mPackages) {
20896            final PackageParser.Package pkg = mPackages.get(packageName);
20897            if (pkg == null) {
20898                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20899                throw new IllegalArgumentException("Unknown package: " + packageName);
20900            }
20901            IBinder ksh = ks.getToken();
20902            if (ksh instanceof KeySetHandle) {
20903                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20904                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20905            }
20906            return false;
20907        }
20908    }
20909
20910    private void deletePackageIfUnusedLPr(final String packageName) {
20911        PackageSetting ps = mSettings.mPackages.get(packageName);
20912        if (ps == null) {
20913            return;
20914        }
20915        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20916            // TODO Implement atomic delete if package is unused
20917            // It is currently possible that the package will be deleted even if it is installed
20918            // after this method returns.
20919            mHandler.post(new Runnable() {
20920                public void run() {
20921                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20922                }
20923            });
20924        }
20925    }
20926
20927    /**
20928     * Check and throw if the given before/after packages would be considered a
20929     * downgrade.
20930     */
20931    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20932            throws PackageManagerException {
20933        if (after.versionCode < before.mVersionCode) {
20934            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20935                    "Update version code " + after.versionCode + " is older than current "
20936                    + before.mVersionCode);
20937        } else if (after.versionCode == before.mVersionCode) {
20938            if (after.baseRevisionCode < before.baseRevisionCode) {
20939                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20940                        "Update base revision code " + after.baseRevisionCode
20941                        + " is older than current " + before.baseRevisionCode);
20942            }
20943
20944            if (!ArrayUtils.isEmpty(after.splitNames)) {
20945                for (int i = 0; i < after.splitNames.length; i++) {
20946                    final String splitName = after.splitNames[i];
20947                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20948                    if (j != -1) {
20949                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20950                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20951                                    "Update split " + splitName + " revision code "
20952                                    + after.splitRevisionCodes[i] + " is older than current "
20953                                    + before.splitRevisionCodes[j]);
20954                        }
20955                    }
20956                }
20957            }
20958        }
20959    }
20960
20961    private static class MoveCallbacks extends Handler {
20962        private static final int MSG_CREATED = 1;
20963        private static final int MSG_STATUS_CHANGED = 2;
20964
20965        private final RemoteCallbackList<IPackageMoveObserver>
20966                mCallbacks = new RemoteCallbackList<>();
20967
20968        private final SparseIntArray mLastStatus = new SparseIntArray();
20969
20970        public MoveCallbacks(Looper looper) {
20971            super(looper);
20972        }
20973
20974        public void register(IPackageMoveObserver callback) {
20975            mCallbacks.register(callback);
20976        }
20977
20978        public void unregister(IPackageMoveObserver callback) {
20979            mCallbacks.unregister(callback);
20980        }
20981
20982        @Override
20983        public void handleMessage(Message msg) {
20984            final SomeArgs args = (SomeArgs) msg.obj;
20985            final int n = mCallbacks.beginBroadcast();
20986            for (int i = 0; i < n; i++) {
20987                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20988                try {
20989                    invokeCallback(callback, msg.what, args);
20990                } catch (RemoteException ignored) {
20991                }
20992            }
20993            mCallbacks.finishBroadcast();
20994            args.recycle();
20995        }
20996
20997        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20998                throws RemoteException {
20999            switch (what) {
21000                case MSG_CREATED: {
21001                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21002                    break;
21003                }
21004                case MSG_STATUS_CHANGED: {
21005                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21006                    break;
21007                }
21008            }
21009        }
21010
21011        private void notifyCreated(int moveId, Bundle extras) {
21012            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21013
21014            final SomeArgs args = SomeArgs.obtain();
21015            args.argi1 = moveId;
21016            args.arg2 = extras;
21017            obtainMessage(MSG_CREATED, args).sendToTarget();
21018        }
21019
21020        private void notifyStatusChanged(int moveId, int status) {
21021            notifyStatusChanged(moveId, status, -1);
21022        }
21023
21024        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21025            Slog.v(TAG, "Move " + moveId + " status " + status);
21026
21027            final SomeArgs args = SomeArgs.obtain();
21028            args.argi1 = moveId;
21029            args.argi2 = status;
21030            args.arg3 = estMillis;
21031            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21032
21033            synchronized (mLastStatus) {
21034                mLastStatus.put(moveId, status);
21035            }
21036        }
21037    }
21038
21039    private final static class OnPermissionChangeListeners extends Handler {
21040        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21041
21042        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21043                new RemoteCallbackList<>();
21044
21045        public OnPermissionChangeListeners(Looper looper) {
21046            super(looper);
21047        }
21048
21049        @Override
21050        public void handleMessage(Message msg) {
21051            switch (msg.what) {
21052                case MSG_ON_PERMISSIONS_CHANGED: {
21053                    final int uid = msg.arg1;
21054                    handleOnPermissionsChanged(uid);
21055                } break;
21056            }
21057        }
21058
21059        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21060            mPermissionListeners.register(listener);
21061
21062        }
21063
21064        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21065            mPermissionListeners.unregister(listener);
21066        }
21067
21068        public void onPermissionsChanged(int uid) {
21069            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21070                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21071            }
21072        }
21073
21074        private void handleOnPermissionsChanged(int uid) {
21075            final int count = mPermissionListeners.beginBroadcast();
21076            try {
21077                for (int i = 0; i < count; i++) {
21078                    IOnPermissionsChangeListener callback = mPermissionListeners
21079                            .getBroadcastItem(i);
21080                    try {
21081                        callback.onPermissionsChanged(uid);
21082                    } catch (RemoteException e) {
21083                        Log.e(TAG, "Permission listener is dead", e);
21084                    }
21085                }
21086            } finally {
21087                mPermissionListeners.finishBroadcast();
21088            }
21089        }
21090    }
21091
21092    private class PackageManagerInternalImpl extends PackageManagerInternal {
21093        @Override
21094        public void setLocationPackagesProvider(PackagesProvider provider) {
21095            synchronized (mPackages) {
21096                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21097            }
21098        }
21099
21100        @Override
21101        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21102            synchronized (mPackages) {
21103                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21104            }
21105        }
21106
21107        @Override
21108        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21109            synchronized (mPackages) {
21110                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21111            }
21112        }
21113
21114        @Override
21115        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21116            synchronized (mPackages) {
21117                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21118            }
21119        }
21120
21121        @Override
21122        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21123            synchronized (mPackages) {
21124                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21125            }
21126        }
21127
21128        @Override
21129        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21130            synchronized (mPackages) {
21131                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21132            }
21133        }
21134
21135        @Override
21136        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21137            synchronized (mPackages) {
21138                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21139                        packageName, userId);
21140            }
21141        }
21142
21143        @Override
21144        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21145            synchronized (mPackages) {
21146                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21147                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21148                        packageName, userId);
21149            }
21150        }
21151
21152        @Override
21153        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21154            synchronized (mPackages) {
21155                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21156                        packageName, userId);
21157            }
21158        }
21159
21160        @Override
21161        public void setKeepUninstalledPackages(final List<String> packageList) {
21162            Preconditions.checkNotNull(packageList);
21163            List<String> removedFromList = null;
21164            synchronized (mPackages) {
21165                if (mKeepUninstalledPackages != null) {
21166                    final int packagesCount = mKeepUninstalledPackages.size();
21167                    for (int i = 0; i < packagesCount; i++) {
21168                        String oldPackage = mKeepUninstalledPackages.get(i);
21169                        if (packageList != null && packageList.contains(oldPackage)) {
21170                            continue;
21171                        }
21172                        if (removedFromList == null) {
21173                            removedFromList = new ArrayList<>();
21174                        }
21175                        removedFromList.add(oldPackage);
21176                    }
21177                }
21178                mKeepUninstalledPackages = new ArrayList<>(packageList);
21179                if (removedFromList != null) {
21180                    final int removedCount = removedFromList.size();
21181                    for (int i = 0; i < removedCount; i++) {
21182                        deletePackageIfUnusedLPr(removedFromList.get(i));
21183                    }
21184                }
21185            }
21186        }
21187
21188        @Override
21189        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21190            synchronized (mPackages) {
21191                // If we do not support permission review, done.
21192                if (!mPermissionReviewRequired) {
21193                    return false;
21194                }
21195
21196                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21197                if (packageSetting == null) {
21198                    return false;
21199                }
21200
21201                // Permission review applies only to apps not supporting the new permission model.
21202                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21203                    return false;
21204                }
21205
21206                // Legacy apps have the permission and get user consent on launch.
21207                PermissionsState permissionsState = packageSetting.getPermissionsState();
21208                return permissionsState.isPermissionReviewRequired(userId);
21209            }
21210        }
21211
21212        @Override
21213        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21214            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21215        }
21216
21217        @Override
21218        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21219                int userId) {
21220            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21221        }
21222
21223        @Override
21224        public void setDeviceAndProfileOwnerPackages(
21225                int deviceOwnerUserId, String deviceOwnerPackage,
21226                SparseArray<String> profileOwnerPackages) {
21227            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21228                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21229        }
21230
21231        @Override
21232        public boolean isPackageDataProtected(int userId, String packageName) {
21233            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21234        }
21235
21236        @Override
21237        public boolean wasPackageEverLaunched(String packageName, int userId) {
21238            synchronized (mPackages) {
21239                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21240            }
21241        }
21242
21243        @Override
21244        public void grantRuntimePermission(String packageName, String name, int userId,
21245                boolean overridePolicy) {
21246            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21247                    overridePolicy);
21248        }
21249
21250        @Override
21251        public void revokeRuntimePermission(String packageName, String name, int userId,
21252                boolean overridePolicy) {
21253            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21254                    overridePolicy);
21255        }
21256    }
21257
21258    @Override
21259    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21260        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21261        synchronized (mPackages) {
21262            final long identity = Binder.clearCallingIdentity();
21263            try {
21264                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21265                        packageNames, userId);
21266            } finally {
21267                Binder.restoreCallingIdentity(identity);
21268            }
21269        }
21270    }
21271
21272    private static void enforceSystemOrPhoneCaller(String tag) {
21273        int callingUid = Binder.getCallingUid();
21274        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21275            throw new SecurityException(
21276                    "Cannot call " + tag + " from UID " + callingUid);
21277        }
21278    }
21279
21280    boolean isHistoricalPackageUsageAvailable() {
21281        return mPackageUsage.isHistoricalPackageUsageAvailable();
21282    }
21283
21284    /**
21285     * Return a <b>copy</b> of the collection of packages known to the package manager.
21286     * @return A copy of the values of mPackages.
21287     */
21288    Collection<PackageParser.Package> getPackages() {
21289        synchronized (mPackages) {
21290            return new ArrayList<>(mPackages.values());
21291        }
21292    }
21293
21294    /**
21295     * Logs process start information (including base APK hash) to the security log.
21296     * @hide
21297     */
21298    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21299            String apkFile, int pid) {
21300        if (!SecurityLog.isLoggingEnabled()) {
21301            return;
21302        }
21303        Bundle data = new Bundle();
21304        data.putLong("startTimestamp", System.currentTimeMillis());
21305        data.putString("processName", processName);
21306        data.putInt("uid", uid);
21307        data.putString("seinfo", seinfo);
21308        data.putString("apkFile", apkFile);
21309        data.putInt("pid", pid);
21310        Message msg = mProcessLoggingHandler.obtainMessage(
21311                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21312        msg.setData(data);
21313        mProcessLoggingHandler.sendMessage(msg);
21314    }
21315
21316    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21317        return mCompilerStats.getPackageStats(pkgName);
21318    }
21319
21320    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21321        return getOrCreateCompilerPackageStats(pkg.packageName);
21322    }
21323
21324    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21325        return mCompilerStats.getOrCreatePackageStats(pkgName);
21326    }
21327
21328    public void deleteCompilerPackageStats(String pkgName) {
21329        mCompilerStats.deletePackageStats(pkgName);
21330    }
21331}
21332