PackageManagerService.java revision c19706a937abc5d025a59b354b3a0d89e7d62805
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_SKU_PROPERTY is set, search for runtime resource overlay APKs in
470     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in
471     * VENDOR_OVERLAY_DIR.
472     */
473    private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku";
474
475    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
476    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
477
478    /** Permission grant: not grant the permission. */
479    private static final int GRANT_DENIED = 1;
480
481    /** Permission grant: grant the permission as an install permission. */
482    private static final int GRANT_INSTALL = 2;
483
484    /** Permission grant: grant the permission as a runtime one. */
485    private static final int GRANT_RUNTIME = 3;
486
487    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
488    private static final int GRANT_UPGRADE = 4;
489
490    /** Canonical intent used to identify what counts as a "web browser" app */
491    private static final Intent sBrowserIntent;
492    static {
493        sBrowserIntent = new Intent();
494        sBrowserIntent.setAction(Intent.ACTION_VIEW);
495        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
496        sBrowserIntent.setData(Uri.parse("http:"));
497    }
498
499    /**
500     * The set of all protected actions [i.e. those actions for which a high priority
501     * intent filter is disallowed].
502     */
503    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
504    static {
505        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
506        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
507        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
508        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
509    }
510
511    // Compilation reasons.
512    public static final int REASON_FIRST_BOOT = 0;
513    public static final int REASON_BOOT = 1;
514    public static final int REASON_INSTALL = 2;
515    public static final int REASON_BACKGROUND_DEXOPT = 3;
516    public static final int REASON_AB_OTA = 4;
517    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
518    public static final int REASON_SHARED_APK = 6;
519    public static final int REASON_FORCED_DEXOPT = 7;
520    public static final int REASON_CORE_APP = 8;
521
522    public static final int REASON_LAST = REASON_CORE_APP;
523
524    /** Special library name that skips shared libraries check during compilation. */
525    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
526
527    final ServiceThread mHandlerThread;
528
529    final PackageHandler mHandler;
530
531    private final ProcessLoggingHandler mProcessLoggingHandler;
532
533    /**
534     * Messages for {@link #mHandler} that need to wait for system ready before
535     * being dispatched.
536     */
537    private ArrayList<Message> mPostSystemReadyMessages;
538
539    final int mSdkVersion = Build.VERSION.SDK_INT;
540
541    final Context mContext;
542    final boolean mFactoryTest;
543    final boolean mOnlyCore;
544    final DisplayMetrics mMetrics;
545    final int mDefParseFlags;
546    final String[] mSeparateProcesses;
547    final boolean mIsUpgrade;
548    final boolean mIsPreNUpgrade;
549    final boolean mIsPreNMR1Upgrade;
550
551    @GuardedBy("mPackages")
552    private boolean mDexOptDialogShown;
553
554    /** The location for ASEC container files on internal storage. */
555    final String mAsecInternalPath;
556
557    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
558    // LOCK HELD.  Can be called with mInstallLock held.
559    @GuardedBy("mInstallLock")
560    final Installer mInstaller;
561
562    /** Directory where installed third-party apps stored */
563    final File mAppInstallDir;
564    final File mEphemeralInstallDir;
565
566    /**
567     * Directory to which applications installed internally have their
568     * 32 bit native libraries copied.
569     */
570    private File mAppLib32InstallDir;
571
572    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
573    // apps.
574    final File mDrmAppPrivateInstallDir;
575
576    // ----------------------------------------------------------------
577
578    // Lock for state used when installing and doing other long running
579    // operations.  Methods that must be called with this lock held have
580    // the suffix "LI".
581    final Object mInstallLock = new Object();
582
583    // ----------------------------------------------------------------
584
585    // Keys are String (package name), values are Package.  This also serves
586    // as the lock for the global state.  Methods that must be called with
587    // this lock held have the prefix "LP".
588    @GuardedBy("mPackages")
589    final ArrayMap<String, PackageParser.Package> mPackages =
590            new ArrayMap<String, PackageParser.Package>();
591
592    final ArrayMap<String, Set<String>> mKnownCodebase =
593            new ArrayMap<String, Set<String>>();
594
595    // Tracks available target package names -> overlay package paths.
596    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
597        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
598
599    /**
600     * Tracks new system packages [received in an OTA] that we expect to
601     * find updated user-installed versions. Keys are package name, values
602     * are package location.
603     */
604    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
605    /**
606     * Tracks high priority intent filters for protected actions. During boot, certain
607     * filter actions are protected and should never be allowed to have a high priority
608     * intent filter for them. However, there is one, and only one exception -- the
609     * setup wizard. It must be able to define a high priority intent filter for these
610     * actions to ensure there are no escapes from the wizard. We need to delay processing
611     * of these during boot as we need to look at all of the system packages in order
612     * to know which component is the setup wizard.
613     */
614    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
615    /**
616     * Whether or not processing protected filters should be deferred.
617     */
618    private boolean mDeferProtectedFilters = true;
619
620    /**
621     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
622     */
623    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
624    /**
625     * Whether or not system app permissions should be promoted from install to runtime.
626     */
627    boolean mPromoteSystemApps;
628
629    @GuardedBy("mPackages")
630    final Settings mSettings;
631
632    /**
633     * Set of package names that are currently "frozen", which means active
634     * surgery is being done on the code/data for that package. The platform
635     * will refuse to launch frozen packages to avoid race conditions.
636     *
637     * @see PackageFreezer
638     */
639    @GuardedBy("mPackages")
640    final ArraySet<String> mFrozenPackages = new ArraySet<>();
641
642    final ProtectedPackages mProtectedPackages;
643
644    boolean mFirstBoot;
645
646    // System configuration read by SystemConfig.
647    final int[] mGlobalGids;
648    final SparseArray<ArraySet<String>> mSystemPermissions;
649    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
650
651    // If mac_permissions.xml was found for seinfo labeling.
652    boolean mFoundPolicyFile;
653
654    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
655
656    public static final class SharedLibraryEntry {
657        public final String path;
658        public final String apk;
659
660        SharedLibraryEntry(String _path, String _apk) {
661            path = _path;
662            apk = _apk;
663        }
664    }
665
666    // Currently known shared libraries.
667    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
668            new ArrayMap<String, SharedLibraryEntry>();
669
670    // All available activities, for your resolving pleasure.
671    final ActivityIntentResolver mActivities =
672            new ActivityIntentResolver();
673
674    // All available receivers, for your resolving pleasure.
675    final ActivityIntentResolver mReceivers =
676            new ActivityIntentResolver();
677
678    // All available services, for your resolving pleasure.
679    final ServiceIntentResolver mServices = new ServiceIntentResolver();
680
681    // All available providers, for your resolving pleasure.
682    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
683
684    // Mapping from provider base names (first directory in content URI codePath)
685    // to the provider information.
686    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
687            new ArrayMap<String, PackageParser.Provider>();
688
689    // Mapping from instrumentation class names to info about them.
690    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
691            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
692
693    // Mapping from permission names to info about them.
694    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
695            new ArrayMap<String, PackageParser.PermissionGroup>();
696
697    // Packages whose data we have transfered into another package, thus
698    // should no longer exist.
699    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
700
701    // Broadcast actions that are only available to the system.
702    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
703
704    /** List of packages waiting for verification. */
705    final SparseArray<PackageVerificationState> mPendingVerification
706            = new SparseArray<PackageVerificationState>();
707
708    /** Set of packages associated with each app op permission. */
709    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
710
711    final PackageInstallerService mInstallerService;
712
713    private final PackageDexOptimizer mPackageDexOptimizer;
714
715    private AtomicInteger mNextMoveId = new AtomicInteger();
716    private final MoveCallbacks mMoveCallbacks;
717
718    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
719
720    // Cache of users who need badging.
721    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
722
723    /** Token for keys in mPendingVerification. */
724    private int mPendingVerificationToken = 0;
725
726    volatile boolean mSystemReady;
727    volatile boolean mSafeMode;
728    volatile boolean mHasSystemUidErrors;
729
730    ApplicationInfo mAndroidApplication;
731    final ActivityInfo mResolveActivity = new ActivityInfo();
732    final ResolveInfo mResolveInfo = new ResolveInfo();
733    ComponentName mResolveComponentName;
734    PackageParser.Package mPlatformPackage;
735    ComponentName mCustomResolverComponentName;
736
737    boolean mResolverReplaced = false;
738
739    private final @Nullable ComponentName mIntentFilterVerifierComponent;
740    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
741
742    private int mIntentFilterVerificationToken = 0;
743
744    /** Component that knows whether or not an ephemeral application exists */
745    final ComponentName mEphemeralResolverComponent;
746    /** The service connection to the ephemeral resolver */
747    final EphemeralResolverConnection mEphemeralResolverConnection;
748
749    /** Component used to install ephemeral applications */
750    final ComponentName mEphemeralInstallerComponent;
751    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
752    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
753
754    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
755            = new SparseArray<IntentFilterVerificationState>();
756
757    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
758
759    // List of packages names to keep cached, even if they are uninstalled for all users
760    private List<String> mKeepUninstalledPackages;
761
762    private UserManagerInternal mUserManagerInternal;
763
764    private static class IFVerificationParams {
765        PackageParser.Package pkg;
766        boolean replacing;
767        int userId;
768        int verifierUid;
769
770        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
771                int _userId, int _verifierUid) {
772            pkg = _pkg;
773            replacing = _replacing;
774            userId = _userId;
775            replacing = _replacing;
776            verifierUid = _verifierUid;
777        }
778    }
779
780    private interface IntentFilterVerifier<T extends IntentFilter> {
781        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
782                                               T filter, String packageName);
783        void startVerifications(int userId);
784        void receiveVerificationResponse(int verificationId);
785    }
786
787    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
788        private Context mContext;
789        private ComponentName mIntentFilterVerifierComponent;
790        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
791
792        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
793            mContext = context;
794            mIntentFilterVerifierComponent = verifierComponent;
795        }
796
797        private String getDefaultScheme() {
798            return IntentFilter.SCHEME_HTTPS;
799        }
800
801        @Override
802        public void startVerifications(int userId) {
803            // Launch verifications requests
804            int count = mCurrentIntentFilterVerifications.size();
805            for (int n=0; n<count; n++) {
806                int verificationId = mCurrentIntentFilterVerifications.get(n);
807                final IntentFilterVerificationState ivs =
808                        mIntentFilterVerificationStates.get(verificationId);
809
810                String packageName = ivs.getPackageName();
811
812                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
813                final int filterCount = filters.size();
814                ArraySet<String> domainsSet = new ArraySet<>();
815                for (int m=0; m<filterCount; m++) {
816                    PackageParser.ActivityIntentInfo filter = filters.get(m);
817                    domainsSet.addAll(filter.getHostsList());
818                }
819                synchronized (mPackages) {
820                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
821                            packageName, domainsSet) != null) {
822                        scheduleWriteSettingsLocked();
823                    }
824                }
825                sendVerificationRequest(userId, verificationId, ivs);
826            }
827            mCurrentIntentFilterVerifications.clear();
828        }
829
830        private void sendVerificationRequest(int userId, int verificationId,
831                IntentFilterVerificationState ivs) {
832
833            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
834            verificationIntent.putExtra(
835                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
836                    verificationId);
837            verificationIntent.putExtra(
838                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
839                    getDefaultScheme());
840            verificationIntent.putExtra(
841                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
842                    ivs.getHostsString());
843            verificationIntent.putExtra(
844                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
845                    ivs.getPackageName());
846            verificationIntent.setComponent(mIntentFilterVerifierComponent);
847            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
848
849            UserHandle user = new UserHandle(userId);
850            mContext.sendBroadcastAsUser(verificationIntent, user);
851            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
852                    "Sending IntentFilter verification broadcast");
853        }
854
855        public void receiveVerificationResponse(int verificationId) {
856            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
857
858            final boolean verified = ivs.isVerified();
859
860            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
861            final int count = filters.size();
862            if (DEBUG_DOMAIN_VERIFICATION) {
863                Slog.i(TAG, "Received verification response " + verificationId
864                        + " for " + count + " filters, verified=" + verified);
865            }
866            for (int n=0; n<count; n++) {
867                PackageParser.ActivityIntentInfo filter = filters.get(n);
868                filter.setVerified(verified);
869
870                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
871                        + " verified with result:" + verified + " and hosts:"
872                        + ivs.getHostsString());
873            }
874
875            mIntentFilterVerificationStates.remove(verificationId);
876
877            final String packageName = ivs.getPackageName();
878            IntentFilterVerificationInfo ivi = null;
879
880            synchronized (mPackages) {
881                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
882            }
883            if (ivi == null) {
884                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
885                        + verificationId + " packageName:" + packageName);
886                return;
887            }
888            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
889                    "Updating IntentFilterVerificationInfo for package " + packageName
890                            +" verificationId:" + verificationId);
891
892            synchronized (mPackages) {
893                if (verified) {
894                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
895                } else {
896                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
897                }
898                scheduleWriteSettingsLocked();
899
900                final int userId = ivs.getUserId();
901                if (userId != UserHandle.USER_ALL) {
902                    final int userStatus =
903                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
904
905                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
906                    boolean needUpdate = false;
907
908                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
909                    // already been set by the User thru the Disambiguation dialog
910                    switch (userStatus) {
911                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
912                            if (verified) {
913                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
914                            } else {
915                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
916                            }
917                            needUpdate = true;
918                            break;
919
920                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
921                            if (verified) {
922                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
923                                needUpdate = true;
924                            }
925                            break;
926
927                        default:
928                            // Nothing to do
929                    }
930
931                    if (needUpdate) {
932                        mSettings.updateIntentFilterVerificationStatusLPw(
933                                packageName, updatedStatus, userId);
934                        scheduleWritePackageRestrictionsLocked(userId);
935                    }
936                }
937            }
938        }
939
940        @Override
941        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
942                    ActivityIntentInfo filter, String packageName) {
943            if (!hasValidDomains(filter)) {
944                return false;
945            }
946            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
947            if (ivs == null) {
948                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
949                        packageName);
950            }
951            if (DEBUG_DOMAIN_VERIFICATION) {
952                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
953            }
954            ivs.addFilter(filter);
955            return true;
956        }
957
958        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
959                int userId, int verificationId, String packageName) {
960            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
961                    verifierUid, userId, packageName);
962            ivs.setPendingState();
963            synchronized (mPackages) {
964                mIntentFilterVerificationStates.append(verificationId, ivs);
965                mCurrentIntentFilterVerifications.add(verificationId);
966            }
967            return ivs;
968        }
969    }
970
971    private static boolean hasValidDomains(ActivityIntentInfo filter) {
972        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
973                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
974                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
975    }
976
977    // Set of pending broadcasts for aggregating enable/disable of components.
978    static class PendingPackageBroadcasts {
979        // for each user id, a map of <package name -> components within that package>
980        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
981
982        public PendingPackageBroadcasts() {
983            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
984        }
985
986        public ArrayList<String> get(int userId, String packageName) {
987            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
988            return packages.get(packageName);
989        }
990
991        public void put(int userId, String packageName, ArrayList<String> components) {
992            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
993            packages.put(packageName, components);
994        }
995
996        public void remove(int userId, String packageName) {
997            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
998            if (packages != null) {
999                packages.remove(packageName);
1000            }
1001        }
1002
1003        public void remove(int userId) {
1004            mUidMap.remove(userId);
1005        }
1006
1007        public int userIdCount() {
1008            return mUidMap.size();
1009        }
1010
1011        public int userIdAt(int n) {
1012            return mUidMap.keyAt(n);
1013        }
1014
1015        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1016            return mUidMap.get(userId);
1017        }
1018
1019        public int size() {
1020            // total number of pending broadcast entries across all userIds
1021            int num = 0;
1022            for (int i = 0; i< mUidMap.size(); i++) {
1023                num += mUidMap.valueAt(i).size();
1024            }
1025            return num;
1026        }
1027
1028        public void clear() {
1029            mUidMap.clear();
1030        }
1031
1032        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1033            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1034            if (map == null) {
1035                map = new ArrayMap<String, ArrayList<String>>();
1036                mUidMap.put(userId, map);
1037            }
1038            return map;
1039        }
1040    }
1041    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1042
1043    // Service Connection to remote media container service to copy
1044    // package uri's from external media onto secure containers
1045    // or internal storage.
1046    private IMediaContainerService mContainerService = null;
1047
1048    static final int SEND_PENDING_BROADCAST = 1;
1049    static final int MCS_BOUND = 3;
1050    static final int END_COPY = 4;
1051    static final int INIT_COPY = 5;
1052    static final int MCS_UNBIND = 6;
1053    static final int START_CLEANING_PACKAGE = 7;
1054    static final int FIND_INSTALL_LOC = 8;
1055    static final int POST_INSTALL = 9;
1056    static final int MCS_RECONNECT = 10;
1057    static final int MCS_GIVE_UP = 11;
1058    static final int UPDATED_MEDIA_STATUS = 12;
1059    static final int WRITE_SETTINGS = 13;
1060    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1061    static final int PACKAGE_VERIFIED = 15;
1062    static final int CHECK_PENDING_VERIFICATION = 16;
1063    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1064    static final int INTENT_FILTER_VERIFIED = 18;
1065    static final int WRITE_PACKAGE_LIST = 19;
1066
1067    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1068
1069    // Delay time in millisecs
1070    static final int BROADCAST_DELAY = 10 * 1000;
1071
1072    static UserManagerService sUserManager;
1073
1074    // Stores a list of users whose package restrictions file needs to be updated
1075    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1076
1077    final private DefaultContainerConnection mDefContainerConn =
1078            new DefaultContainerConnection();
1079    class DefaultContainerConnection implements ServiceConnection {
1080        public void onServiceConnected(ComponentName name, IBinder service) {
1081            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1082            IMediaContainerService imcs =
1083                IMediaContainerService.Stub.asInterface(service);
1084            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1085        }
1086
1087        public void onServiceDisconnected(ComponentName name) {
1088            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1089        }
1090    }
1091
1092    // Recordkeeping of restore-after-install operations that are currently in flight
1093    // between the Package Manager and the Backup Manager
1094    static class PostInstallData {
1095        public InstallArgs args;
1096        public PackageInstalledInfo res;
1097
1098        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1099            args = _a;
1100            res = _r;
1101        }
1102    }
1103
1104    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1105    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1106
1107    // XML tags for backup/restore of various bits of state
1108    private static final String TAG_PREFERRED_BACKUP = "pa";
1109    private static final String TAG_DEFAULT_APPS = "da";
1110    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1111
1112    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1113    private static final String TAG_ALL_GRANTS = "rt-grants";
1114    private static final String TAG_GRANT = "grant";
1115    private static final String ATTR_PACKAGE_NAME = "pkg";
1116
1117    private static final String TAG_PERMISSION = "perm";
1118    private static final String ATTR_PERMISSION_NAME = "name";
1119    private static final String ATTR_IS_GRANTED = "g";
1120    private static final String ATTR_USER_SET = "set";
1121    private static final String ATTR_USER_FIXED = "fixed";
1122    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1123
1124    // System/policy permission grants are not backed up
1125    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1126            FLAG_PERMISSION_POLICY_FIXED
1127            | FLAG_PERMISSION_SYSTEM_FIXED
1128            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1129
1130    // And we back up these user-adjusted states
1131    private static final int USER_RUNTIME_GRANT_MASK =
1132            FLAG_PERMISSION_USER_SET
1133            | FLAG_PERMISSION_USER_FIXED
1134            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1135
1136    final @Nullable String mRequiredVerifierPackage;
1137    final @NonNull String mRequiredInstallerPackage;
1138    final @NonNull String mRequiredUninstallerPackage;
1139    final @Nullable String mSetupWizardPackage;
1140    final @Nullable String mStorageManagerPackage;
1141    final @NonNull String mServicesSystemSharedLibraryPackageName;
1142    final @NonNull String mSharedSystemSharedLibraryPackageName;
1143
1144    final boolean mPermissionReviewRequired;
1145
1146    private final PackageUsage mPackageUsage = new PackageUsage();
1147    private final CompilerStats mCompilerStats = new CompilerStats();
1148
1149    class PackageHandler extends Handler {
1150        private boolean mBound = false;
1151        final ArrayList<HandlerParams> mPendingInstalls =
1152            new ArrayList<HandlerParams>();
1153
1154        private boolean connectToService() {
1155            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1156                    " DefaultContainerService");
1157            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1158            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1159            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1160                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1161                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1162                mBound = true;
1163                return true;
1164            }
1165            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1166            return false;
1167        }
1168
1169        private void disconnectService() {
1170            mContainerService = null;
1171            mBound = false;
1172            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1173            mContext.unbindService(mDefContainerConn);
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175        }
1176
1177        PackageHandler(Looper looper) {
1178            super(looper);
1179        }
1180
1181        public void handleMessage(Message msg) {
1182            try {
1183                doHandleMessage(msg);
1184            } finally {
1185                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186            }
1187        }
1188
1189        void doHandleMessage(Message msg) {
1190            switch (msg.what) {
1191                case INIT_COPY: {
1192                    HandlerParams params = (HandlerParams) msg.obj;
1193                    int idx = mPendingInstalls.size();
1194                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1195                    // If a bind was already initiated we dont really
1196                    // need to do anything. The pending install
1197                    // will be processed later on.
1198                    if (!mBound) {
1199                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1200                                System.identityHashCode(mHandler));
1201                        // If this is the only one pending we might
1202                        // have to bind to the service again.
1203                        if (!connectToService()) {
1204                            Slog.e(TAG, "Failed to bind to media container service");
1205                            params.serviceError();
1206                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                    System.identityHashCode(mHandler));
1208                            if (params.traceMethod != null) {
1209                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1210                                        params.traceCookie);
1211                            }
1212                            return;
1213                        } else {
1214                            // Once we bind to the service, the first
1215                            // pending request will be processed.
1216                            mPendingInstalls.add(idx, params);
1217                        }
1218                    } else {
1219                        mPendingInstalls.add(idx, params);
1220                        // Already bound to the service. Just make
1221                        // sure we trigger off processing the first request.
1222                        if (idx == 0) {
1223                            mHandler.sendEmptyMessage(MCS_BOUND);
1224                        }
1225                    }
1226                    break;
1227                }
1228                case MCS_BOUND: {
1229                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1230                    if (msg.obj != null) {
1231                        mContainerService = (IMediaContainerService) msg.obj;
1232                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1233                                System.identityHashCode(mHandler));
1234                    }
1235                    if (mContainerService == null) {
1236                        if (!mBound) {
1237                            // Something seriously wrong since we are not bound and we are not
1238                            // waiting for connection. Bail out.
1239                            Slog.e(TAG, "Cannot bind to media container service");
1240                            for (HandlerParams params : mPendingInstalls) {
1241                                // Indicate service bind error
1242                                params.serviceError();
1243                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1244                                        System.identityHashCode(params));
1245                                if (params.traceMethod != null) {
1246                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1247                                            params.traceMethod, params.traceCookie);
1248                                }
1249                                return;
1250                            }
1251                            mPendingInstalls.clear();
1252                        } else {
1253                            Slog.w(TAG, "Waiting to connect to media container service");
1254                        }
1255                    } else if (mPendingInstalls.size() > 0) {
1256                        HandlerParams params = mPendingInstalls.get(0);
1257                        if (params != null) {
1258                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                    System.identityHashCode(params));
1260                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1261                            if (params.startCopy()) {
1262                                // We are done...  look for more work or to
1263                                // go idle.
1264                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1265                                        "Checking for more work or unbind...");
1266                                // Delete pending install
1267                                if (mPendingInstalls.size() > 0) {
1268                                    mPendingInstalls.remove(0);
1269                                }
1270                                if (mPendingInstalls.size() == 0) {
1271                                    if (mBound) {
1272                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                                "Posting delayed MCS_UNBIND");
1274                                        removeMessages(MCS_UNBIND);
1275                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1276                                        // Unbind after a little delay, to avoid
1277                                        // continual thrashing.
1278                                        sendMessageDelayed(ubmsg, 10000);
1279                                    }
1280                                } else {
1281                                    // There are more pending requests in queue.
1282                                    // Just post MCS_BOUND message to trigger processing
1283                                    // of next pending install.
1284                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                            "Posting MCS_BOUND for next work");
1286                                    mHandler.sendEmptyMessage(MCS_BOUND);
1287                                }
1288                            }
1289                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1290                        }
1291                    } else {
1292                        // Should never happen ideally.
1293                        Slog.w(TAG, "Empty queue");
1294                    }
1295                    break;
1296                }
1297                case MCS_RECONNECT: {
1298                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1299                    if (mPendingInstalls.size() > 0) {
1300                        if (mBound) {
1301                            disconnectService();
1302                        }
1303                        if (!connectToService()) {
1304                            Slog.e(TAG, "Failed to bind to media container service");
1305                            for (HandlerParams params : mPendingInstalls) {
1306                                // Indicate service bind error
1307                                params.serviceError();
1308                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1309                                        System.identityHashCode(params));
1310                            }
1311                            mPendingInstalls.clear();
1312                        }
1313                    }
1314                    break;
1315                }
1316                case MCS_UNBIND: {
1317                    // If there is no actual work left, then time to unbind.
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1319
1320                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1321                        if (mBound) {
1322                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1323
1324                            disconnectService();
1325                        }
1326                    } else if (mPendingInstalls.size() > 0) {
1327                        // There are more pending requests in queue.
1328                        // Just post MCS_BOUND message to trigger processing
1329                        // of next pending install.
1330                        mHandler.sendEmptyMessage(MCS_BOUND);
1331                    }
1332
1333                    break;
1334                }
1335                case MCS_GIVE_UP: {
1336                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1337                    HandlerParams params = mPendingInstalls.remove(0);
1338                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1339                            System.identityHashCode(params));
1340                    break;
1341                }
1342                case SEND_PENDING_BROADCAST: {
1343                    String packages[];
1344                    ArrayList<String> components[];
1345                    int size = 0;
1346                    int uids[];
1347                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1348                    synchronized (mPackages) {
1349                        if (mPendingBroadcasts == null) {
1350                            return;
1351                        }
1352                        size = mPendingBroadcasts.size();
1353                        if (size <= 0) {
1354                            // Nothing to be done. Just return
1355                            return;
1356                        }
1357                        packages = new String[size];
1358                        components = new ArrayList[size];
1359                        uids = new int[size];
1360                        int i = 0;  // filling out the above arrays
1361
1362                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1363                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1364                            Iterator<Map.Entry<String, ArrayList<String>>> it
1365                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1366                                            .entrySet().iterator();
1367                            while (it.hasNext() && i < size) {
1368                                Map.Entry<String, ArrayList<String>> ent = it.next();
1369                                packages[i] = ent.getKey();
1370                                components[i] = ent.getValue();
1371                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1372                                uids[i] = (ps != null)
1373                                        ? UserHandle.getUid(packageUserId, ps.appId)
1374                                        : -1;
1375                                i++;
1376                            }
1377                        }
1378                        size = i;
1379                        mPendingBroadcasts.clear();
1380                    }
1381                    // Send broadcasts
1382                    for (int i = 0; i < size; i++) {
1383                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1384                    }
1385                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1386                    break;
1387                }
1388                case START_CLEANING_PACKAGE: {
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1390                    final String packageName = (String)msg.obj;
1391                    final int userId = msg.arg1;
1392                    final boolean andCode = msg.arg2 != 0;
1393                    synchronized (mPackages) {
1394                        if (userId == UserHandle.USER_ALL) {
1395                            int[] users = sUserManager.getUserIds();
1396                            for (int user : users) {
1397                                mSettings.addPackageToCleanLPw(
1398                                        new PackageCleanItem(user, packageName, andCode));
1399                            }
1400                        } else {
1401                            mSettings.addPackageToCleanLPw(
1402                                    new PackageCleanItem(userId, packageName, andCode));
1403                        }
1404                    }
1405                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406                    startCleaningPackages();
1407                } break;
1408                case POST_INSTALL: {
1409                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1410
1411                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1412                    final boolean didRestore = (msg.arg2 != 0);
1413                    mRunningInstalls.delete(msg.arg1);
1414
1415                    if (data != null) {
1416                        InstallArgs args = data.args;
1417                        PackageInstalledInfo parentRes = data.res;
1418
1419                        final boolean grantPermissions = (args.installFlags
1420                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1421                        final boolean killApp = (args.installFlags
1422                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1423                        final String[] grantedPermissions = args.installGrantPermissions;
1424
1425                        // Handle the parent package
1426                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1427                                grantedPermissions, didRestore, args.installerPackageName,
1428                                args.observer);
1429
1430                        // Handle the child packages
1431                        final int childCount = (parentRes.addedChildPackages != null)
1432                                ? parentRes.addedChildPackages.size() : 0;
1433                        for (int i = 0; i < childCount; i++) {
1434                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1435                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1436                                    grantedPermissions, false, args.installerPackageName,
1437                                    args.observer);
1438                        }
1439
1440                        // Log tracing if needed
1441                        if (args.traceMethod != null) {
1442                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1443                                    args.traceCookie);
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448
1449                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1450                } break;
1451                case UPDATED_MEDIA_STATUS: {
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1453                    boolean reportStatus = msg.arg1 == 1;
1454                    boolean doGc = msg.arg2 == 1;
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1456                    if (doGc) {
1457                        // Force a gc to clear up stale containers.
1458                        Runtime.getRuntime().gc();
1459                    }
1460                    if (msg.obj != null) {
1461                        @SuppressWarnings("unchecked")
1462                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1463                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1464                        // Unload containers
1465                        unloadAllContainers(args);
1466                    }
1467                    if (reportStatus) {
1468                        try {
1469                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1470                            PackageHelper.getMountService().finishMediaUpdate();
1471                        } catch (RemoteException e) {
1472                            Log.e(TAG, "MountService not running?");
1473                        }
1474                    }
1475                } break;
1476                case WRITE_SETTINGS: {
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1478                    synchronized (mPackages) {
1479                        removeMessages(WRITE_SETTINGS);
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        mSettings.writeLPr();
1482                        mDirtyUsers.clear();
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case WRITE_PACKAGE_RESTRICTIONS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        for (int userId : mDirtyUsers) {
1491                            mSettings.writePackageRestrictionsLPr(userId);
1492                        }
1493                        mDirtyUsers.clear();
1494                    }
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1496                } break;
1497                case WRITE_PACKAGE_LIST: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    synchronized (mPackages) {
1500                        removeMessages(WRITE_PACKAGE_LIST);
1501                        mSettings.writePackageListLPr(msg.arg1);
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                } break;
1505                case CHECK_PENDING_VERIFICATION: {
1506                    final int verificationId = msg.arg1;
1507                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                    if ((state != null) && !state.timeoutExtended()) {
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        Slog.i(TAG, "Verification timed out for " + originUri);
1514                        mPendingVerification.remove(verificationId);
1515
1516                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                            Slog.i(TAG, "Continuing with installation of " + originUri);
1520                            state.setVerifierResponse(Binder.getCallingUid(),
1521                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_ALLOW,
1524                                    state.getInstallArgs().getUser());
1525                            try {
1526                                ret = args.copyApk(mContainerService, true);
1527                            } catch (RemoteException e) {
1528                                Slog.e(TAG, "Could not contact the ContainerService");
1529                            }
1530                        } else {
1531                            broadcastPackageVerified(verificationId, originUri,
1532                                    PackageManager.VERIFICATION_REJECT,
1533                                    state.getInstallArgs().getUser());
1534                        }
1535
1536                        Trace.asyncTraceEnd(
1537                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538
1539                        processPendingInstall(args, ret);
1540                        mHandler.sendEmptyMessage(MCS_UNBIND);
1541                    }
1542                    break;
1543                }
1544                case PACKAGE_VERIFIED: {
1545                    final int verificationId = msg.arg1;
1546
1547                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1548                    if (state == null) {
1549                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1550                        break;
1551                    }
1552
1553                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (state.isVerificationComplete()) {
1558                        mPendingVerification.remove(verificationId);
1559
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        int ret;
1564                        if (state.isInstallAllowed()) {
1565                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    response.code, state.getInstallArgs().getUser());
1568                            try {
1569                                ret = args.copyApk(mContainerService, true);
1570                            } catch (RemoteException e) {
1571                                Slog.e(TAG, "Could not contact the ContainerService");
1572                            }
1573                        } else {
1574                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575                        }
1576
1577                        Trace.asyncTraceEnd(
1578                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579
1580                        processPendingInstall(args, ret);
1581                        mHandler.sendEmptyMessage(MCS_UNBIND);
1582                    }
1583
1584                    break;
1585                }
1586                case START_INTENT_FILTER_VERIFICATIONS: {
1587                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1588                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589                            params.replacing, params.pkg);
1590                    break;
1591                }
1592                case INTENT_FILTER_VERIFIED: {
1593                    final int verificationId = msg.arg1;
1594
1595                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596                            verificationId);
1597                    if (state == null) {
1598                        Slog.w(TAG, "Invalid IntentFilter verification token "
1599                                + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final int userId = state.getUserId();
1604
1605                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                            "Processing IntentFilter verification with token:"
1607                            + verificationId + " and userId:" + userId);
1608
1609                    final IntentFilterVerificationResponse response =
1610                            (IntentFilterVerificationResponse) msg.obj;
1611
1612                    state.setVerifierResponse(response.callerUid, response.code);
1613
1614                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                            "IntentFilter verification with token:" + verificationId
1616                            + " and userId:" + userId
1617                            + " is settings verifier response with response code:"
1618                            + response.code);
1619
1620                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622                                + response.getFailedDomainsString());
1623                    }
1624
1625                    if (state.isVerificationComplete()) {
1626                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627                    } else {
1628                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629                                "IntentFilter verification with token:" + verificationId
1630                                + " was not said to be complete");
1631                    }
1632
1633                    break;
1634                }
1635            }
1636        }
1637    }
1638
1639    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640            boolean killApp, String[] grantedPermissions,
1641            boolean launchedForRestore, String installerPackage,
1642            IPackageInstallObserver2 installObserver) {
1643        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644            // Send the removed broadcasts
1645            if (res.removedInfo != null) {
1646                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1647            }
1648
1649            // Now that we successfully installed the package, grant runtime
1650            // permissions if requested before broadcasting the install.
1651            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652                    >= Build.VERSION_CODES.M) {
1653                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1654            }
1655
1656            final boolean update = res.removedInfo != null
1657                    && res.removedInfo.removedPackage != null;
1658
1659            // If this is the first time we have child packages for a disabled privileged
1660            // app that had no children, we grant requested runtime permissions to the new
1661            // children if the parent on the system image had them already granted.
1662            if (res.pkg.parentPackage != null) {
1663                synchronized (mPackages) {
1664                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1665                }
1666            }
1667
1668            synchronized (mPackages) {
1669                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1670            }
1671
1672            final String packageName = res.pkg.applicationInfo.packageName;
1673            Bundle extras = new Bundle(1);
1674            extras.putInt(Intent.EXTRA_UID, res.uid);
1675
1676            // Determine the set of users who are adding this package for
1677            // the first time vs. those who are seeing an update.
1678            int[] firstUsers = EMPTY_INT_ARRAY;
1679            int[] updateUsers = EMPTY_INT_ARRAY;
1680            if (res.origUsers == null || res.origUsers.length == 0) {
1681                firstUsers = res.newUsers;
1682            } else {
1683                for (int newUser : res.newUsers) {
1684                    boolean isNew = true;
1685                    for (int origUser : res.origUsers) {
1686                        if (origUser == newUser) {
1687                            isNew = false;
1688                            break;
1689                        }
1690                    }
1691                    if (isNew) {
1692                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1693                    } else {
1694                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1695                    }
1696                }
1697            }
1698
1699            // Send installed broadcasts if the install/update is not ephemeral
1700            if (!isEphemeral(res.pkg)) {
1701                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1702
1703                // Send added for users that see the package for the first time
1704                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                        extras, 0 /*flags*/, null /*targetPackage*/,
1706                        null /*finishedReceiver*/, firstUsers);
1707
1708                // Send added for users that don't see the package for the first time
1709                if (update) {
1710                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1711                }
1712                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1713                        extras, 0 /*flags*/, null /*targetPackage*/,
1714                        null /*finishedReceiver*/, updateUsers);
1715
1716                // Send replaced for users that don't see the package for the first time
1717                if (update) {
1718                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1719                            packageName, extras, 0 /*flags*/,
1720                            null /*targetPackage*/, null /*finishedReceiver*/,
1721                            updateUsers);
1722                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1723                            null /*package*/, null /*extras*/, 0 /*flags*/,
1724                            packageName /*targetPackage*/,
1725                            null /*finishedReceiver*/, updateUsers);
1726                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1727                    // First-install and we did a restore, so we're responsible for the
1728                    // first-launch broadcast.
1729                    if (DEBUG_BACKUP) {
1730                        Slog.i(TAG, "Post-restore of " + packageName
1731                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1732                    }
1733                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1734                }
1735
1736                // Send broadcast package appeared if forward locked/external for all users
1737                // treat asec-hosted packages like removable media on upgrade
1738                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1739                    if (DEBUG_INSTALL) {
1740                        Slog.i(TAG, "upgrading pkg " + res.pkg
1741                                + " is ASEC-hosted -> AVAILABLE");
1742                    }
1743                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1744                    ArrayList<String> pkgList = new ArrayList<>(1);
1745                    pkgList.add(packageName);
1746                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1747                }
1748            }
1749
1750            // Work that needs to happen on first install within each user
1751            if (firstUsers != null && firstUsers.length > 0) {
1752                synchronized (mPackages) {
1753                    for (int userId : firstUsers) {
1754                        // If this app is a browser and it's newly-installed for some
1755                        // users, clear any default-browser state in those users. The
1756                        // app's nature doesn't depend on the user, so we can just check
1757                        // its browser nature in any user and generalize.
1758                        if (packageIsBrowser(packageName, userId)) {
1759                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1760                        }
1761
1762                        // We may also need to apply pending (restored) runtime
1763                        // permission grants within these users.
1764                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1765                    }
1766                }
1767            }
1768
1769            // Log current value of "unknown sources" setting
1770            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1771                    getUnknownSourcesSettings());
1772
1773            // Force a gc to clear up things
1774            Runtime.getRuntime().gc();
1775
1776            // Remove the replaced package's older resources safely now
1777            // We delete after a gc for applications  on sdcard.
1778            if (res.removedInfo != null && res.removedInfo.args != null) {
1779                synchronized (mInstallLock) {
1780                    res.removedInfo.args.doPostDeleteLI(true);
1781                }
1782            }
1783        }
1784
1785        // If someone is watching installs - notify them
1786        if (installObserver != null) {
1787            try {
1788                Bundle extras = extrasForInstallResult(res);
1789                installObserver.onPackageInstalled(res.name, res.returnCode,
1790                        res.returnMsg, extras);
1791            } catch (RemoteException e) {
1792                Slog.i(TAG, "Observer no longer exists.");
1793            }
1794        }
1795    }
1796
1797    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1798            PackageParser.Package pkg) {
1799        if (pkg.parentPackage == null) {
1800            return;
1801        }
1802        if (pkg.requestedPermissions == null) {
1803            return;
1804        }
1805        final PackageSetting disabledSysParentPs = mSettings
1806                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1807        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1808                || !disabledSysParentPs.isPrivileged()
1809                || (disabledSysParentPs.childPackageNames != null
1810                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1811            return;
1812        }
1813        final int[] allUserIds = sUserManager.getUserIds();
1814        final int permCount = pkg.requestedPermissions.size();
1815        for (int i = 0; i < permCount; i++) {
1816            String permission = pkg.requestedPermissions.get(i);
1817            BasePermission bp = mSettings.mPermissions.get(permission);
1818            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1819                continue;
1820            }
1821            for (int userId : allUserIds) {
1822                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1823                        permission, userId)) {
1824                    grantRuntimePermission(pkg.packageName, permission, userId);
1825                }
1826            }
1827        }
1828    }
1829
1830    private StorageEventListener mStorageListener = new StorageEventListener() {
1831        @Override
1832        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1833            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1834                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1835                    final String volumeUuid = vol.getFsUuid();
1836
1837                    // Clean up any users or apps that were removed or recreated
1838                    // while this volume was missing
1839                    reconcileUsers(volumeUuid);
1840                    reconcileApps(volumeUuid);
1841
1842                    // Clean up any install sessions that expired or were
1843                    // cancelled while this volume was missing
1844                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1845
1846                    loadPrivatePackages(vol);
1847
1848                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1849                    unloadPrivatePackages(vol);
1850                }
1851            }
1852
1853            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1854                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1855                    updateExternalMediaStatus(true, false);
1856                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1857                    updateExternalMediaStatus(false, false);
1858                }
1859            }
1860        }
1861
1862        @Override
1863        public void onVolumeForgotten(String fsUuid) {
1864            if (TextUtils.isEmpty(fsUuid)) {
1865                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1866                return;
1867            }
1868
1869            // Remove any apps installed on the forgotten volume
1870            synchronized (mPackages) {
1871                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1872                for (PackageSetting ps : packages) {
1873                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1874                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1875                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1876                }
1877
1878                mSettings.onVolumeForgotten(fsUuid);
1879                mSettings.writeLPr();
1880            }
1881        }
1882    };
1883
1884    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1885            String[] grantedPermissions) {
1886        for (int userId : userIds) {
1887            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1888        }
1889
1890        // We could have touched GID membership, so flush out packages.list
1891        synchronized (mPackages) {
1892            mSettings.writePackageListLPr();
1893        }
1894    }
1895
1896    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1897            String[] grantedPermissions) {
1898        SettingBase sb = (SettingBase) pkg.mExtras;
1899        if (sb == null) {
1900            return;
1901        }
1902
1903        PermissionsState permissionsState = sb.getPermissionsState();
1904
1905        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1906                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1907
1908        for (String permission : pkg.requestedPermissions) {
1909            final BasePermission bp;
1910            synchronized (mPackages) {
1911                bp = mSettings.mPermissions.get(permission);
1912            }
1913            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1914                    && (grantedPermissions == null
1915                           || ArrayUtils.contains(grantedPermissions, permission))) {
1916                final int flags = permissionsState.getPermissionFlags(permission, userId);
1917                // Installer cannot change immutable permissions.
1918                if ((flags & immutableFlags) == 0) {
1919                    grantRuntimePermission(pkg.packageName, permission, userId);
1920                }
1921            }
1922        }
1923    }
1924
1925    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1926        Bundle extras = null;
1927        switch (res.returnCode) {
1928            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1929                extras = new Bundle();
1930                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1931                        res.origPermission);
1932                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1933                        res.origPackage);
1934                break;
1935            }
1936            case PackageManager.INSTALL_SUCCEEDED: {
1937                extras = new Bundle();
1938                extras.putBoolean(Intent.EXTRA_REPLACING,
1939                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1940                break;
1941            }
1942        }
1943        return extras;
1944    }
1945
1946    void scheduleWriteSettingsLocked() {
1947        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1948            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1949        }
1950    }
1951
1952    void scheduleWritePackageListLocked(int userId) {
1953        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1954            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1955            msg.arg1 = userId;
1956            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1957        }
1958    }
1959
1960    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1961        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1962        scheduleWritePackageRestrictionsLocked(userId);
1963    }
1964
1965    void scheduleWritePackageRestrictionsLocked(int userId) {
1966        final int[] userIds = (userId == UserHandle.USER_ALL)
1967                ? sUserManager.getUserIds() : new int[]{userId};
1968        for (int nextUserId : userIds) {
1969            if (!sUserManager.exists(nextUserId)) return;
1970            mDirtyUsers.add(nextUserId);
1971            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1972                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1973            }
1974        }
1975    }
1976
1977    public static PackageManagerService main(Context context, Installer installer,
1978            boolean factoryTest, boolean onlyCore) {
1979        // Self-check for initial settings.
1980        PackageManagerServiceCompilerMapping.checkProperties();
1981
1982        PackageManagerService m = new PackageManagerService(context, installer,
1983                factoryTest, onlyCore);
1984        m.enableSystemUserPackages();
1985        ServiceManager.addService("package", m);
1986        return m;
1987    }
1988
1989    private void enableSystemUserPackages() {
1990        if (!UserManager.isSplitSystemUser()) {
1991            return;
1992        }
1993        // For system user, enable apps based on the following conditions:
1994        // - app is whitelisted or belong to one of these groups:
1995        //   -- system app which has no launcher icons
1996        //   -- system app which has INTERACT_ACROSS_USERS permission
1997        //   -- system IME app
1998        // - app is not in the blacklist
1999        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2000        Set<String> enableApps = new ArraySet<>();
2001        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2002                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2003                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2004        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2005        enableApps.addAll(wlApps);
2006        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2007                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2008        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2009        enableApps.removeAll(blApps);
2010        Log.i(TAG, "Applications installed for system user: " + enableApps);
2011        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2012                UserHandle.SYSTEM);
2013        final int allAppsSize = allAps.size();
2014        synchronized (mPackages) {
2015            for (int i = 0; i < allAppsSize; i++) {
2016                String pName = allAps.get(i);
2017                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2018                // Should not happen, but we shouldn't be failing if it does
2019                if (pkgSetting == null) {
2020                    continue;
2021                }
2022                boolean install = enableApps.contains(pName);
2023                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2024                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2025                            + " for system user");
2026                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2027                }
2028            }
2029        }
2030    }
2031
2032    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2033        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2034                Context.DISPLAY_SERVICE);
2035        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2036    }
2037
2038    /**
2039     * Requests that files preopted on a secondary system partition be copied to the data partition
2040     * if possible.  Note that the actual copying of the files is accomplished by init for security
2041     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2042     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2043     */
2044    private static void requestCopyPreoptedFiles() {
2045        final int WAIT_TIME_MS = 100;
2046        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2047        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2048            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2049            // We will wait for up to 100 seconds.
2050            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2051            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2052                try {
2053                    Thread.sleep(WAIT_TIME_MS);
2054                } catch (InterruptedException e) {
2055                    // Do nothing
2056                }
2057                if (SystemClock.uptimeMillis() > timeEnd) {
2058                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2059                    Slog.wtf(TAG, "cppreopt did not finish!");
2060                    break;
2061                }
2062            }
2063        }
2064    }
2065
2066    public PackageManagerService(Context context, Installer installer,
2067            boolean factoryTest, boolean onlyCore) {
2068        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2069        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2070                SystemClock.uptimeMillis());
2071
2072        if (mSdkVersion <= 0) {
2073            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2074        }
2075
2076        mContext = context;
2077
2078        mPermissionReviewRequired = context.getResources().getBoolean(
2079                R.bool.config_permissionReviewRequired);
2080
2081        mFactoryTest = factoryTest;
2082        mOnlyCore = onlyCore;
2083        mMetrics = new DisplayMetrics();
2084        mSettings = new Settings(mPackages);
2085        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2086                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2088                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2090                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2091        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2092                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2094                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2095        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2096                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2097
2098        String separateProcesses = SystemProperties.get("debug.separate_processes");
2099        if (separateProcesses != null && separateProcesses.length() > 0) {
2100            if ("*".equals(separateProcesses)) {
2101                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2102                mSeparateProcesses = null;
2103                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2104            } else {
2105                mDefParseFlags = 0;
2106                mSeparateProcesses = separateProcesses.split(",");
2107                Slog.w(TAG, "Running with debug.separate_processes: "
2108                        + separateProcesses);
2109            }
2110        } else {
2111            mDefParseFlags = 0;
2112            mSeparateProcesses = null;
2113        }
2114
2115        mInstaller = installer;
2116        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2117                "*dexopt*");
2118        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2119
2120        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2121                FgThread.get().getLooper());
2122
2123        getDefaultDisplayMetrics(context, mMetrics);
2124
2125        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2126        SystemConfig systemConfig = SystemConfig.getInstance();
2127        mGlobalGids = systemConfig.getGlobalGids();
2128        mSystemPermissions = systemConfig.getSystemPermissions();
2129        mAvailableFeatures = systemConfig.getAvailableFeatures();
2130        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2131
2132        mProtectedPackages = new ProtectedPackages(mContext);
2133
2134        synchronized (mInstallLock) {
2135        // writer
2136        synchronized (mPackages) {
2137            mHandlerThread = new ServiceThread(TAG,
2138                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2139            mHandlerThread.start();
2140            mHandler = new PackageHandler(mHandlerThread.getLooper());
2141            mProcessLoggingHandler = new ProcessLoggingHandler();
2142            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2143
2144            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2145
2146            File dataDir = Environment.getDataDirectory();
2147            mAppInstallDir = new File(dataDir, "app");
2148            mAppLib32InstallDir = new File(dataDir, "app-lib");
2149            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2150            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2151            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2152
2153            sUserManager = new UserManagerService(context, this, mPackages);
2154
2155            // Propagate permission configuration in to package manager.
2156            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2157                    = systemConfig.getPermissions();
2158            for (int i=0; i<permConfig.size(); i++) {
2159                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2160                BasePermission bp = mSettings.mPermissions.get(perm.name);
2161                if (bp == null) {
2162                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2163                    mSettings.mPermissions.put(perm.name, bp);
2164                }
2165                if (perm.gids != null) {
2166                    bp.setGids(perm.gids, perm.perUser);
2167                }
2168            }
2169
2170            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2171            for (int i=0; i<libConfig.size(); i++) {
2172                mSharedLibraries.put(libConfig.keyAt(i),
2173                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2174            }
2175
2176            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2177
2178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2179            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2181
2182            if (mFirstBoot) {
2183                requestCopyPreoptedFiles();
2184            }
2185
2186            String customResolverActivity = Resources.getSystem().getString(
2187                    R.string.config_customResolverActivity);
2188            if (TextUtils.isEmpty(customResolverActivity)) {
2189                customResolverActivity = null;
2190            } else {
2191                mCustomResolverComponentName = ComponentName.unflattenFromString(
2192                        customResolverActivity);
2193            }
2194
2195            long startTime = SystemClock.uptimeMillis();
2196
2197            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2198                    startTime);
2199
2200            // Set flag to monitor and not change apk file paths when
2201            // scanning install directories.
2202            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2203
2204            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2205            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2206
2207            if (bootClassPath == null) {
2208                Slog.w(TAG, "No BOOTCLASSPATH found!");
2209            }
2210
2211            if (systemServerClassPath == null) {
2212                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2213            }
2214
2215            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2216            final String[] dexCodeInstructionSets =
2217                    getDexCodeInstructionSets(
2218                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2219
2220            /**
2221             * Ensure all external libraries have had dexopt run on them.
2222             */
2223            if (mSharedLibraries.size() > 0) {
2224                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2225                // NOTE: For now, we're compiling these system "shared libraries"
2226                // (and framework jars) into all available architectures. It's possible
2227                // to compile them only when we come across an app that uses them (there's
2228                // already logic for that in scanPackageLI) but that adds some complexity.
2229                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2230                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2231                        final String lib = libEntry.path;
2232                        if (lib == null) {
2233                            continue;
2234                        }
2235
2236                        try {
2237                            // Shared libraries do not have profiles so we perform a full
2238                            // AOT compilation (if needed).
2239                            int dexoptNeeded = DexFile.getDexOptNeeded(
2240                                    lib, dexCodeInstructionSet,
2241                                    getCompilerFilterForReason(REASON_SHARED_APK),
2242                                    false /* newProfile */);
2243                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2244                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2245                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2246                                        getCompilerFilterForReason(REASON_SHARED_APK),
2247                                        StorageManager.UUID_PRIVATE_INTERNAL,
2248                                        SKIP_SHARED_LIBRARY_CHECK);
2249                            }
2250                        } catch (FileNotFoundException e) {
2251                            Slog.w(TAG, "Library not found: " + lib);
2252                        } catch (IOException | InstallerException e) {
2253                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2254                                    + e.getMessage());
2255                        }
2256                    }
2257                }
2258                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2259            }
2260
2261            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2262
2263            final VersionInfo ver = mSettings.getInternalVersion();
2264            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2265
2266            // when upgrading from pre-M, promote system app permissions from install to runtime
2267            mPromoteSystemApps =
2268                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2269
2270            // When upgrading from pre-N, we need to handle package extraction like first boot,
2271            // as there is no profiling data available.
2272            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2273
2274            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2275
2276            // save off the names of pre-existing system packages prior to scanning; we don't
2277            // want to automatically grant runtime permissions for new system apps
2278            if (mPromoteSystemApps) {
2279                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2280                while (pkgSettingIter.hasNext()) {
2281                    PackageSetting ps = pkgSettingIter.next();
2282                    if (isSystemApp(ps)) {
2283                        mExistingSystemPackages.add(ps.name);
2284                    }
2285                }
2286            }
2287
2288            // Collect vendor overlay packages.
2289            // (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            File vendorOverlayDir;
2293            String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY);
2294            if (!overlaySkuDir.isEmpty()) {
2295                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir);
2296            } else {
2297                vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2298            }
2299            scanDirTracedLI(vendorOverlayDir, 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        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11784    }
11785
11786    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11787            int appId, int userId) {
11788        Bundle extras = new Bundle(1);
11789        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11790
11791        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11792                packageName, extras, 0, null, null, new int[] {userId});
11793        try {
11794            IActivityManager am = ActivityManagerNative.getDefault();
11795            if (isSystem && am.isUserRunning(userId, 0)) {
11796                // The just-installed/enabled app is bundled on the system, so presumed
11797                // to be able to run automatically without needing an explicit launch.
11798                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11799                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11800                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11801                        .setPackage(packageName);
11802                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11803                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11804            }
11805        } catch (RemoteException e) {
11806            // shouldn't happen
11807            Slog.w(TAG, "Unable to bootstrap installed package", e);
11808        }
11809    }
11810
11811    @Override
11812    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11813            int userId) {
11814        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11815        PackageSetting pkgSetting;
11816        final int uid = Binder.getCallingUid();
11817        enforceCrossUserPermission(uid, userId,
11818                true /* requireFullPermission */, true /* checkShell */,
11819                "setApplicationHiddenSetting for user " + userId);
11820
11821        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11822            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11823            return false;
11824        }
11825
11826        long callingId = Binder.clearCallingIdentity();
11827        try {
11828            boolean sendAdded = false;
11829            boolean sendRemoved = false;
11830            // writer
11831            synchronized (mPackages) {
11832                pkgSetting = mSettings.mPackages.get(packageName);
11833                if (pkgSetting == null) {
11834                    return false;
11835                }
11836                // Do not allow "android" is being disabled
11837                if ("android".equals(packageName)) {
11838                    Slog.w(TAG, "Cannot hide package: android");
11839                    return false;
11840                }
11841                // Only allow protected packages to hide themselves.
11842                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11843                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11844                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11845                    return false;
11846                }
11847
11848                if (pkgSetting.getHidden(userId) != hidden) {
11849                    pkgSetting.setHidden(hidden, userId);
11850                    mSettings.writePackageRestrictionsLPr(userId);
11851                    if (hidden) {
11852                        sendRemoved = true;
11853                    } else {
11854                        sendAdded = true;
11855                    }
11856                }
11857            }
11858            if (sendAdded) {
11859                sendPackageAddedForUser(packageName, pkgSetting, userId);
11860                return true;
11861            }
11862            if (sendRemoved) {
11863                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11864                        "hiding pkg");
11865                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11866                return true;
11867            }
11868        } finally {
11869            Binder.restoreCallingIdentity(callingId);
11870        }
11871        return false;
11872    }
11873
11874    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11875            int userId) {
11876        final PackageRemovedInfo info = new PackageRemovedInfo();
11877        info.removedPackage = packageName;
11878        info.removedUsers = new int[] {userId};
11879        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11880        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11881    }
11882
11883    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11884        if (pkgList.length > 0) {
11885            Bundle extras = new Bundle(1);
11886            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11887
11888            sendPackageBroadcast(
11889                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11890                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11891                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11892                    new int[] {userId});
11893        }
11894    }
11895
11896    /**
11897     * Returns true if application is not found or there was an error. Otherwise it returns
11898     * the hidden state of the package for the given user.
11899     */
11900    @Override
11901    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11902        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11903        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11904                true /* requireFullPermission */, false /* checkShell */,
11905                "getApplicationHidden for user " + userId);
11906        PackageSetting pkgSetting;
11907        long callingId = Binder.clearCallingIdentity();
11908        try {
11909            // writer
11910            synchronized (mPackages) {
11911                pkgSetting = mSettings.mPackages.get(packageName);
11912                if (pkgSetting == null) {
11913                    return true;
11914                }
11915                return pkgSetting.getHidden(userId);
11916            }
11917        } finally {
11918            Binder.restoreCallingIdentity(callingId);
11919        }
11920    }
11921
11922    /**
11923     * @hide
11924     */
11925    @Override
11926    public int installExistingPackageAsUser(String packageName, int userId) {
11927        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11928                null);
11929        PackageSetting pkgSetting;
11930        final int uid = Binder.getCallingUid();
11931        enforceCrossUserPermission(uid, userId,
11932                true /* requireFullPermission */, true /* checkShell */,
11933                "installExistingPackage for user " + userId);
11934        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11935            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11936        }
11937
11938        long callingId = Binder.clearCallingIdentity();
11939        try {
11940            boolean installed = false;
11941
11942            // writer
11943            synchronized (mPackages) {
11944                pkgSetting = mSettings.mPackages.get(packageName);
11945                if (pkgSetting == null) {
11946                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11947                }
11948                if (!pkgSetting.getInstalled(userId)) {
11949                    pkgSetting.setInstalled(true, userId);
11950                    pkgSetting.setHidden(false, userId);
11951                    mSettings.writePackageRestrictionsLPr(userId);
11952                    installed = true;
11953                }
11954            }
11955
11956            if (installed) {
11957                if (pkgSetting.pkg != null) {
11958                    synchronized (mInstallLock) {
11959                        // We don't need to freeze for a brand new install
11960                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11961                    }
11962                }
11963                sendPackageAddedForUser(packageName, pkgSetting, userId);
11964            }
11965        } finally {
11966            Binder.restoreCallingIdentity(callingId);
11967        }
11968
11969        return PackageManager.INSTALL_SUCCEEDED;
11970    }
11971
11972    boolean isUserRestricted(int userId, String restrictionKey) {
11973        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11974        if (restrictions.getBoolean(restrictionKey, false)) {
11975            Log.w(TAG, "User is restricted: " + restrictionKey);
11976            return true;
11977        }
11978        return false;
11979    }
11980
11981    @Override
11982    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11983            int userId) {
11984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11985        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11986                true /* requireFullPermission */, true /* checkShell */,
11987                "setPackagesSuspended for user " + userId);
11988
11989        if (ArrayUtils.isEmpty(packageNames)) {
11990            return packageNames;
11991        }
11992
11993        // List of package names for whom the suspended state has changed.
11994        List<String> changedPackages = new ArrayList<>(packageNames.length);
11995        // List of package names for whom the suspended state is not set as requested in this
11996        // method.
11997        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11998        long callingId = Binder.clearCallingIdentity();
11999        try {
12000            for (int i = 0; i < packageNames.length; i++) {
12001                String packageName = packageNames[i];
12002                boolean changed = false;
12003                final int appId;
12004                synchronized (mPackages) {
12005                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12006                    if (pkgSetting == null) {
12007                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12008                                + "\". Skipping suspending/un-suspending.");
12009                        unactionedPackages.add(packageName);
12010                        continue;
12011                    }
12012                    appId = pkgSetting.appId;
12013                    if (pkgSetting.getSuspended(userId) != suspended) {
12014                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12015                            unactionedPackages.add(packageName);
12016                            continue;
12017                        }
12018                        pkgSetting.setSuspended(suspended, userId);
12019                        mSettings.writePackageRestrictionsLPr(userId);
12020                        changed = true;
12021                        changedPackages.add(packageName);
12022                    }
12023                }
12024
12025                if (changed && suspended) {
12026                    killApplication(packageName, UserHandle.getUid(userId, appId),
12027                            "suspending package");
12028                }
12029            }
12030        } finally {
12031            Binder.restoreCallingIdentity(callingId);
12032        }
12033
12034        if (!changedPackages.isEmpty()) {
12035            sendPackagesSuspendedForUser(changedPackages.toArray(
12036                    new String[changedPackages.size()]), userId, suspended);
12037        }
12038
12039        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12040    }
12041
12042    @Override
12043    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12044        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12045                true /* requireFullPermission */, false /* checkShell */,
12046                "isPackageSuspendedForUser for user " + userId);
12047        synchronized (mPackages) {
12048            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12049            if (pkgSetting == null) {
12050                throw new IllegalArgumentException("Unknown target package: " + packageName);
12051            }
12052            return pkgSetting.getSuspended(userId);
12053        }
12054    }
12055
12056    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12057        if (isPackageDeviceAdmin(packageName, userId)) {
12058            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12059                    + "\": has an active device admin");
12060            return false;
12061        }
12062
12063        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12064        if (packageName.equals(activeLauncherPackageName)) {
12065            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12066                    + "\": contains the active launcher");
12067            return false;
12068        }
12069
12070        if (packageName.equals(mRequiredInstallerPackage)) {
12071            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12072                    + "\": required for package installation");
12073            return false;
12074        }
12075
12076        if (packageName.equals(mRequiredUninstallerPackage)) {
12077            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12078                    + "\": required for package uninstallation");
12079            return false;
12080        }
12081
12082        if (packageName.equals(mRequiredVerifierPackage)) {
12083            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12084                    + "\": required for package verification");
12085            return false;
12086        }
12087
12088        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12089            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12090                    + "\": is the default dialer");
12091            return false;
12092        }
12093
12094        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12095            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12096                    + "\": protected package");
12097            return false;
12098        }
12099
12100        return true;
12101    }
12102
12103    private String getActiveLauncherPackageName(int userId) {
12104        Intent intent = new Intent(Intent.ACTION_MAIN);
12105        intent.addCategory(Intent.CATEGORY_HOME);
12106        ResolveInfo resolveInfo = resolveIntent(
12107                intent,
12108                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12109                PackageManager.MATCH_DEFAULT_ONLY,
12110                userId);
12111
12112        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12113    }
12114
12115    private String getDefaultDialerPackageName(int userId) {
12116        synchronized (mPackages) {
12117            return mSettings.getDefaultDialerPackageNameLPw(userId);
12118        }
12119    }
12120
12121    @Override
12122    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12123        mContext.enforceCallingOrSelfPermission(
12124                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12125                "Only package verification agents can verify applications");
12126
12127        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12128        final PackageVerificationResponse response = new PackageVerificationResponse(
12129                verificationCode, Binder.getCallingUid());
12130        msg.arg1 = id;
12131        msg.obj = response;
12132        mHandler.sendMessage(msg);
12133    }
12134
12135    @Override
12136    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12137            long millisecondsToDelay) {
12138        mContext.enforceCallingOrSelfPermission(
12139                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12140                "Only package verification agents can extend verification timeouts");
12141
12142        final PackageVerificationState state = mPendingVerification.get(id);
12143        final PackageVerificationResponse response = new PackageVerificationResponse(
12144                verificationCodeAtTimeout, Binder.getCallingUid());
12145
12146        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12147            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12148        }
12149        if (millisecondsToDelay < 0) {
12150            millisecondsToDelay = 0;
12151        }
12152        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12153                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12154            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12155        }
12156
12157        if ((state != null) && !state.timeoutExtended()) {
12158            state.extendTimeout();
12159
12160            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12161            msg.arg1 = id;
12162            msg.obj = response;
12163            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12164        }
12165    }
12166
12167    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12168            int verificationCode, UserHandle user) {
12169        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12170        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12171        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12172        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12173        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12174
12175        mContext.sendBroadcastAsUser(intent, user,
12176                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12177    }
12178
12179    private ComponentName matchComponentForVerifier(String packageName,
12180            List<ResolveInfo> receivers) {
12181        ActivityInfo targetReceiver = null;
12182
12183        final int NR = receivers.size();
12184        for (int i = 0; i < NR; i++) {
12185            final ResolveInfo info = receivers.get(i);
12186            if (info.activityInfo == null) {
12187                continue;
12188            }
12189
12190            if (packageName.equals(info.activityInfo.packageName)) {
12191                targetReceiver = info.activityInfo;
12192                break;
12193            }
12194        }
12195
12196        if (targetReceiver == null) {
12197            return null;
12198        }
12199
12200        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12201    }
12202
12203    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12204            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12205        if (pkgInfo.verifiers.length == 0) {
12206            return null;
12207        }
12208
12209        final int N = pkgInfo.verifiers.length;
12210        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12211        for (int i = 0; i < N; i++) {
12212            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12213
12214            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12215                    receivers);
12216            if (comp == null) {
12217                continue;
12218            }
12219
12220            final int verifierUid = getUidForVerifier(verifierInfo);
12221            if (verifierUid == -1) {
12222                continue;
12223            }
12224
12225            if (DEBUG_VERIFY) {
12226                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12227                        + " with the correct signature");
12228            }
12229            sufficientVerifiers.add(comp);
12230            verificationState.addSufficientVerifier(verifierUid);
12231        }
12232
12233        return sufficientVerifiers;
12234    }
12235
12236    private int getUidForVerifier(VerifierInfo verifierInfo) {
12237        synchronized (mPackages) {
12238            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12239            if (pkg == null) {
12240                return -1;
12241            } else if (pkg.mSignatures.length != 1) {
12242                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12243                        + " has more than one signature; ignoring");
12244                return -1;
12245            }
12246
12247            /*
12248             * If the public key of the package's signature does not match
12249             * our expected public key, then this is a different package and
12250             * we should skip.
12251             */
12252
12253            final byte[] expectedPublicKey;
12254            try {
12255                final Signature verifierSig = pkg.mSignatures[0];
12256                final PublicKey publicKey = verifierSig.getPublicKey();
12257                expectedPublicKey = publicKey.getEncoded();
12258            } catch (CertificateException e) {
12259                return -1;
12260            }
12261
12262            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12263
12264            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12265                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12266                        + " does not have the expected public key; ignoring");
12267                return -1;
12268            }
12269
12270            return pkg.applicationInfo.uid;
12271        }
12272    }
12273
12274    @Override
12275    public void finishPackageInstall(int token, boolean didLaunch) {
12276        enforceSystemOrRoot("Only the system is allowed to finish installs");
12277
12278        if (DEBUG_INSTALL) {
12279            Slog.v(TAG, "BM finishing package install for " + token);
12280        }
12281        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12282
12283        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12284        mHandler.sendMessage(msg);
12285    }
12286
12287    /**
12288     * Get the verification agent timeout.
12289     *
12290     * @return verification timeout in milliseconds
12291     */
12292    private long getVerificationTimeout() {
12293        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12294                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12295                DEFAULT_VERIFICATION_TIMEOUT);
12296    }
12297
12298    /**
12299     * Get the default verification agent response code.
12300     *
12301     * @return default verification response code
12302     */
12303    private int getDefaultVerificationResponse() {
12304        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12305                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12306                DEFAULT_VERIFICATION_RESPONSE);
12307    }
12308
12309    /**
12310     * Check whether or not package verification has been enabled.
12311     *
12312     * @return true if verification should be performed
12313     */
12314    private boolean isVerificationEnabled(int userId, int installFlags) {
12315        if (!DEFAULT_VERIFY_ENABLE) {
12316            return false;
12317        }
12318        // Ephemeral apps don't get the full verification treatment
12319        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12320            if (DEBUG_EPHEMERAL) {
12321                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12322            }
12323            return false;
12324        }
12325
12326        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12327
12328        // Check if installing from ADB
12329        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12330            // Do not run verification in a test harness environment
12331            if (ActivityManager.isRunningInTestHarness()) {
12332                return false;
12333            }
12334            if (ensureVerifyAppsEnabled) {
12335                return true;
12336            }
12337            // Check if the developer does not want package verification for ADB installs
12338            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12339                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12340                return false;
12341            }
12342        }
12343
12344        if (ensureVerifyAppsEnabled) {
12345            return true;
12346        }
12347
12348        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12349                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12350    }
12351
12352    @Override
12353    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12354            throws RemoteException {
12355        mContext.enforceCallingOrSelfPermission(
12356                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12357                "Only intentfilter verification agents can verify applications");
12358
12359        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12360        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12361                Binder.getCallingUid(), verificationCode, failedDomains);
12362        msg.arg1 = id;
12363        msg.obj = response;
12364        mHandler.sendMessage(msg);
12365    }
12366
12367    @Override
12368    public int getIntentVerificationStatus(String packageName, int userId) {
12369        synchronized (mPackages) {
12370            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12371        }
12372    }
12373
12374    @Override
12375    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12376        mContext.enforceCallingOrSelfPermission(
12377                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12378
12379        boolean result = false;
12380        synchronized (mPackages) {
12381            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12382        }
12383        if (result) {
12384            scheduleWritePackageRestrictionsLocked(userId);
12385        }
12386        return result;
12387    }
12388
12389    @Override
12390    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12391            String packageName) {
12392        synchronized (mPackages) {
12393            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12394        }
12395    }
12396
12397    @Override
12398    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12399        if (TextUtils.isEmpty(packageName)) {
12400            return ParceledListSlice.emptyList();
12401        }
12402        synchronized (mPackages) {
12403            PackageParser.Package pkg = mPackages.get(packageName);
12404            if (pkg == null || pkg.activities == null) {
12405                return ParceledListSlice.emptyList();
12406            }
12407            final int count = pkg.activities.size();
12408            ArrayList<IntentFilter> result = new ArrayList<>();
12409            for (int n=0; n<count; n++) {
12410                PackageParser.Activity activity = pkg.activities.get(n);
12411                if (activity.intents != null && activity.intents.size() > 0) {
12412                    result.addAll(activity.intents);
12413                }
12414            }
12415            return new ParceledListSlice<>(result);
12416        }
12417    }
12418
12419    @Override
12420    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12421        mContext.enforceCallingOrSelfPermission(
12422                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12423
12424        synchronized (mPackages) {
12425            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12426            if (packageName != null) {
12427                result |= updateIntentVerificationStatus(packageName,
12428                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12429                        userId);
12430                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12431                        packageName, userId);
12432            }
12433            return result;
12434        }
12435    }
12436
12437    @Override
12438    public String getDefaultBrowserPackageName(int userId) {
12439        synchronized (mPackages) {
12440            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12441        }
12442    }
12443
12444    /**
12445     * Get the "allow unknown sources" setting.
12446     *
12447     * @return the current "allow unknown sources" setting
12448     */
12449    private int getUnknownSourcesSettings() {
12450        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12451                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12452                -1);
12453    }
12454
12455    @Override
12456    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12457        final int uid = Binder.getCallingUid();
12458        // writer
12459        synchronized (mPackages) {
12460            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12461            if (targetPackageSetting == null) {
12462                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12463            }
12464
12465            PackageSetting installerPackageSetting;
12466            if (installerPackageName != null) {
12467                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12468                if (installerPackageSetting == null) {
12469                    throw new IllegalArgumentException("Unknown installer package: "
12470                            + installerPackageName);
12471                }
12472            } else {
12473                installerPackageSetting = null;
12474            }
12475
12476            Signature[] callerSignature;
12477            Object obj = mSettings.getUserIdLPr(uid);
12478            if (obj != null) {
12479                if (obj instanceof SharedUserSetting) {
12480                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12481                } else if (obj instanceof PackageSetting) {
12482                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12483                } else {
12484                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12485                }
12486            } else {
12487                throw new SecurityException("Unknown calling UID: " + uid);
12488            }
12489
12490            // Verify: can't set installerPackageName to a package that is
12491            // not signed with the same cert as the caller.
12492            if (installerPackageSetting != null) {
12493                if (compareSignatures(callerSignature,
12494                        installerPackageSetting.signatures.mSignatures)
12495                        != PackageManager.SIGNATURE_MATCH) {
12496                    throw new SecurityException(
12497                            "Caller does not have same cert as new installer package "
12498                            + installerPackageName);
12499                }
12500            }
12501
12502            // Verify: if target already has an installer package, it must
12503            // be signed with the same cert as the caller.
12504            if (targetPackageSetting.installerPackageName != null) {
12505                PackageSetting setting = mSettings.mPackages.get(
12506                        targetPackageSetting.installerPackageName);
12507                // If the currently set package isn't valid, then it's always
12508                // okay to change it.
12509                if (setting != null) {
12510                    if (compareSignatures(callerSignature,
12511                            setting.signatures.mSignatures)
12512                            != PackageManager.SIGNATURE_MATCH) {
12513                        throw new SecurityException(
12514                                "Caller does not have same cert as old installer package "
12515                                + targetPackageSetting.installerPackageName);
12516                    }
12517                }
12518            }
12519
12520            // Okay!
12521            targetPackageSetting.installerPackageName = installerPackageName;
12522            if (installerPackageName != null) {
12523                mSettings.mInstallerPackages.add(installerPackageName);
12524            }
12525            scheduleWriteSettingsLocked();
12526        }
12527    }
12528
12529    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12530        // Queue up an async operation since the package installation may take a little while.
12531        mHandler.post(new Runnable() {
12532            public void run() {
12533                mHandler.removeCallbacks(this);
12534                 // Result object to be returned
12535                PackageInstalledInfo res = new PackageInstalledInfo();
12536                res.setReturnCode(currentStatus);
12537                res.uid = -1;
12538                res.pkg = null;
12539                res.removedInfo = null;
12540                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12541                    args.doPreInstall(res.returnCode);
12542                    synchronized (mInstallLock) {
12543                        installPackageTracedLI(args, res);
12544                    }
12545                    args.doPostInstall(res.returnCode, res.uid);
12546                }
12547
12548                // A restore should be performed at this point if (a) the install
12549                // succeeded, (b) the operation is not an update, and (c) the new
12550                // package has not opted out of backup participation.
12551                final boolean update = res.removedInfo != null
12552                        && res.removedInfo.removedPackage != null;
12553                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12554                boolean doRestore = !update
12555                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12556
12557                // Set up the post-install work request bookkeeping.  This will be used
12558                // and cleaned up by the post-install event handling regardless of whether
12559                // there's a restore pass performed.  Token values are >= 1.
12560                int token;
12561                if (mNextInstallToken < 0) mNextInstallToken = 1;
12562                token = mNextInstallToken++;
12563
12564                PostInstallData data = new PostInstallData(args, res);
12565                mRunningInstalls.put(token, data);
12566                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12567
12568                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12569                    // Pass responsibility to the Backup Manager.  It will perform a
12570                    // restore if appropriate, then pass responsibility back to the
12571                    // Package Manager to run the post-install observer callbacks
12572                    // and broadcasts.
12573                    IBackupManager bm = IBackupManager.Stub.asInterface(
12574                            ServiceManager.getService(Context.BACKUP_SERVICE));
12575                    if (bm != null) {
12576                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12577                                + " to BM for possible restore");
12578                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12579                        try {
12580                            // TODO: http://b/22388012
12581                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12582                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12583                            } else {
12584                                doRestore = false;
12585                            }
12586                        } catch (RemoteException e) {
12587                            // can't happen; the backup manager is local
12588                        } catch (Exception e) {
12589                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12590                            doRestore = false;
12591                        }
12592                    } else {
12593                        Slog.e(TAG, "Backup Manager not found!");
12594                        doRestore = false;
12595                    }
12596                }
12597
12598                if (!doRestore) {
12599                    // No restore possible, or the Backup Manager was mysteriously not
12600                    // available -- just fire the post-install work request directly.
12601                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12602
12603                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12604
12605                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12606                    mHandler.sendMessage(msg);
12607                }
12608            }
12609        });
12610    }
12611
12612    /**
12613     * Callback from PackageSettings whenever an app is first transitioned out of the
12614     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12615     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12616     * here whether the app is the target of an ongoing install, and only send the
12617     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12618     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12619     * handling.
12620     */
12621    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12622        // Serialize this with the rest of the install-process message chain.  In the
12623        // restore-at-install case, this Runnable will necessarily run before the
12624        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12625        // are coherent.  In the non-restore case, the app has already completed install
12626        // and been launched through some other means, so it is not in a problematic
12627        // state for observers to see the FIRST_LAUNCH signal.
12628        mHandler.post(new Runnable() {
12629            @Override
12630            public void run() {
12631                for (int i = 0; i < mRunningInstalls.size(); i++) {
12632                    final PostInstallData data = mRunningInstalls.valueAt(i);
12633                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12634                        continue;
12635                    }
12636                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12637                        // right package; but is it for the right user?
12638                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12639                            if (userId == data.res.newUsers[uIndex]) {
12640                                if (DEBUG_BACKUP) {
12641                                    Slog.i(TAG, "Package " + pkgName
12642                                            + " being restored so deferring FIRST_LAUNCH");
12643                                }
12644                                return;
12645                            }
12646                        }
12647                    }
12648                }
12649                // didn't find it, so not being restored
12650                if (DEBUG_BACKUP) {
12651                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12652                }
12653                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12654            }
12655        });
12656    }
12657
12658    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12659        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12660                installerPkg, null, userIds);
12661    }
12662
12663    private abstract class HandlerParams {
12664        private static final int MAX_RETRIES = 4;
12665
12666        /**
12667         * Number of times startCopy() has been attempted and had a non-fatal
12668         * error.
12669         */
12670        private int mRetries = 0;
12671
12672        /** User handle for the user requesting the information or installation. */
12673        private final UserHandle mUser;
12674        String traceMethod;
12675        int traceCookie;
12676
12677        HandlerParams(UserHandle user) {
12678            mUser = user;
12679        }
12680
12681        UserHandle getUser() {
12682            return mUser;
12683        }
12684
12685        HandlerParams setTraceMethod(String traceMethod) {
12686            this.traceMethod = traceMethod;
12687            return this;
12688        }
12689
12690        HandlerParams setTraceCookie(int traceCookie) {
12691            this.traceCookie = traceCookie;
12692            return this;
12693        }
12694
12695        final boolean startCopy() {
12696            boolean res;
12697            try {
12698                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12699
12700                if (++mRetries > MAX_RETRIES) {
12701                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12702                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12703                    handleServiceError();
12704                    return false;
12705                } else {
12706                    handleStartCopy();
12707                    res = true;
12708                }
12709            } catch (RemoteException e) {
12710                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12711                mHandler.sendEmptyMessage(MCS_RECONNECT);
12712                res = false;
12713            }
12714            handleReturnCode();
12715            return res;
12716        }
12717
12718        final void serviceError() {
12719            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12720            handleServiceError();
12721            handleReturnCode();
12722        }
12723
12724        abstract void handleStartCopy() throws RemoteException;
12725        abstract void handleServiceError();
12726        abstract void handleReturnCode();
12727    }
12728
12729    class MeasureParams extends HandlerParams {
12730        private final PackageStats mStats;
12731        private boolean mSuccess;
12732
12733        private final IPackageStatsObserver mObserver;
12734
12735        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12736            super(new UserHandle(stats.userHandle));
12737            mObserver = observer;
12738            mStats = stats;
12739        }
12740
12741        @Override
12742        public String toString() {
12743            return "MeasureParams{"
12744                + Integer.toHexString(System.identityHashCode(this))
12745                + " " + mStats.packageName + "}";
12746        }
12747
12748        @Override
12749        void handleStartCopy() throws RemoteException {
12750            synchronized (mInstallLock) {
12751                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12752            }
12753
12754            if (mSuccess) {
12755                boolean mounted = false;
12756                try {
12757                    final String status = Environment.getExternalStorageState();
12758                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12759                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12760                } catch (Exception e) {
12761                }
12762
12763                if (mounted) {
12764                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12765
12766                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12767                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12768
12769                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12770                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12771
12772                    // Always subtract cache size, since it's a subdirectory
12773                    mStats.externalDataSize -= mStats.externalCacheSize;
12774
12775                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12776                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12777
12778                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12779                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12780                }
12781            }
12782        }
12783
12784        @Override
12785        void handleReturnCode() {
12786            if (mObserver != null) {
12787                try {
12788                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12789                } catch (RemoteException e) {
12790                    Slog.i(TAG, "Observer no longer exists.");
12791                }
12792            }
12793        }
12794
12795        @Override
12796        void handleServiceError() {
12797            Slog.e(TAG, "Could not measure application " + mStats.packageName
12798                            + " external storage");
12799        }
12800    }
12801
12802    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12803            throws RemoteException {
12804        long result = 0;
12805        for (File path : paths) {
12806            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12807        }
12808        return result;
12809    }
12810
12811    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12812        for (File path : paths) {
12813            try {
12814                mcs.clearDirectory(path.getAbsolutePath());
12815            } catch (RemoteException e) {
12816            }
12817        }
12818    }
12819
12820    static class OriginInfo {
12821        /**
12822         * Location where install is coming from, before it has been
12823         * copied/renamed into place. This could be a single monolithic APK
12824         * file, or a cluster directory. This location may be untrusted.
12825         */
12826        final File file;
12827        final String cid;
12828
12829        /**
12830         * Flag indicating that {@link #file} or {@link #cid} has already been
12831         * staged, meaning downstream users don't need to defensively copy the
12832         * contents.
12833         */
12834        final boolean staged;
12835
12836        /**
12837         * Flag indicating that {@link #file} or {@link #cid} is an already
12838         * installed app that is being moved.
12839         */
12840        final boolean existing;
12841
12842        final String resolvedPath;
12843        final File resolvedFile;
12844
12845        static OriginInfo fromNothing() {
12846            return new OriginInfo(null, null, false, false);
12847        }
12848
12849        static OriginInfo fromUntrustedFile(File file) {
12850            return new OriginInfo(file, null, false, false);
12851        }
12852
12853        static OriginInfo fromExistingFile(File file) {
12854            return new OriginInfo(file, null, false, true);
12855        }
12856
12857        static OriginInfo fromStagedFile(File file) {
12858            return new OriginInfo(file, null, true, false);
12859        }
12860
12861        static OriginInfo fromStagedContainer(String cid) {
12862            return new OriginInfo(null, cid, true, false);
12863        }
12864
12865        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12866            this.file = file;
12867            this.cid = cid;
12868            this.staged = staged;
12869            this.existing = existing;
12870
12871            if (cid != null) {
12872                resolvedPath = PackageHelper.getSdDir(cid);
12873                resolvedFile = new File(resolvedPath);
12874            } else if (file != null) {
12875                resolvedPath = file.getAbsolutePath();
12876                resolvedFile = file;
12877            } else {
12878                resolvedPath = null;
12879                resolvedFile = null;
12880            }
12881        }
12882    }
12883
12884    static class MoveInfo {
12885        final int moveId;
12886        final String fromUuid;
12887        final String toUuid;
12888        final String packageName;
12889        final String dataAppName;
12890        final int appId;
12891        final String seinfo;
12892        final int targetSdkVersion;
12893
12894        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12895                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12896            this.moveId = moveId;
12897            this.fromUuid = fromUuid;
12898            this.toUuid = toUuid;
12899            this.packageName = packageName;
12900            this.dataAppName = dataAppName;
12901            this.appId = appId;
12902            this.seinfo = seinfo;
12903            this.targetSdkVersion = targetSdkVersion;
12904        }
12905    }
12906
12907    static class VerificationInfo {
12908        /** A constant used to indicate that a uid value is not present. */
12909        public static final int NO_UID = -1;
12910
12911        /** URI referencing where the package was downloaded from. */
12912        final Uri originatingUri;
12913
12914        /** HTTP referrer URI associated with the originatingURI. */
12915        final Uri referrer;
12916
12917        /** UID of the application that the install request originated from. */
12918        final int originatingUid;
12919
12920        /** UID of application requesting the install */
12921        final int installerUid;
12922
12923        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12924            this.originatingUri = originatingUri;
12925            this.referrer = referrer;
12926            this.originatingUid = originatingUid;
12927            this.installerUid = installerUid;
12928        }
12929    }
12930
12931    class InstallParams extends HandlerParams {
12932        final OriginInfo origin;
12933        final MoveInfo move;
12934        final IPackageInstallObserver2 observer;
12935        int installFlags;
12936        final String installerPackageName;
12937        final String volumeUuid;
12938        private InstallArgs mArgs;
12939        private int mRet;
12940        final String packageAbiOverride;
12941        final String[] grantedRuntimePermissions;
12942        final VerificationInfo verificationInfo;
12943        final Certificate[][] certificates;
12944
12945        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12946                int installFlags, String installerPackageName, String volumeUuid,
12947                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12948                String[] grantedPermissions, Certificate[][] certificates) {
12949            super(user);
12950            this.origin = origin;
12951            this.move = move;
12952            this.observer = observer;
12953            this.installFlags = installFlags;
12954            this.installerPackageName = installerPackageName;
12955            this.volumeUuid = volumeUuid;
12956            this.verificationInfo = verificationInfo;
12957            this.packageAbiOverride = packageAbiOverride;
12958            this.grantedRuntimePermissions = grantedPermissions;
12959            this.certificates = certificates;
12960        }
12961
12962        @Override
12963        public String toString() {
12964            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12965                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12966        }
12967
12968        private int installLocationPolicy(PackageInfoLite pkgLite) {
12969            String packageName = pkgLite.packageName;
12970            int installLocation = pkgLite.installLocation;
12971            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12972            // reader
12973            synchronized (mPackages) {
12974                // Currently installed package which the new package is attempting to replace or
12975                // null if no such package is installed.
12976                PackageParser.Package installedPkg = mPackages.get(packageName);
12977                // Package which currently owns the data which the new package will own if installed.
12978                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12979                // will be null whereas dataOwnerPkg will contain information about the package
12980                // which was uninstalled while keeping its data.
12981                PackageParser.Package dataOwnerPkg = installedPkg;
12982                if (dataOwnerPkg  == null) {
12983                    PackageSetting ps = mSettings.mPackages.get(packageName);
12984                    if (ps != null) {
12985                        dataOwnerPkg = ps.pkg;
12986                    }
12987                }
12988
12989                if (dataOwnerPkg != null) {
12990                    // If installed, the package will get access to data left on the device by its
12991                    // predecessor. As a security measure, this is permited only if this is not a
12992                    // version downgrade or if the predecessor package is marked as debuggable and
12993                    // a downgrade is explicitly requested.
12994                    //
12995                    // On debuggable platform builds, downgrades are permitted even for
12996                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12997                    // not offer security guarantees and thus it's OK to disable some security
12998                    // mechanisms to make debugging/testing easier on those builds. However, even on
12999                    // debuggable builds downgrades of packages are permitted only if requested via
13000                    // installFlags. This is because we aim to keep the behavior of debuggable
13001                    // platform builds as close as possible to the behavior of non-debuggable
13002                    // platform builds.
13003                    final boolean downgradeRequested =
13004                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13005                    final boolean packageDebuggable =
13006                                (dataOwnerPkg.applicationInfo.flags
13007                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13008                    final boolean downgradePermitted =
13009                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13010                    if (!downgradePermitted) {
13011                        try {
13012                            checkDowngrade(dataOwnerPkg, pkgLite);
13013                        } catch (PackageManagerException e) {
13014                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13015                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13016                        }
13017                    }
13018                }
13019
13020                if (installedPkg != null) {
13021                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13022                        // Check for updated system application.
13023                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13024                            if (onSd) {
13025                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13026                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13027                            }
13028                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13029                        } else {
13030                            if (onSd) {
13031                                // Install flag overrides everything.
13032                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13033                            }
13034                            // If current upgrade specifies particular preference
13035                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13036                                // Application explicitly specified internal.
13037                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13038                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13039                                // App explictly prefers external. Let policy decide
13040                            } else {
13041                                // Prefer previous location
13042                                if (isExternal(installedPkg)) {
13043                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13044                                }
13045                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13046                            }
13047                        }
13048                    } else {
13049                        // Invalid install. Return error code
13050                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13051                    }
13052                }
13053            }
13054            // All the special cases have been taken care of.
13055            // Return result based on recommended install location.
13056            if (onSd) {
13057                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13058            }
13059            return pkgLite.recommendedInstallLocation;
13060        }
13061
13062        /*
13063         * Invoke remote method to get package information and install
13064         * location values. Override install location based on default
13065         * policy if needed and then create install arguments based
13066         * on the install location.
13067         */
13068        public void handleStartCopy() throws RemoteException {
13069            int ret = PackageManager.INSTALL_SUCCEEDED;
13070
13071            // If we're already staged, we've firmly committed to an install location
13072            if (origin.staged) {
13073                if (origin.file != null) {
13074                    installFlags |= PackageManager.INSTALL_INTERNAL;
13075                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13076                } else if (origin.cid != null) {
13077                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13078                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13079                } else {
13080                    throw new IllegalStateException("Invalid stage location");
13081                }
13082            }
13083
13084            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13085            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13086            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13087            PackageInfoLite pkgLite = null;
13088
13089            if (onInt && onSd) {
13090                // Check if both bits are set.
13091                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13092                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13093            } else if (onSd && ephemeral) {
13094                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13095                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13096            } else {
13097                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13098                        packageAbiOverride);
13099
13100                if (DEBUG_EPHEMERAL && ephemeral) {
13101                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13102                }
13103
13104                /*
13105                 * If we have too little free space, try to free cache
13106                 * before giving up.
13107                 */
13108                if (!origin.staged && pkgLite.recommendedInstallLocation
13109                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13110                    // TODO: focus freeing disk space on the target device
13111                    final StorageManager storage = StorageManager.from(mContext);
13112                    final long lowThreshold = storage.getStorageLowBytes(
13113                            Environment.getDataDirectory());
13114
13115                    final long sizeBytes = mContainerService.calculateInstalledSize(
13116                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13117
13118                    try {
13119                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13120                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13121                                installFlags, packageAbiOverride);
13122                    } catch (InstallerException e) {
13123                        Slog.w(TAG, "Failed to free cache", e);
13124                    }
13125
13126                    /*
13127                     * The cache free must have deleted the file we
13128                     * downloaded to install.
13129                     *
13130                     * TODO: fix the "freeCache" call to not delete
13131                     *       the file we care about.
13132                     */
13133                    if (pkgLite.recommendedInstallLocation
13134                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13135                        pkgLite.recommendedInstallLocation
13136                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13137                    }
13138                }
13139            }
13140
13141            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13142                int loc = pkgLite.recommendedInstallLocation;
13143                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13144                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13145                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13146                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13147                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13148                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13149                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13150                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13151                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13152                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13153                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13154                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13155                } else {
13156                    // Override with defaults if needed.
13157                    loc = installLocationPolicy(pkgLite);
13158                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13159                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13160                    } else if (!onSd && !onInt) {
13161                        // Override install location with flags
13162                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13163                            // Set the flag to install on external media.
13164                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13165                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13166                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13167                            if (DEBUG_EPHEMERAL) {
13168                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13169                            }
13170                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13171                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13172                                    |PackageManager.INSTALL_INTERNAL);
13173                        } else {
13174                            // Make sure the flag for installing on external
13175                            // media is unset
13176                            installFlags |= PackageManager.INSTALL_INTERNAL;
13177                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13178                        }
13179                    }
13180                }
13181            }
13182
13183            final InstallArgs args = createInstallArgs(this);
13184            mArgs = args;
13185
13186            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13187                // TODO: http://b/22976637
13188                // Apps installed for "all" users use the device owner to verify the app
13189                UserHandle verifierUser = getUser();
13190                if (verifierUser == UserHandle.ALL) {
13191                    verifierUser = UserHandle.SYSTEM;
13192                }
13193
13194                /*
13195                 * Determine if we have any installed package verifiers. If we
13196                 * do, then we'll defer to them to verify the packages.
13197                 */
13198                final int requiredUid = mRequiredVerifierPackage == null ? -1
13199                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13200                                verifierUser.getIdentifier());
13201                if (!origin.existing && requiredUid != -1
13202                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13203                    final Intent verification = new Intent(
13204                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13205                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13206                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13207                            PACKAGE_MIME_TYPE);
13208                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13209
13210                    // Query all live verifiers based on current user state
13211                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13212                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13213
13214                    if (DEBUG_VERIFY) {
13215                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13216                                + verification.toString() + " with " + pkgLite.verifiers.length
13217                                + " optional verifiers");
13218                    }
13219
13220                    final int verificationId = mPendingVerificationToken++;
13221
13222                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13223
13224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13225                            installerPackageName);
13226
13227                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13228                            installFlags);
13229
13230                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13231                            pkgLite.packageName);
13232
13233                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13234                            pkgLite.versionCode);
13235
13236                    if (verificationInfo != null) {
13237                        if (verificationInfo.originatingUri != null) {
13238                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13239                                    verificationInfo.originatingUri);
13240                        }
13241                        if (verificationInfo.referrer != null) {
13242                            verification.putExtra(Intent.EXTRA_REFERRER,
13243                                    verificationInfo.referrer);
13244                        }
13245                        if (verificationInfo.originatingUid >= 0) {
13246                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13247                                    verificationInfo.originatingUid);
13248                        }
13249                        if (verificationInfo.installerUid >= 0) {
13250                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13251                                    verificationInfo.installerUid);
13252                        }
13253                    }
13254
13255                    final PackageVerificationState verificationState = new PackageVerificationState(
13256                            requiredUid, args);
13257
13258                    mPendingVerification.append(verificationId, verificationState);
13259
13260                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13261                            receivers, verificationState);
13262
13263                    /*
13264                     * If any sufficient verifiers were listed in the package
13265                     * manifest, attempt to ask them.
13266                     */
13267                    if (sufficientVerifiers != null) {
13268                        final int N = sufficientVerifiers.size();
13269                        if (N == 0) {
13270                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13271                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13272                        } else {
13273                            for (int i = 0; i < N; i++) {
13274                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13275
13276                                final Intent sufficientIntent = new Intent(verification);
13277                                sufficientIntent.setComponent(verifierComponent);
13278                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13279                            }
13280                        }
13281                    }
13282
13283                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13284                            mRequiredVerifierPackage, receivers);
13285                    if (ret == PackageManager.INSTALL_SUCCEEDED
13286                            && mRequiredVerifierPackage != null) {
13287                        Trace.asyncTraceBegin(
13288                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13289                        /*
13290                         * Send the intent to the required verification agent,
13291                         * but only start the verification timeout after the
13292                         * target BroadcastReceivers have run.
13293                         */
13294                        verification.setComponent(requiredVerifierComponent);
13295                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13296                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13297                                new BroadcastReceiver() {
13298                                    @Override
13299                                    public void onReceive(Context context, Intent intent) {
13300                                        final Message msg = mHandler
13301                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13302                                        msg.arg1 = verificationId;
13303                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13304                                    }
13305                                }, null, 0, null, null);
13306
13307                        /*
13308                         * We don't want the copy to proceed until verification
13309                         * succeeds, so null out this field.
13310                         */
13311                        mArgs = null;
13312                    }
13313                } else {
13314                    /*
13315                     * No package verification is enabled, so immediately start
13316                     * the remote call to initiate copy using temporary file.
13317                     */
13318                    ret = args.copyApk(mContainerService, true);
13319                }
13320            }
13321
13322            mRet = ret;
13323        }
13324
13325        @Override
13326        void handleReturnCode() {
13327            // If mArgs is null, then MCS couldn't be reached. When it
13328            // reconnects, it will try again to install. At that point, this
13329            // will succeed.
13330            if (mArgs != null) {
13331                processPendingInstall(mArgs, mRet);
13332            }
13333        }
13334
13335        @Override
13336        void handleServiceError() {
13337            mArgs = createInstallArgs(this);
13338            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13339        }
13340
13341        public boolean isForwardLocked() {
13342            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13343        }
13344    }
13345
13346    /**
13347     * Used during creation of InstallArgs
13348     *
13349     * @param installFlags package installation flags
13350     * @return true if should be installed on external storage
13351     */
13352    private static boolean installOnExternalAsec(int installFlags) {
13353        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13354            return false;
13355        }
13356        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13357            return true;
13358        }
13359        return false;
13360    }
13361
13362    /**
13363     * Used during creation of InstallArgs
13364     *
13365     * @param installFlags package installation flags
13366     * @return true if should be installed as forward locked
13367     */
13368    private static boolean installForwardLocked(int installFlags) {
13369        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13370    }
13371
13372    private InstallArgs createInstallArgs(InstallParams params) {
13373        if (params.move != null) {
13374            return new MoveInstallArgs(params);
13375        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13376            return new AsecInstallArgs(params);
13377        } else {
13378            return new FileInstallArgs(params);
13379        }
13380    }
13381
13382    /**
13383     * Create args that describe an existing installed package. Typically used
13384     * when cleaning up old installs, or used as a move source.
13385     */
13386    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13387            String resourcePath, String[] instructionSets) {
13388        final boolean isInAsec;
13389        if (installOnExternalAsec(installFlags)) {
13390            /* Apps on SD card are always in ASEC containers. */
13391            isInAsec = true;
13392        } else if (installForwardLocked(installFlags)
13393                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13394            /*
13395             * Forward-locked apps are only in ASEC containers if they're the
13396             * new style
13397             */
13398            isInAsec = true;
13399        } else {
13400            isInAsec = false;
13401        }
13402
13403        if (isInAsec) {
13404            return new AsecInstallArgs(codePath, instructionSets,
13405                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13406        } else {
13407            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13408        }
13409    }
13410
13411    static abstract class InstallArgs {
13412        /** @see InstallParams#origin */
13413        final OriginInfo origin;
13414        /** @see InstallParams#move */
13415        final MoveInfo move;
13416
13417        final IPackageInstallObserver2 observer;
13418        // Always refers to PackageManager flags only
13419        final int installFlags;
13420        final String installerPackageName;
13421        final String volumeUuid;
13422        final UserHandle user;
13423        final String abiOverride;
13424        final String[] installGrantPermissions;
13425        /** If non-null, drop an async trace when the install completes */
13426        final String traceMethod;
13427        final int traceCookie;
13428        final Certificate[][] certificates;
13429
13430        // The list of instruction sets supported by this app. This is currently
13431        // only used during the rmdex() phase to clean up resources. We can get rid of this
13432        // if we move dex files under the common app path.
13433        /* nullable */ String[] instructionSets;
13434
13435        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13436                int installFlags, String installerPackageName, String volumeUuid,
13437                UserHandle user, String[] instructionSets,
13438                String abiOverride, String[] installGrantPermissions,
13439                String traceMethod, int traceCookie, Certificate[][] certificates) {
13440            this.origin = origin;
13441            this.move = move;
13442            this.installFlags = installFlags;
13443            this.observer = observer;
13444            this.installerPackageName = installerPackageName;
13445            this.volumeUuid = volumeUuid;
13446            this.user = user;
13447            this.instructionSets = instructionSets;
13448            this.abiOverride = abiOverride;
13449            this.installGrantPermissions = installGrantPermissions;
13450            this.traceMethod = traceMethod;
13451            this.traceCookie = traceCookie;
13452            this.certificates = certificates;
13453        }
13454
13455        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13456        abstract int doPreInstall(int status);
13457
13458        /**
13459         * Rename package into final resting place. All paths on the given
13460         * scanned package should be updated to reflect the rename.
13461         */
13462        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13463        abstract int doPostInstall(int status, int uid);
13464
13465        /** @see PackageSettingBase#codePathString */
13466        abstract String getCodePath();
13467        /** @see PackageSettingBase#resourcePathString */
13468        abstract String getResourcePath();
13469
13470        // Need installer lock especially for dex file removal.
13471        abstract void cleanUpResourcesLI();
13472        abstract boolean doPostDeleteLI(boolean delete);
13473
13474        /**
13475         * Called before the source arguments are copied. This is used mostly
13476         * for MoveParams when it needs to read the source file to put it in the
13477         * destination.
13478         */
13479        int doPreCopy() {
13480            return PackageManager.INSTALL_SUCCEEDED;
13481        }
13482
13483        /**
13484         * Called after the source arguments are copied. This is used mostly for
13485         * MoveParams when it needs to read the source file to put it in the
13486         * destination.
13487         */
13488        int doPostCopy(int uid) {
13489            return PackageManager.INSTALL_SUCCEEDED;
13490        }
13491
13492        protected boolean isFwdLocked() {
13493            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13494        }
13495
13496        protected boolean isExternalAsec() {
13497            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13498        }
13499
13500        protected boolean isEphemeral() {
13501            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13502        }
13503
13504        UserHandle getUser() {
13505            return user;
13506        }
13507    }
13508
13509    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13510        if (!allCodePaths.isEmpty()) {
13511            if (instructionSets == null) {
13512                throw new IllegalStateException("instructionSet == null");
13513            }
13514            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13515            for (String codePath : allCodePaths) {
13516                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13517                    try {
13518                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13519                    } catch (InstallerException ignored) {
13520                    }
13521                }
13522            }
13523        }
13524    }
13525
13526    /**
13527     * Logic to handle installation of non-ASEC applications, including copying
13528     * and renaming logic.
13529     */
13530    class FileInstallArgs extends InstallArgs {
13531        private File codeFile;
13532        private File resourceFile;
13533
13534        // Example topology:
13535        // /data/app/com.example/base.apk
13536        // /data/app/com.example/split_foo.apk
13537        // /data/app/com.example/lib/arm/libfoo.so
13538        // /data/app/com.example/lib/arm64/libfoo.so
13539        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13540
13541        /** New install */
13542        FileInstallArgs(InstallParams params) {
13543            super(params.origin, params.move, params.observer, params.installFlags,
13544                    params.installerPackageName, params.volumeUuid,
13545                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13546                    params.grantedRuntimePermissions,
13547                    params.traceMethod, params.traceCookie, params.certificates);
13548            if (isFwdLocked()) {
13549                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13550            }
13551        }
13552
13553        /** Existing install */
13554        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13555            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13556                    null, null, null, 0, null /*certificates*/);
13557            this.codeFile = (codePath != null) ? new File(codePath) : null;
13558            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13559        }
13560
13561        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13562            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13563            try {
13564                return doCopyApk(imcs, temp);
13565            } finally {
13566                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13567            }
13568        }
13569
13570        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13571            if (origin.staged) {
13572                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13573                codeFile = origin.file;
13574                resourceFile = origin.file;
13575                return PackageManager.INSTALL_SUCCEEDED;
13576            }
13577
13578            try {
13579                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13580                final File tempDir =
13581                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13582                codeFile = tempDir;
13583                resourceFile = tempDir;
13584            } catch (IOException e) {
13585                Slog.w(TAG, "Failed to create copy file: " + e);
13586                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13587            }
13588
13589            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13590                @Override
13591                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13592                    if (!FileUtils.isValidExtFilename(name)) {
13593                        throw new IllegalArgumentException("Invalid filename: " + name);
13594                    }
13595                    try {
13596                        final File file = new File(codeFile, name);
13597                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13598                                O_RDWR | O_CREAT, 0644);
13599                        Os.chmod(file.getAbsolutePath(), 0644);
13600                        return new ParcelFileDescriptor(fd);
13601                    } catch (ErrnoException e) {
13602                        throw new RemoteException("Failed to open: " + e.getMessage());
13603                    }
13604                }
13605            };
13606
13607            int ret = PackageManager.INSTALL_SUCCEEDED;
13608            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13609            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13610                Slog.e(TAG, "Failed to copy package");
13611                return ret;
13612            }
13613
13614            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13615            NativeLibraryHelper.Handle handle = null;
13616            try {
13617                handle = NativeLibraryHelper.Handle.create(codeFile);
13618                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13619                        abiOverride);
13620            } catch (IOException e) {
13621                Slog.e(TAG, "Copying native libraries failed", e);
13622                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13623            } finally {
13624                IoUtils.closeQuietly(handle);
13625            }
13626
13627            return ret;
13628        }
13629
13630        int doPreInstall(int status) {
13631            if (status != PackageManager.INSTALL_SUCCEEDED) {
13632                cleanUp();
13633            }
13634            return status;
13635        }
13636
13637        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13638            if (status != PackageManager.INSTALL_SUCCEEDED) {
13639                cleanUp();
13640                return false;
13641            }
13642
13643            final File targetDir = codeFile.getParentFile();
13644            final File beforeCodeFile = codeFile;
13645            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13646
13647            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13648            try {
13649                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13650            } catch (ErrnoException e) {
13651                Slog.w(TAG, "Failed to rename", e);
13652                return false;
13653            }
13654
13655            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13656                Slog.w(TAG, "Failed to restorecon");
13657                return false;
13658            }
13659
13660            // Reflect the rename internally
13661            codeFile = afterCodeFile;
13662            resourceFile = afterCodeFile;
13663
13664            // Reflect the rename in scanned details
13665            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13666            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13667                    afterCodeFile, pkg.baseCodePath));
13668            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13669                    afterCodeFile, pkg.splitCodePaths));
13670
13671            // Reflect the rename in app info
13672            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13673            pkg.setApplicationInfoCodePath(pkg.codePath);
13674            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13675            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13676            pkg.setApplicationInfoResourcePath(pkg.codePath);
13677            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13678            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13679
13680            return true;
13681        }
13682
13683        int doPostInstall(int status, int uid) {
13684            if (status != PackageManager.INSTALL_SUCCEEDED) {
13685                cleanUp();
13686            }
13687            return status;
13688        }
13689
13690        @Override
13691        String getCodePath() {
13692            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13693        }
13694
13695        @Override
13696        String getResourcePath() {
13697            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13698        }
13699
13700        private boolean cleanUp() {
13701            if (codeFile == null || !codeFile.exists()) {
13702                return false;
13703            }
13704
13705            removeCodePathLI(codeFile);
13706
13707            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13708                resourceFile.delete();
13709            }
13710
13711            return true;
13712        }
13713
13714        void cleanUpResourcesLI() {
13715            // Try enumerating all code paths before deleting
13716            List<String> allCodePaths = Collections.EMPTY_LIST;
13717            if (codeFile != null && codeFile.exists()) {
13718                try {
13719                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13720                    allCodePaths = pkg.getAllCodePaths();
13721                } catch (PackageParserException e) {
13722                    // Ignored; we tried our best
13723                }
13724            }
13725
13726            cleanUp();
13727            removeDexFiles(allCodePaths, instructionSets);
13728        }
13729
13730        boolean doPostDeleteLI(boolean delete) {
13731            // XXX err, shouldn't we respect the delete flag?
13732            cleanUpResourcesLI();
13733            return true;
13734        }
13735    }
13736
13737    private boolean isAsecExternal(String cid) {
13738        final String asecPath = PackageHelper.getSdFilesystem(cid);
13739        return !asecPath.startsWith(mAsecInternalPath);
13740    }
13741
13742    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13743            PackageManagerException {
13744        if (copyRet < 0) {
13745            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13746                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13747                throw new PackageManagerException(copyRet, message);
13748            }
13749        }
13750    }
13751
13752    /**
13753     * Extract the MountService "container ID" from the full code path of an
13754     * .apk.
13755     */
13756    static String cidFromCodePath(String fullCodePath) {
13757        int eidx = fullCodePath.lastIndexOf("/");
13758        String subStr1 = fullCodePath.substring(0, eidx);
13759        int sidx = subStr1.lastIndexOf("/");
13760        return subStr1.substring(sidx+1, eidx);
13761    }
13762
13763    /**
13764     * Logic to handle installation of ASEC applications, including copying and
13765     * renaming logic.
13766     */
13767    class AsecInstallArgs extends InstallArgs {
13768        static final String RES_FILE_NAME = "pkg.apk";
13769        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13770
13771        String cid;
13772        String packagePath;
13773        String resourcePath;
13774
13775        /** New install */
13776        AsecInstallArgs(InstallParams params) {
13777            super(params.origin, params.move, params.observer, params.installFlags,
13778                    params.installerPackageName, params.volumeUuid,
13779                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13780                    params.grantedRuntimePermissions,
13781                    params.traceMethod, params.traceCookie, params.certificates);
13782        }
13783
13784        /** Existing install */
13785        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13786                        boolean isExternal, boolean isForwardLocked) {
13787            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13788              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13789                    instructionSets, null, null, null, 0, null /*certificates*/);
13790            // Hackily pretend we're still looking at a full code path
13791            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13792                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13793            }
13794
13795            // Extract cid from fullCodePath
13796            int eidx = fullCodePath.lastIndexOf("/");
13797            String subStr1 = fullCodePath.substring(0, eidx);
13798            int sidx = subStr1.lastIndexOf("/");
13799            cid = subStr1.substring(sidx+1, eidx);
13800            setMountPath(subStr1);
13801        }
13802
13803        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13804            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13805              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13806                    instructionSets, null, null, null, 0, null /*certificates*/);
13807            this.cid = cid;
13808            setMountPath(PackageHelper.getSdDir(cid));
13809        }
13810
13811        void createCopyFile() {
13812            cid = mInstallerService.allocateExternalStageCidLegacy();
13813        }
13814
13815        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13816            if (origin.staged && origin.cid != null) {
13817                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13818                cid = origin.cid;
13819                setMountPath(PackageHelper.getSdDir(cid));
13820                return PackageManager.INSTALL_SUCCEEDED;
13821            }
13822
13823            if (temp) {
13824                createCopyFile();
13825            } else {
13826                /*
13827                 * Pre-emptively destroy the container since it's destroyed if
13828                 * copying fails due to it existing anyway.
13829                 */
13830                PackageHelper.destroySdDir(cid);
13831            }
13832
13833            final String newMountPath = imcs.copyPackageToContainer(
13834                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13835                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13836
13837            if (newMountPath != null) {
13838                setMountPath(newMountPath);
13839                return PackageManager.INSTALL_SUCCEEDED;
13840            } else {
13841                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13842            }
13843        }
13844
13845        @Override
13846        String getCodePath() {
13847            return packagePath;
13848        }
13849
13850        @Override
13851        String getResourcePath() {
13852            return resourcePath;
13853        }
13854
13855        int doPreInstall(int status) {
13856            if (status != PackageManager.INSTALL_SUCCEEDED) {
13857                // Destroy container
13858                PackageHelper.destroySdDir(cid);
13859            } else {
13860                boolean mounted = PackageHelper.isContainerMounted(cid);
13861                if (!mounted) {
13862                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13863                            Process.SYSTEM_UID);
13864                    if (newMountPath != null) {
13865                        setMountPath(newMountPath);
13866                    } else {
13867                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13868                    }
13869                }
13870            }
13871            return status;
13872        }
13873
13874        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13875            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13876            String newMountPath = null;
13877            if (PackageHelper.isContainerMounted(cid)) {
13878                // Unmount the container
13879                if (!PackageHelper.unMountSdDir(cid)) {
13880                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13881                    return false;
13882                }
13883            }
13884            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13885                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13886                        " which might be stale. Will try to clean up.");
13887                // Clean up the stale container and proceed to recreate.
13888                if (!PackageHelper.destroySdDir(newCacheId)) {
13889                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13890                    return false;
13891                }
13892                // Successfully cleaned up stale container. Try to rename again.
13893                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13894                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13895                            + " inspite of cleaning it up.");
13896                    return false;
13897                }
13898            }
13899            if (!PackageHelper.isContainerMounted(newCacheId)) {
13900                Slog.w(TAG, "Mounting container " + newCacheId);
13901                newMountPath = PackageHelper.mountSdDir(newCacheId,
13902                        getEncryptKey(), Process.SYSTEM_UID);
13903            } else {
13904                newMountPath = PackageHelper.getSdDir(newCacheId);
13905            }
13906            if (newMountPath == null) {
13907                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13908                return false;
13909            }
13910            Log.i(TAG, "Succesfully renamed " + cid +
13911                    " to " + newCacheId +
13912                    " at new path: " + newMountPath);
13913            cid = newCacheId;
13914
13915            final File beforeCodeFile = new File(packagePath);
13916            setMountPath(newMountPath);
13917            final File afterCodeFile = new File(packagePath);
13918
13919            // Reflect the rename in scanned details
13920            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13921            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13922                    afterCodeFile, pkg.baseCodePath));
13923            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13924                    afterCodeFile, pkg.splitCodePaths));
13925
13926            // Reflect the rename in app info
13927            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13928            pkg.setApplicationInfoCodePath(pkg.codePath);
13929            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13930            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13931            pkg.setApplicationInfoResourcePath(pkg.codePath);
13932            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13933            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13934
13935            return true;
13936        }
13937
13938        private void setMountPath(String mountPath) {
13939            final File mountFile = new File(mountPath);
13940
13941            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13942            if (monolithicFile.exists()) {
13943                packagePath = monolithicFile.getAbsolutePath();
13944                if (isFwdLocked()) {
13945                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13946                } else {
13947                    resourcePath = packagePath;
13948                }
13949            } else {
13950                packagePath = mountFile.getAbsolutePath();
13951                resourcePath = packagePath;
13952            }
13953        }
13954
13955        int doPostInstall(int status, int uid) {
13956            if (status != PackageManager.INSTALL_SUCCEEDED) {
13957                cleanUp();
13958            } else {
13959                final int groupOwner;
13960                final String protectedFile;
13961                if (isFwdLocked()) {
13962                    groupOwner = UserHandle.getSharedAppGid(uid);
13963                    protectedFile = RES_FILE_NAME;
13964                } else {
13965                    groupOwner = -1;
13966                    protectedFile = null;
13967                }
13968
13969                if (uid < Process.FIRST_APPLICATION_UID
13970                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13971                    Slog.e(TAG, "Failed to finalize " + cid);
13972                    PackageHelper.destroySdDir(cid);
13973                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13974                }
13975
13976                boolean mounted = PackageHelper.isContainerMounted(cid);
13977                if (!mounted) {
13978                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13979                }
13980            }
13981            return status;
13982        }
13983
13984        private void cleanUp() {
13985            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13986
13987            // Destroy secure container
13988            PackageHelper.destroySdDir(cid);
13989        }
13990
13991        private List<String> getAllCodePaths() {
13992            final File codeFile = new File(getCodePath());
13993            if (codeFile != null && codeFile.exists()) {
13994                try {
13995                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13996                    return pkg.getAllCodePaths();
13997                } catch (PackageParserException e) {
13998                    // Ignored; we tried our best
13999                }
14000            }
14001            return Collections.EMPTY_LIST;
14002        }
14003
14004        void cleanUpResourcesLI() {
14005            // Enumerate all code paths before deleting
14006            cleanUpResourcesLI(getAllCodePaths());
14007        }
14008
14009        private void cleanUpResourcesLI(List<String> allCodePaths) {
14010            cleanUp();
14011            removeDexFiles(allCodePaths, instructionSets);
14012        }
14013
14014        String getPackageName() {
14015            return getAsecPackageName(cid);
14016        }
14017
14018        boolean doPostDeleteLI(boolean delete) {
14019            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14020            final List<String> allCodePaths = getAllCodePaths();
14021            boolean mounted = PackageHelper.isContainerMounted(cid);
14022            if (mounted) {
14023                // Unmount first
14024                if (PackageHelper.unMountSdDir(cid)) {
14025                    mounted = false;
14026                }
14027            }
14028            if (!mounted && delete) {
14029                cleanUpResourcesLI(allCodePaths);
14030            }
14031            return !mounted;
14032        }
14033
14034        @Override
14035        int doPreCopy() {
14036            if (isFwdLocked()) {
14037                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14038                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14039                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14040                }
14041            }
14042
14043            return PackageManager.INSTALL_SUCCEEDED;
14044        }
14045
14046        @Override
14047        int doPostCopy(int uid) {
14048            if (isFwdLocked()) {
14049                if (uid < Process.FIRST_APPLICATION_UID
14050                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14051                                RES_FILE_NAME)) {
14052                    Slog.e(TAG, "Failed to finalize " + cid);
14053                    PackageHelper.destroySdDir(cid);
14054                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14055                }
14056            }
14057
14058            return PackageManager.INSTALL_SUCCEEDED;
14059        }
14060    }
14061
14062    /**
14063     * Logic to handle movement of existing installed applications.
14064     */
14065    class MoveInstallArgs extends InstallArgs {
14066        private File codeFile;
14067        private File resourceFile;
14068
14069        /** New install */
14070        MoveInstallArgs(InstallParams params) {
14071            super(params.origin, params.move, params.observer, params.installFlags,
14072                    params.installerPackageName, params.volumeUuid,
14073                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14074                    params.grantedRuntimePermissions,
14075                    params.traceMethod, params.traceCookie, params.certificates);
14076        }
14077
14078        int copyApk(IMediaContainerService imcs, boolean temp) {
14079            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14080                    + move.fromUuid + " to " + move.toUuid);
14081            synchronized (mInstaller) {
14082                try {
14083                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14084                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14085                } catch (InstallerException e) {
14086                    Slog.w(TAG, "Failed to move app", e);
14087                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14088                }
14089            }
14090
14091            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14092            resourceFile = codeFile;
14093            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14094
14095            return PackageManager.INSTALL_SUCCEEDED;
14096        }
14097
14098        int doPreInstall(int status) {
14099            if (status != PackageManager.INSTALL_SUCCEEDED) {
14100                cleanUp(move.toUuid);
14101            }
14102            return status;
14103        }
14104
14105        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14106            if (status != PackageManager.INSTALL_SUCCEEDED) {
14107                cleanUp(move.toUuid);
14108                return false;
14109            }
14110
14111            // Reflect the move in app info
14112            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14113            pkg.setApplicationInfoCodePath(pkg.codePath);
14114            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14115            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14116            pkg.setApplicationInfoResourcePath(pkg.codePath);
14117            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14118            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14119
14120            return true;
14121        }
14122
14123        int doPostInstall(int status, int uid) {
14124            if (status == PackageManager.INSTALL_SUCCEEDED) {
14125                cleanUp(move.fromUuid);
14126            } else {
14127                cleanUp(move.toUuid);
14128            }
14129            return status;
14130        }
14131
14132        @Override
14133        String getCodePath() {
14134            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14135        }
14136
14137        @Override
14138        String getResourcePath() {
14139            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14140        }
14141
14142        private boolean cleanUp(String volumeUuid) {
14143            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14144                    move.dataAppName);
14145            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14146            final int[] userIds = sUserManager.getUserIds();
14147            synchronized (mInstallLock) {
14148                // Clean up both app data and code
14149                // All package moves are frozen until finished
14150                for (int userId : userIds) {
14151                    try {
14152                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14153                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14154                    } catch (InstallerException e) {
14155                        Slog.w(TAG, String.valueOf(e));
14156                    }
14157                }
14158                removeCodePathLI(codeFile);
14159            }
14160            return true;
14161        }
14162
14163        void cleanUpResourcesLI() {
14164            throw new UnsupportedOperationException();
14165        }
14166
14167        boolean doPostDeleteLI(boolean delete) {
14168            throw new UnsupportedOperationException();
14169        }
14170    }
14171
14172    static String getAsecPackageName(String packageCid) {
14173        int idx = packageCid.lastIndexOf("-");
14174        if (idx == -1) {
14175            return packageCid;
14176        }
14177        return packageCid.substring(0, idx);
14178    }
14179
14180    // Utility method used to create code paths based on package name and available index.
14181    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14182        String idxStr = "";
14183        int idx = 1;
14184        // Fall back to default value of idx=1 if prefix is not
14185        // part of oldCodePath
14186        if (oldCodePath != null) {
14187            String subStr = oldCodePath;
14188            // Drop the suffix right away
14189            if (suffix != null && subStr.endsWith(suffix)) {
14190                subStr = subStr.substring(0, subStr.length() - suffix.length());
14191            }
14192            // If oldCodePath already contains prefix find out the
14193            // ending index to either increment or decrement.
14194            int sidx = subStr.lastIndexOf(prefix);
14195            if (sidx != -1) {
14196                subStr = subStr.substring(sidx + prefix.length());
14197                if (subStr != null) {
14198                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14199                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14200                    }
14201                    try {
14202                        idx = Integer.parseInt(subStr);
14203                        if (idx <= 1) {
14204                            idx++;
14205                        } else {
14206                            idx--;
14207                        }
14208                    } catch(NumberFormatException e) {
14209                    }
14210                }
14211            }
14212        }
14213        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14214        return prefix + idxStr;
14215    }
14216
14217    private File getNextCodePath(File targetDir, String packageName) {
14218        int suffix = 1;
14219        File result;
14220        do {
14221            result = new File(targetDir, packageName + "-" + suffix);
14222            suffix++;
14223        } while (result.exists());
14224        return result;
14225    }
14226
14227    // Utility method that returns the relative package path with respect
14228    // to the installation directory. Like say for /data/data/com.test-1.apk
14229    // string com.test-1 is returned.
14230    static String deriveCodePathName(String codePath) {
14231        if (codePath == null) {
14232            return null;
14233        }
14234        final File codeFile = new File(codePath);
14235        final String name = codeFile.getName();
14236        if (codeFile.isDirectory()) {
14237            return name;
14238        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14239            final int lastDot = name.lastIndexOf('.');
14240            return name.substring(0, lastDot);
14241        } else {
14242            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14243            return null;
14244        }
14245    }
14246
14247    static class PackageInstalledInfo {
14248        String name;
14249        int uid;
14250        // The set of users that originally had this package installed.
14251        int[] origUsers;
14252        // The set of users that now have this package installed.
14253        int[] newUsers;
14254        PackageParser.Package pkg;
14255        int returnCode;
14256        String returnMsg;
14257        PackageRemovedInfo removedInfo;
14258        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14259
14260        public void setError(int code, String msg) {
14261            setReturnCode(code);
14262            setReturnMessage(msg);
14263            Slog.w(TAG, msg);
14264        }
14265
14266        public void setError(String msg, PackageParserException e) {
14267            setReturnCode(e.error);
14268            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14269            Slog.w(TAG, msg, e);
14270        }
14271
14272        public void setError(String msg, PackageManagerException e) {
14273            returnCode = e.error;
14274            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14275            Slog.w(TAG, msg, e);
14276        }
14277
14278        public void setReturnCode(int returnCode) {
14279            this.returnCode = returnCode;
14280            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14281            for (int i = 0; i < childCount; i++) {
14282                addedChildPackages.valueAt(i).returnCode = returnCode;
14283            }
14284        }
14285
14286        private void setReturnMessage(String returnMsg) {
14287            this.returnMsg = returnMsg;
14288            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14289            for (int i = 0; i < childCount; i++) {
14290                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14291            }
14292        }
14293
14294        // In some error cases we want to convey more info back to the observer
14295        String origPackage;
14296        String origPermission;
14297    }
14298
14299    /*
14300     * Install a non-existing package.
14301     */
14302    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14303            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14304            PackageInstalledInfo res) {
14305        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14306
14307        // Remember this for later, in case we need to rollback this install
14308        String pkgName = pkg.packageName;
14309
14310        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14311
14312        synchronized(mPackages) {
14313            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14314            if (renamedPackage != null) {
14315                // A package with the same name is already installed, though
14316                // it has been renamed to an older name.  The package we
14317                // are trying to install should be installed as an update to
14318                // the existing one, but that has not been requested, so bail.
14319                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14320                        + " without first uninstalling package running as "
14321                        + renamedPackage);
14322                return;
14323            }
14324            if (mPackages.containsKey(pkgName)) {
14325                // Don't allow installation over an existing package with the same name.
14326                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14327                        + " without first uninstalling.");
14328                return;
14329            }
14330        }
14331
14332        try {
14333            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14334                    System.currentTimeMillis(), user);
14335
14336            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14337
14338            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14339                prepareAppDataAfterInstallLIF(newPackage);
14340
14341            } else {
14342                // Remove package from internal structures, but keep around any
14343                // data that might have already existed
14344                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14345                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14346            }
14347        } catch (PackageManagerException e) {
14348            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14349        }
14350
14351        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14352    }
14353
14354    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14355        // Can't rotate keys during boot or if sharedUser.
14356        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14357                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14358            return false;
14359        }
14360        // app is using upgradeKeySets; make sure all are valid
14361        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14362        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14363        for (int i = 0; i < upgradeKeySets.length; i++) {
14364            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14365                Slog.wtf(TAG, "Package "
14366                         + (oldPs.name != null ? oldPs.name : "<null>")
14367                         + " contains upgrade-key-set reference to unknown key-set: "
14368                         + upgradeKeySets[i]
14369                         + " reverting to signatures check.");
14370                return false;
14371            }
14372        }
14373        return true;
14374    }
14375
14376    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14377        // Upgrade keysets are being used.  Determine if new package has a superset of the
14378        // required keys.
14379        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14380        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14381        for (int i = 0; i < upgradeKeySets.length; i++) {
14382            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14383            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14384                return true;
14385            }
14386        }
14387        return false;
14388    }
14389
14390    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14391        try (DigestInputStream digestStream =
14392                new DigestInputStream(new FileInputStream(file), digest)) {
14393            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14394        }
14395    }
14396
14397    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14398            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14399        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14400
14401        final PackageParser.Package oldPackage;
14402        final String pkgName = pkg.packageName;
14403        final int[] allUsers;
14404        final int[] installedUsers;
14405
14406        synchronized(mPackages) {
14407            oldPackage = mPackages.get(pkgName);
14408            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14409
14410            // don't allow upgrade to target a release SDK from a pre-release SDK
14411            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14412                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14413            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14414                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14415            if (oldTargetsPreRelease
14416                    && !newTargetsPreRelease
14417                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14418                Slog.w(TAG, "Can't install package targeting released sdk");
14419                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14420                return;
14421            }
14422
14423            // don't allow an upgrade from full to ephemeral
14424            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14425            if (isEphemeral && !oldIsEphemeral) {
14426                // can't downgrade from full to ephemeral
14427                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14428                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14429                return;
14430            }
14431
14432            // verify signatures are valid
14433            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14434            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14435                if (!checkUpgradeKeySetLP(ps, pkg)) {
14436                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14437                            "New package not signed by keys specified by upgrade-keysets: "
14438                                    + pkgName);
14439                    return;
14440                }
14441            } else {
14442                // default to original signature matching
14443                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14444                        != PackageManager.SIGNATURE_MATCH) {
14445                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14446                            "New package has a different signature: " + pkgName);
14447                    return;
14448                }
14449            }
14450
14451            // don't allow a system upgrade unless the upgrade hash matches
14452            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14453                byte[] digestBytes = null;
14454                try {
14455                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14456                    updateDigest(digest, new File(pkg.baseCodePath));
14457                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14458                        for (String path : pkg.splitCodePaths) {
14459                            updateDigest(digest, new File(path));
14460                        }
14461                    }
14462                    digestBytes = digest.digest();
14463                } catch (NoSuchAlgorithmException | IOException e) {
14464                    res.setError(INSTALL_FAILED_INVALID_APK,
14465                            "Could not compute hash: " + pkgName);
14466                    return;
14467                }
14468                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14469                    res.setError(INSTALL_FAILED_INVALID_APK,
14470                            "New package fails restrict-update check: " + pkgName);
14471                    return;
14472                }
14473                // retain upgrade restriction
14474                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14475            }
14476
14477            // Check for shared user id changes
14478            String invalidPackageName =
14479                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14480            if (invalidPackageName != null) {
14481                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14482                        "Package " + invalidPackageName + " tried to change user "
14483                                + oldPackage.mSharedUserId);
14484                return;
14485            }
14486
14487            // In case of rollback, remember per-user/profile install state
14488            allUsers = sUserManager.getUserIds();
14489            installedUsers = ps.queryInstalledUsers(allUsers, true);
14490        }
14491
14492        // Update what is removed
14493        res.removedInfo = new PackageRemovedInfo();
14494        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14495        res.removedInfo.removedPackage = oldPackage.packageName;
14496        res.removedInfo.isUpdate = true;
14497        res.removedInfo.origUsers = installedUsers;
14498        final int childCount = (oldPackage.childPackages != null)
14499                ? oldPackage.childPackages.size() : 0;
14500        for (int i = 0; i < childCount; i++) {
14501            boolean childPackageUpdated = false;
14502            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14503            if (res.addedChildPackages != null) {
14504                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14505                if (childRes != null) {
14506                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14507                    childRes.removedInfo.removedPackage = childPkg.packageName;
14508                    childRes.removedInfo.isUpdate = true;
14509                    childPackageUpdated = true;
14510                }
14511            }
14512            if (!childPackageUpdated) {
14513                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14514                childRemovedRes.removedPackage = childPkg.packageName;
14515                childRemovedRes.isUpdate = false;
14516                childRemovedRes.dataRemoved = true;
14517                synchronized (mPackages) {
14518                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14519                    if (childPs != null) {
14520                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14521                    }
14522                }
14523                if (res.removedInfo.removedChildPackages == null) {
14524                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14525                }
14526                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14527            }
14528        }
14529
14530        boolean sysPkg = (isSystemApp(oldPackage));
14531        if (sysPkg) {
14532            // Set the system/privileged flags as needed
14533            final boolean privileged =
14534                    (oldPackage.applicationInfo.privateFlags
14535                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14536            final int systemPolicyFlags = policyFlags
14537                    | PackageParser.PARSE_IS_SYSTEM
14538                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14539
14540            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14541                    user, allUsers, installerPackageName, res);
14542        } else {
14543            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14544                    user, allUsers, installerPackageName, res);
14545        }
14546    }
14547
14548    public List<String> getPreviousCodePaths(String packageName) {
14549        final PackageSetting ps = mSettings.mPackages.get(packageName);
14550        final List<String> result = new ArrayList<String>();
14551        if (ps != null && ps.oldCodePaths != null) {
14552            result.addAll(ps.oldCodePaths);
14553        }
14554        return result;
14555    }
14556
14557    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14558            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14559            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14560        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14561                + deletedPackage);
14562
14563        String pkgName = deletedPackage.packageName;
14564        boolean deletedPkg = true;
14565        boolean addedPkg = false;
14566        boolean updatedSettings = false;
14567        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14568        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14569                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14570
14571        final long origUpdateTime = (pkg.mExtras != null)
14572                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14573
14574        // First delete the existing package while retaining the data directory
14575        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14576                res.removedInfo, true, pkg)) {
14577            // If the existing package wasn't successfully deleted
14578            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14579            deletedPkg = false;
14580        } else {
14581            // Successfully deleted the old package; proceed with replace.
14582
14583            // If deleted package lived in a container, give users a chance to
14584            // relinquish resources before killing.
14585            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14586                if (DEBUG_INSTALL) {
14587                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14588                }
14589                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14590                final ArrayList<String> pkgList = new ArrayList<String>(1);
14591                pkgList.add(deletedPackage.applicationInfo.packageName);
14592                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14593            }
14594
14595            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14596                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14597            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14598
14599            try {
14600                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14601                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14602                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14603
14604                // Update the in-memory copy of the previous code paths.
14605                PackageSetting ps = mSettings.mPackages.get(pkgName);
14606                if (!killApp) {
14607                    if (ps.oldCodePaths == null) {
14608                        ps.oldCodePaths = new ArraySet<>();
14609                    }
14610                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14611                    if (deletedPackage.splitCodePaths != null) {
14612                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14613                    }
14614                } else {
14615                    ps.oldCodePaths = null;
14616                }
14617                if (ps.childPackageNames != null) {
14618                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14619                        final String childPkgName = ps.childPackageNames.get(i);
14620                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14621                        childPs.oldCodePaths = ps.oldCodePaths;
14622                    }
14623                }
14624                prepareAppDataAfterInstallLIF(newPackage);
14625                addedPkg = true;
14626            } catch (PackageManagerException e) {
14627                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14628            }
14629        }
14630
14631        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14632            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14633
14634            // Revert all internal state mutations and added folders for the failed install
14635            if (addedPkg) {
14636                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14637                        res.removedInfo, true, null);
14638            }
14639
14640            // Restore the old package
14641            if (deletedPkg) {
14642                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14643                File restoreFile = new File(deletedPackage.codePath);
14644                // Parse old package
14645                boolean oldExternal = isExternal(deletedPackage);
14646                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14647                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14648                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14649                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14650                try {
14651                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14652                            null);
14653                } catch (PackageManagerException e) {
14654                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14655                            + e.getMessage());
14656                    return;
14657                }
14658
14659                synchronized (mPackages) {
14660                    // Ensure the installer package name up to date
14661                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14662
14663                    // Update permissions for restored package
14664                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14665
14666                    mSettings.writeLPr();
14667                }
14668
14669                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14670            }
14671        } else {
14672            synchronized (mPackages) {
14673                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14674                if (ps != null) {
14675                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14676                    if (res.removedInfo.removedChildPackages != null) {
14677                        final int childCount = res.removedInfo.removedChildPackages.size();
14678                        // Iterate in reverse as we may modify the collection
14679                        for (int i = childCount - 1; i >= 0; i--) {
14680                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14681                            if (res.addedChildPackages.containsKey(childPackageName)) {
14682                                res.removedInfo.removedChildPackages.removeAt(i);
14683                            } else {
14684                                PackageRemovedInfo childInfo = res.removedInfo
14685                                        .removedChildPackages.valueAt(i);
14686                                childInfo.removedForAllUsers = mPackages.get(
14687                                        childInfo.removedPackage) == null;
14688                            }
14689                        }
14690                    }
14691                }
14692            }
14693        }
14694    }
14695
14696    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14697            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14698            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14699        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14700                + ", old=" + deletedPackage);
14701
14702        final boolean disabledSystem;
14703
14704        // Remove existing system package
14705        removePackageLI(deletedPackage, true);
14706
14707        synchronized (mPackages) {
14708            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14709        }
14710        if (!disabledSystem) {
14711            // We didn't need to disable the .apk as a current system package,
14712            // which means we are replacing another update that is already
14713            // installed.  We need to make sure to delete the older one's .apk.
14714            res.removedInfo.args = createInstallArgsForExisting(0,
14715                    deletedPackage.applicationInfo.getCodePath(),
14716                    deletedPackage.applicationInfo.getResourcePath(),
14717                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14718        } else {
14719            res.removedInfo.args = null;
14720        }
14721
14722        // Successfully disabled the old package. Now proceed with re-installation
14723        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14724                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14725        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14726
14727        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14728        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14729                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14730
14731        PackageParser.Package newPackage = null;
14732        try {
14733            // Add the package to the internal data structures
14734            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14735
14736            // Set the update and install times
14737            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14738            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14739                    System.currentTimeMillis());
14740
14741            // Update the package dynamic state if succeeded
14742            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14743                // Now that the install succeeded make sure we remove data
14744                // directories for any child package the update removed.
14745                final int deletedChildCount = (deletedPackage.childPackages != null)
14746                        ? deletedPackage.childPackages.size() : 0;
14747                final int newChildCount = (newPackage.childPackages != null)
14748                        ? newPackage.childPackages.size() : 0;
14749                for (int i = 0; i < deletedChildCount; i++) {
14750                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14751                    boolean childPackageDeleted = true;
14752                    for (int j = 0; j < newChildCount; j++) {
14753                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14754                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14755                            childPackageDeleted = false;
14756                            break;
14757                        }
14758                    }
14759                    if (childPackageDeleted) {
14760                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14761                                deletedChildPkg.packageName);
14762                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14763                            PackageRemovedInfo removedChildRes = res.removedInfo
14764                                    .removedChildPackages.get(deletedChildPkg.packageName);
14765                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14766                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14767                        }
14768                    }
14769                }
14770
14771                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14772                prepareAppDataAfterInstallLIF(newPackage);
14773            }
14774        } catch (PackageManagerException e) {
14775            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14776            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14777        }
14778
14779        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14780            // Re installation failed. Restore old information
14781            // Remove new pkg information
14782            if (newPackage != null) {
14783                removeInstalledPackageLI(newPackage, true);
14784            }
14785            // Add back the old system package
14786            try {
14787                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14788            } catch (PackageManagerException e) {
14789                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14790            }
14791
14792            synchronized (mPackages) {
14793                if (disabledSystem) {
14794                    enableSystemPackageLPw(deletedPackage);
14795                }
14796
14797                // Ensure the installer package name up to date
14798                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14799
14800                // Update permissions for restored package
14801                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14802
14803                mSettings.writeLPr();
14804            }
14805
14806            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14807                    + " after failed upgrade");
14808        }
14809    }
14810
14811    /**
14812     * Checks whether the parent or any of the child packages have a change shared
14813     * user. For a package to be a valid update the shred users of the parent and
14814     * the children should match. We may later support changing child shared users.
14815     * @param oldPkg The updated package.
14816     * @param newPkg The update package.
14817     * @return The shared user that change between the versions.
14818     */
14819    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14820            PackageParser.Package newPkg) {
14821        // Check parent shared user
14822        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14823            return newPkg.packageName;
14824        }
14825        // Check child shared users
14826        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14827        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14828        for (int i = 0; i < newChildCount; i++) {
14829            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14830            // If this child was present, did it have the same shared user?
14831            for (int j = 0; j < oldChildCount; j++) {
14832                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14833                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14834                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14835                    return newChildPkg.packageName;
14836                }
14837            }
14838        }
14839        return null;
14840    }
14841
14842    private void removeNativeBinariesLI(PackageSetting ps) {
14843        // Remove the lib path for the parent package
14844        if (ps != null) {
14845            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14846            // Remove the lib path for the child packages
14847            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14848            for (int i = 0; i < childCount; i++) {
14849                PackageSetting childPs = null;
14850                synchronized (mPackages) {
14851                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
14852                }
14853                if (childPs != null) {
14854                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14855                            .legacyNativeLibraryPathString);
14856                }
14857            }
14858        }
14859    }
14860
14861    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14862        // Enable the parent package
14863        mSettings.enableSystemPackageLPw(pkg.packageName);
14864        // Enable the child packages
14865        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14866        for (int i = 0; i < childCount; i++) {
14867            PackageParser.Package childPkg = pkg.childPackages.get(i);
14868            mSettings.enableSystemPackageLPw(childPkg.packageName);
14869        }
14870    }
14871
14872    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14873            PackageParser.Package newPkg) {
14874        // Disable the parent package (parent always replaced)
14875        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14876        // Disable the child packages
14877        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14878        for (int i = 0; i < childCount; i++) {
14879            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14880            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14881            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14882        }
14883        return disabled;
14884    }
14885
14886    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14887            String installerPackageName) {
14888        // Enable the parent package
14889        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
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.setInstallerPackageName(childPkg.packageName, installerPackageName);
14895        }
14896    }
14897
14898    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14899        // Collect all used permissions in the UID
14900        ArraySet<String> usedPermissions = new ArraySet<>();
14901        final int packageCount = su.packages.size();
14902        for (int i = 0; i < packageCount; i++) {
14903            PackageSetting ps = su.packages.valueAt(i);
14904            if (ps.pkg == null) {
14905                continue;
14906            }
14907            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14908            for (int j = 0; j < requestedPermCount; j++) {
14909                String permission = ps.pkg.requestedPermissions.get(j);
14910                BasePermission bp = mSettings.mPermissions.get(permission);
14911                if (bp != null) {
14912                    usedPermissions.add(permission);
14913                }
14914            }
14915        }
14916
14917        PermissionsState permissionsState = su.getPermissionsState();
14918        // Prune install permissions
14919        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14920        final int installPermCount = installPermStates.size();
14921        for (int i = installPermCount - 1; i >= 0;  i--) {
14922            PermissionState permissionState = installPermStates.get(i);
14923            if (!usedPermissions.contains(permissionState.getName())) {
14924                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14925                if (bp != null) {
14926                    permissionsState.revokeInstallPermission(bp);
14927                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14928                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14929                }
14930            }
14931        }
14932
14933        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14934
14935        // Prune runtime permissions
14936        for (int userId : allUserIds) {
14937            List<PermissionState> runtimePermStates = permissionsState
14938                    .getRuntimePermissionStates(userId);
14939            final int runtimePermCount = runtimePermStates.size();
14940            for (int i = runtimePermCount - 1; i >= 0; i--) {
14941                PermissionState permissionState = runtimePermStates.get(i);
14942                if (!usedPermissions.contains(permissionState.getName())) {
14943                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14944                    if (bp != null) {
14945                        permissionsState.revokeRuntimePermission(bp, userId);
14946                        permissionsState.updatePermissionFlags(bp, userId,
14947                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14948                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14949                                runtimePermissionChangedUserIds, userId);
14950                    }
14951                }
14952            }
14953        }
14954
14955        return runtimePermissionChangedUserIds;
14956    }
14957
14958    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14959            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14960        // Update the parent package setting
14961        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14962                res, user);
14963        // Update the child packages setting
14964        final int childCount = (newPackage.childPackages != null)
14965                ? newPackage.childPackages.size() : 0;
14966        for (int i = 0; i < childCount; i++) {
14967            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14968            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14969            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14970                    childRes.origUsers, childRes, user);
14971        }
14972    }
14973
14974    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14975            String installerPackageName, int[] allUsers, int[] installedForUsers,
14976            PackageInstalledInfo res, UserHandle user) {
14977        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14978
14979        String pkgName = newPackage.packageName;
14980        synchronized (mPackages) {
14981            //write settings. the installStatus will be incomplete at this stage.
14982            //note that the new package setting would have already been
14983            //added to mPackages. It hasn't been persisted yet.
14984            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14985            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14986            mSettings.writeLPr();
14987            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14988        }
14989
14990        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14991        synchronized (mPackages) {
14992            updatePermissionsLPw(newPackage.packageName, newPackage,
14993                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14994                            ? UPDATE_PERMISSIONS_ALL : 0));
14995            // For system-bundled packages, we assume that installing an upgraded version
14996            // of the package implies that the user actually wants to run that new code,
14997            // so we enable the package.
14998            PackageSetting ps = mSettings.mPackages.get(pkgName);
14999            final int userId = user.getIdentifier();
15000            if (ps != null) {
15001                if (isSystemApp(newPackage)) {
15002                    if (DEBUG_INSTALL) {
15003                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15004                    }
15005                    // Enable system package for requested users
15006                    if (res.origUsers != null) {
15007                        for (int origUserId : res.origUsers) {
15008                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15009                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15010                                        origUserId, installerPackageName);
15011                            }
15012                        }
15013                    }
15014                    // Also convey the prior install/uninstall state
15015                    if (allUsers != null && installedForUsers != null) {
15016                        for (int currentUserId : allUsers) {
15017                            final boolean installed = ArrayUtils.contains(
15018                                    installedForUsers, currentUserId);
15019                            if (DEBUG_INSTALL) {
15020                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15021                            }
15022                            ps.setInstalled(installed, currentUserId);
15023                        }
15024                        // these install state changes will be persisted in the
15025                        // upcoming call to mSettings.writeLPr().
15026                    }
15027                }
15028                // It's implied that when a user requests installation, they want the app to be
15029                // installed and enabled.
15030                if (userId != UserHandle.USER_ALL) {
15031                    ps.setInstalled(true, userId);
15032                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15033                }
15034            }
15035            res.name = pkgName;
15036            res.uid = newPackage.applicationInfo.uid;
15037            res.pkg = newPackage;
15038            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15039            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15040            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15041            //to update install status
15042            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15043            mSettings.writeLPr();
15044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15045        }
15046
15047        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15048    }
15049
15050    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15051        try {
15052            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15053            installPackageLI(args, res);
15054        } finally {
15055            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15056        }
15057    }
15058
15059    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15060        final int installFlags = args.installFlags;
15061        final String installerPackageName = args.installerPackageName;
15062        final String volumeUuid = args.volumeUuid;
15063        final File tmpPackageFile = new File(args.getCodePath());
15064        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15065        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15066                || (args.volumeUuid != null));
15067        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15068        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15069        boolean replace = false;
15070        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15071        if (args.move != null) {
15072            // moving a complete application; perform an initial scan on the new install location
15073            scanFlags |= SCAN_INITIAL;
15074        }
15075        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15076            scanFlags |= SCAN_DONT_KILL_APP;
15077        }
15078
15079        // Result object to be returned
15080        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15081
15082        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15083
15084        // Sanity check
15085        if (ephemeral && (forwardLocked || onExternal)) {
15086            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15087                    + " external=" + onExternal);
15088            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15089            return;
15090        }
15091
15092        // Retrieve PackageSettings and parse package
15093        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15094                | PackageParser.PARSE_ENFORCE_CODE
15095                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15096                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15097                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15098                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15099        PackageParser pp = new PackageParser();
15100        pp.setSeparateProcesses(mSeparateProcesses);
15101        pp.setDisplayMetrics(mMetrics);
15102
15103        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15104        final PackageParser.Package pkg;
15105        try {
15106            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15107        } catch (PackageParserException e) {
15108            res.setError("Failed parse during installPackageLI", e);
15109            return;
15110        } finally {
15111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15112        }
15113
15114        // If we are installing a clustered package add results for the children
15115        if (pkg.childPackages != null) {
15116            synchronized (mPackages) {
15117                final int childCount = pkg.childPackages.size();
15118                for (int i = 0; i < childCount; i++) {
15119                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15120                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15121                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15122                    childRes.pkg = childPkg;
15123                    childRes.name = childPkg.packageName;
15124                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15125                    if (childPs != null) {
15126                        childRes.origUsers = childPs.queryInstalledUsers(
15127                                sUserManager.getUserIds(), true);
15128                    }
15129                    if ((mPackages.containsKey(childPkg.packageName))) {
15130                        childRes.removedInfo = new PackageRemovedInfo();
15131                        childRes.removedInfo.removedPackage = childPkg.packageName;
15132                    }
15133                    if (res.addedChildPackages == null) {
15134                        res.addedChildPackages = new ArrayMap<>();
15135                    }
15136                    res.addedChildPackages.put(childPkg.packageName, childRes);
15137                }
15138            }
15139        }
15140
15141        // If package doesn't declare API override, mark that we have an install
15142        // time CPU ABI override.
15143        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15144            pkg.cpuAbiOverride = args.abiOverride;
15145        }
15146
15147        String pkgName = res.name = pkg.packageName;
15148        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15149            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15150                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15151                return;
15152            }
15153        }
15154
15155        try {
15156            // either use what we've been given or parse directly from the APK
15157            if (args.certificates != null) {
15158                try {
15159                    PackageParser.populateCertificates(pkg, args.certificates);
15160                } catch (PackageParserException e) {
15161                    // there was something wrong with the certificates we were given;
15162                    // try to pull them from the APK
15163                    PackageParser.collectCertificates(pkg, parseFlags);
15164                }
15165            } else {
15166                PackageParser.collectCertificates(pkg, parseFlags);
15167            }
15168        } catch (PackageParserException e) {
15169            res.setError("Failed collect during installPackageLI", e);
15170            return;
15171        }
15172
15173        // Get rid of all references to package scan path via parser.
15174        pp = null;
15175        String oldCodePath = null;
15176        boolean systemApp = false;
15177        synchronized (mPackages) {
15178            // Check if installing already existing package
15179            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15180                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15181                if (pkg.mOriginalPackages != null
15182                        && pkg.mOriginalPackages.contains(oldName)
15183                        && mPackages.containsKey(oldName)) {
15184                    // This package is derived from an original package,
15185                    // and this device has been updating from that original
15186                    // name.  We must continue using the original name, so
15187                    // rename the new package here.
15188                    pkg.setPackageName(oldName);
15189                    pkgName = pkg.packageName;
15190                    replace = true;
15191                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15192                            + oldName + " pkgName=" + pkgName);
15193                } else if (mPackages.containsKey(pkgName)) {
15194                    // This package, under its official name, already exists
15195                    // on the device; we should replace it.
15196                    replace = true;
15197                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15198                }
15199
15200                // Child packages are installed through the parent package
15201                if (pkg.parentPackage != null) {
15202                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15203                            "Package " + pkg.packageName + " is child of package "
15204                                    + pkg.parentPackage.parentPackage + ". Child packages "
15205                                    + "can be updated only through the parent package.");
15206                    return;
15207                }
15208
15209                if (replace) {
15210                    // Prevent apps opting out from runtime permissions
15211                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15212                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15213                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15214                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15215                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15216                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15217                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15218                                        + " doesn't support runtime permissions but the old"
15219                                        + " target SDK " + oldTargetSdk + " does.");
15220                        return;
15221                    }
15222
15223                    // Prevent installing of child packages
15224                    if (oldPackage.parentPackage != null) {
15225                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15226                                "Package " + pkg.packageName + " is child of package "
15227                                        + oldPackage.parentPackage + ". Child packages "
15228                                        + "can be updated only through the parent package.");
15229                        return;
15230                    }
15231                }
15232            }
15233
15234            PackageSetting ps = mSettings.mPackages.get(pkgName);
15235            if (ps != null) {
15236                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15237
15238                // Quick sanity check that we're signed correctly if updating;
15239                // we'll check this again later when scanning, but we want to
15240                // bail early here before tripping over redefined permissions.
15241                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15242                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15243                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15244                                + pkg.packageName + " upgrade keys do not match the "
15245                                + "previously installed version");
15246                        return;
15247                    }
15248                } else {
15249                    try {
15250                        verifySignaturesLP(ps, pkg);
15251                    } catch (PackageManagerException e) {
15252                        res.setError(e.error, e.getMessage());
15253                        return;
15254                    }
15255                }
15256
15257                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15258                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15259                    systemApp = (ps.pkg.applicationInfo.flags &
15260                            ApplicationInfo.FLAG_SYSTEM) != 0;
15261                }
15262                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15263            }
15264
15265            // Check whether the newly-scanned package wants to define an already-defined perm
15266            int N = pkg.permissions.size();
15267            for (int i = N-1; i >= 0; i--) {
15268                PackageParser.Permission perm = pkg.permissions.get(i);
15269                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15270                if (bp != null) {
15271                    // If the defining package is signed with our cert, it's okay.  This
15272                    // also includes the "updating the same package" case, of course.
15273                    // "updating same package" could also involve key-rotation.
15274                    final boolean sigsOk;
15275                    if (bp.sourcePackage.equals(pkg.packageName)
15276                            && (bp.packageSetting instanceof PackageSetting)
15277                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15278                                    scanFlags))) {
15279                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15280                    } else {
15281                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15282                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15283                    }
15284                    if (!sigsOk) {
15285                        // If the owning package is the system itself, we log but allow
15286                        // install to proceed; we fail the install on all other permission
15287                        // redefinitions.
15288                        if (!bp.sourcePackage.equals("android")) {
15289                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15290                                    + pkg.packageName + " attempting to redeclare permission "
15291                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15292                            res.origPermission = perm.info.name;
15293                            res.origPackage = bp.sourcePackage;
15294                            return;
15295                        } else {
15296                            Slog.w(TAG, "Package " + pkg.packageName
15297                                    + " attempting to redeclare system permission "
15298                                    + perm.info.name + "; ignoring new declaration");
15299                            pkg.permissions.remove(i);
15300                        }
15301                    }
15302                }
15303            }
15304        }
15305
15306        if (systemApp) {
15307            if (onExternal) {
15308                // Abort update; system app can't be replaced with app on sdcard
15309                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15310                        "Cannot install updates to system apps on sdcard");
15311                return;
15312            } else if (ephemeral) {
15313                // Abort update; system app can't be replaced with an ephemeral app
15314                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15315                        "Cannot update a system app with an ephemeral app");
15316                return;
15317            }
15318        }
15319
15320        if (args.move != null) {
15321            // We did an in-place move, so dex is ready to roll
15322            scanFlags |= SCAN_NO_DEX;
15323            scanFlags |= SCAN_MOVE;
15324
15325            synchronized (mPackages) {
15326                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15327                if (ps == null) {
15328                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15329                            "Missing settings for moved package " + pkgName);
15330                }
15331
15332                // We moved the entire application as-is, so bring over the
15333                // previously derived ABI information.
15334                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15335                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15336            }
15337
15338        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15339            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15340            scanFlags |= SCAN_NO_DEX;
15341
15342            try {
15343                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15344                    args.abiOverride : pkg.cpuAbiOverride);
15345                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15346                        true /*extractLibs*/, mAppLib32InstallDir);
15347            } catch (PackageManagerException pme) {
15348                Slog.e(TAG, "Error deriving application ABI", pme);
15349                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15350                return;
15351            }
15352
15353            // Shared libraries for the package need to be updated.
15354            synchronized (mPackages) {
15355                try {
15356                    updateSharedLibrariesLPr(pkg, null);
15357                } catch (PackageManagerException e) {
15358                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15359                }
15360            }
15361            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15362            // Do not run PackageDexOptimizer through the local performDexOpt
15363            // method because `pkg` may not be in `mPackages` yet.
15364            //
15365            // Also, don't fail application installs if the dexopt step fails.
15366            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15367                    null /* instructionSets */, false /* checkProfiles */,
15368                    getCompilerFilterForReason(REASON_INSTALL),
15369                    getOrCreateCompilerPackageStats(pkg));
15370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15371
15372            // Notify BackgroundDexOptService that the package has been changed.
15373            // If this is an update of a package which used to fail to compile,
15374            // BDOS will remove it from its blacklist.
15375            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15376        }
15377
15378        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15379            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15380            return;
15381        }
15382
15383        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15384
15385        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15386                "installPackageLI")) {
15387            if (replace) {
15388                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15389                        installerPackageName, res);
15390            } else {
15391                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15392                        args.user, installerPackageName, volumeUuid, res);
15393            }
15394        }
15395        synchronized (mPackages) {
15396            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15397            if (ps != null) {
15398                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15399            }
15400
15401            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15402            for (int i = 0; i < childCount; i++) {
15403                PackageParser.Package childPkg = pkg.childPackages.get(i);
15404                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15405                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15406                if (childPs != null) {
15407                    childRes.newUsers = childPs.queryInstalledUsers(
15408                            sUserManager.getUserIds(), true);
15409                }
15410            }
15411        }
15412    }
15413
15414    private void startIntentFilterVerifications(int userId, boolean replacing,
15415            PackageParser.Package pkg) {
15416        if (mIntentFilterVerifierComponent == null) {
15417            Slog.w(TAG, "No IntentFilter verification will not be done as "
15418                    + "there is no IntentFilterVerifier available!");
15419            return;
15420        }
15421
15422        final int verifierUid = getPackageUid(
15423                mIntentFilterVerifierComponent.getPackageName(),
15424                MATCH_DEBUG_TRIAGED_MISSING,
15425                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15426
15427        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15428        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15429        mHandler.sendMessage(msg);
15430
15431        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15432        for (int i = 0; i < childCount; i++) {
15433            PackageParser.Package childPkg = pkg.childPackages.get(i);
15434            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15435            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15436            mHandler.sendMessage(msg);
15437        }
15438    }
15439
15440    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15441            PackageParser.Package pkg) {
15442        int size = pkg.activities.size();
15443        if (size == 0) {
15444            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15445                    "No activity, so no need to verify any IntentFilter!");
15446            return;
15447        }
15448
15449        final boolean hasDomainURLs = hasDomainURLs(pkg);
15450        if (!hasDomainURLs) {
15451            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15452                    "No domain URLs, so no need to verify any IntentFilter!");
15453            return;
15454        }
15455
15456        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15457                + " if any IntentFilter from the " + size
15458                + " Activities needs verification ...");
15459
15460        int count = 0;
15461        final String packageName = pkg.packageName;
15462
15463        synchronized (mPackages) {
15464            // If this is a new install and we see that we've already run verification for this
15465            // package, we have nothing to do: it means the state was restored from backup.
15466            if (!replacing) {
15467                IntentFilterVerificationInfo ivi =
15468                        mSettings.getIntentFilterVerificationLPr(packageName);
15469                if (ivi != null) {
15470                    if (DEBUG_DOMAIN_VERIFICATION) {
15471                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15472                                + ivi.getStatusString());
15473                    }
15474                    return;
15475                }
15476            }
15477
15478            // If any filters need to be verified, then all need to be.
15479            boolean needToVerify = false;
15480            for (PackageParser.Activity a : pkg.activities) {
15481                for (ActivityIntentInfo filter : a.intents) {
15482                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15483                        if (DEBUG_DOMAIN_VERIFICATION) {
15484                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15485                        }
15486                        needToVerify = true;
15487                        break;
15488                    }
15489                }
15490            }
15491
15492            if (needToVerify) {
15493                final int verificationId = mIntentFilterVerificationToken++;
15494                for (PackageParser.Activity a : pkg.activities) {
15495                    for (ActivityIntentInfo filter : a.intents) {
15496                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15497                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15498                                    "Verification needed for IntentFilter:" + filter.toString());
15499                            mIntentFilterVerifier.addOneIntentFilterVerification(
15500                                    verifierUid, userId, verificationId, filter, packageName);
15501                            count++;
15502                        }
15503                    }
15504                }
15505            }
15506        }
15507
15508        if (count > 0) {
15509            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15510                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15511                    +  " for userId:" + userId);
15512            mIntentFilterVerifier.startVerifications(userId);
15513        } else {
15514            if (DEBUG_DOMAIN_VERIFICATION) {
15515                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15516            }
15517        }
15518    }
15519
15520    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15521        final ComponentName cn  = filter.activity.getComponentName();
15522        final String packageName = cn.getPackageName();
15523
15524        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15525                packageName);
15526        if (ivi == null) {
15527            return true;
15528        }
15529        int status = ivi.getStatus();
15530        switch (status) {
15531            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15532            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15533                return true;
15534
15535            default:
15536                // Nothing to do
15537                return false;
15538        }
15539    }
15540
15541    private static boolean isMultiArch(ApplicationInfo info) {
15542        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15543    }
15544
15545    private static boolean isExternal(PackageParser.Package pkg) {
15546        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15547    }
15548
15549    private static boolean isExternal(PackageSetting ps) {
15550        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15551    }
15552
15553    private static boolean isEphemeral(PackageParser.Package pkg) {
15554        return pkg.applicationInfo.isEphemeralApp();
15555    }
15556
15557    private static boolean isEphemeral(PackageSetting ps) {
15558        return ps.pkg != null && isEphemeral(ps.pkg);
15559    }
15560
15561    private static boolean isSystemApp(PackageParser.Package pkg) {
15562        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15563    }
15564
15565    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15566        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15567    }
15568
15569    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15570        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15571    }
15572
15573    private static boolean isSystemApp(PackageSetting ps) {
15574        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15575    }
15576
15577    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15578        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15579    }
15580
15581    private int packageFlagsToInstallFlags(PackageSetting ps) {
15582        int installFlags = 0;
15583        if (isEphemeral(ps)) {
15584            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15585        }
15586        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15587            // This existing package was an external ASEC install when we have
15588            // the external flag without a UUID
15589            installFlags |= PackageManager.INSTALL_EXTERNAL;
15590        }
15591        if (ps.isForwardLocked()) {
15592            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15593        }
15594        return installFlags;
15595    }
15596
15597    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15598        if (isExternal(pkg)) {
15599            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15600                return StorageManager.UUID_PRIMARY_PHYSICAL;
15601            } else {
15602                return pkg.volumeUuid;
15603            }
15604        } else {
15605            return StorageManager.UUID_PRIVATE_INTERNAL;
15606        }
15607    }
15608
15609    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15610        if (isExternal(pkg)) {
15611            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15612                return mSettings.getExternalVersion();
15613            } else {
15614                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15615            }
15616        } else {
15617            return mSettings.getInternalVersion();
15618        }
15619    }
15620
15621    private void deleteTempPackageFiles() {
15622        final FilenameFilter filter = new FilenameFilter() {
15623            public boolean accept(File dir, String name) {
15624                return name.startsWith("vmdl") && name.endsWith(".tmp");
15625            }
15626        };
15627        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15628            file.delete();
15629        }
15630    }
15631
15632    @Override
15633    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15634            int flags) {
15635        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15636                flags);
15637    }
15638
15639    @Override
15640    public void deletePackage(final String packageName,
15641            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15642        mContext.enforceCallingOrSelfPermission(
15643                android.Manifest.permission.DELETE_PACKAGES, null);
15644        Preconditions.checkNotNull(packageName);
15645        Preconditions.checkNotNull(observer);
15646        final int uid = Binder.getCallingUid();
15647        if (!isOrphaned(packageName)
15648                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15649            try {
15650                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15651                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15652                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15653                observer.onUserActionRequired(intent);
15654            } catch (RemoteException re) {
15655            }
15656            return;
15657        }
15658        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15659        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15660        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15661            mContext.enforceCallingOrSelfPermission(
15662                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15663                    "deletePackage for user " + userId);
15664        }
15665
15666        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15667            try {
15668                observer.onPackageDeleted(packageName,
15669                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15670            } catch (RemoteException re) {
15671            }
15672            return;
15673        }
15674
15675        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15676            try {
15677                observer.onPackageDeleted(packageName,
15678                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15679            } catch (RemoteException re) {
15680            }
15681            return;
15682        }
15683
15684        if (DEBUG_REMOVE) {
15685            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15686                    + " deleteAllUsers: " + deleteAllUsers );
15687        }
15688        // Queue up an async operation since the package deletion may take a little while.
15689        mHandler.post(new Runnable() {
15690            public void run() {
15691                mHandler.removeCallbacks(this);
15692                int returnCode;
15693                if (!deleteAllUsers) {
15694                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15695                } else {
15696                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15697                    // If nobody is blocking uninstall, proceed with delete for all users
15698                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15699                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15700                    } else {
15701                        // Otherwise uninstall individually for users with blockUninstalls=false
15702                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15703                        for (int userId : users) {
15704                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15705                                returnCode = deletePackageX(packageName, userId, userFlags);
15706                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15707                                    Slog.w(TAG, "Package delete failed for user " + userId
15708                                            + ", returnCode " + returnCode);
15709                                }
15710                            }
15711                        }
15712                        // The app has only been marked uninstalled for certain users.
15713                        // We still need to report that delete was blocked
15714                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15715                    }
15716                }
15717                try {
15718                    observer.onPackageDeleted(packageName, returnCode, null);
15719                } catch (RemoteException e) {
15720                    Log.i(TAG, "Observer no longer exists.");
15721                } //end catch
15722            } //end run
15723        });
15724    }
15725
15726    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15727        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15728              || callingUid == Process.SYSTEM_UID) {
15729            return true;
15730        }
15731        final int callingUserId = UserHandle.getUserId(callingUid);
15732        // If the caller installed the pkgName, then allow it to silently uninstall.
15733        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15734            return true;
15735        }
15736
15737        // Allow package verifier to silently uninstall.
15738        if (mRequiredVerifierPackage != null &&
15739                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15740            return true;
15741        }
15742
15743        // Allow package uninstaller to silently uninstall.
15744        if (mRequiredUninstallerPackage != null &&
15745                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15746            return true;
15747        }
15748
15749        // Allow storage manager to silently uninstall.
15750        if (mStorageManagerPackage != null &&
15751                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15752            return true;
15753        }
15754        return false;
15755    }
15756
15757    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15758        int[] result = EMPTY_INT_ARRAY;
15759        for (int userId : userIds) {
15760            if (getBlockUninstallForUser(packageName, userId)) {
15761                result = ArrayUtils.appendInt(result, userId);
15762            }
15763        }
15764        return result;
15765    }
15766
15767    @Override
15768    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15769        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15770    }
15771
15772    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15773        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15774                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15775        try {
15776            if (dpm != null) {
15777                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15778                        /* callingUserOnly =*/ false);
15779                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15780                        : deviceOwnerComponentName.getPackageName();
15781                // Does the package contains the device owner?
15782                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15783                // this check is probably not needed, since DO should be registered as a device
15784                // admin on some user too. (Original bug for this: b/17657954)
15785                if (packageName.equals(deviceOwnerPackageName)) {
15786                    return true;
15787                }
15788                // Does it contain a device admin for any user?
15789                int[] users;
15790                if (userId == UserHandle.USER_ALL) {
15791                    users = sUserManager.getUserIds();
15792                } else {
15793                    users = new int[]{userId};
15794                }
15795                for (int i = 0; i < users.length; ++i) {
15796                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15797                        return true;
15798                    }
15799                }
15800            }
15801        } catch (RemoteException e) {
15802        }
15803        return false;
15804    }
15805
15806    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15807        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15808    }
15809
15810    /**
15811     *  This method is an internal method that could be get invoked either
15812     *  to delete an installed package or to clean up a failed installation.
15813     *  After deleting an installed package, a broadcast is sent to notify any
15814     *  listeners that the package has been removed. For cleaning up a failed
15815     *  installation, the broadcast is not necessary since the package's
15816     *  installation wouldn't have sent the initial broadcast either
15817     *  The key steps in deleting a package are
15818     *  deleting the package information in internal structures like mPackages,
15819     *  deleting the packages base directories through installd
15820     *  updating mSettings to reflect current status
15821     *  persisting settings for later use
15822     *  sending a broadcast if necessary
15823     */
15824    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15825        final PackageRemovedInfo info = new PackageRemovedInfo();
15826        final boolean res;
15827
15828        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15829                ? UserHandle.USER_ALL : userId;
15830
15831        if (isPackageDeviceAdmin(packageName, removeUser)) {
15832            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15833            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15834        }
15835
15836        PackageSetting uninstalledPs = null;
15837
15838        // for the uninstall-updates case and restricted profiles, remember the per-
15839        // user handle installed state
15840        int[] allUsers;
15841        synchronized (mPackages) {
15842            uninstalledPs = mSettings.mPackages.get(packageName);
15843            if (uninstalledPs == null) {
15844                Slog.w(TAG, "Not removing non-existent package " + packageName);
15845                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15846            }
15847            allUsers = sUserManager.getUserIds();
15848            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15849        }
15850
15851        final int freezeUser;
15852        if (isUpdatedSystemApp(uninstalledPs)
15853                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15854            // We're downgrading a system app, which will apply to all users, so
15855            // freeze them all during the downgrade
15856            freezeUser = UserHandle.USER_ALL;
15857        } else {
15858            freezeUser = removeUser;
15859        }
15860
15861        synchronized (mInstallLock) {
15862            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15863            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15864                    deleteFlags, "deletePackageX")) {
15865                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15866                        deleteFlags | REMOVE_CHATTY, info, true, null);
15867            }
15868            synchronized (mPackages) {
15869                if (res) {
15870                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15871                }
15872            }
15873        }
15874
15875        if (res) {
15876            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15877            info.sendPackageRemovedBroadcasts(killApp);
15878            info.sendSystemPackageUpdatedBroadcasts();
15879            info.sendSystemPackageAppearedBroadcasts();
15880        }
15881        // Force a gc here.
15882        Runtime.getRuntime().gc();
15883        // Delete the resources here after sending the broadcast to let
15884        // other processes clean up before deleting resources.
15885        if (info.args != null) {
15886            synchronized (mInstallLock) {
15887                info.args.doPostDeleteLI(true);
15888            }
15889        }
15890
15891        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15892    }
15893
15894    class PackageRemovedInfo {
15895        String removedPackage;
15896        int uid = -1;
15897        int removedAppId = -1;
15898        int[] origUsers;
15899        int[] removedUsers = null;
15900        boolean isRemovedPackageSystemUpdate = false;
15901        boolean isUpdate;
15902        boolean dataRemoved;
15903        boolean removedForAllUsers;
15904        // Clean up resources deleted packages.
15905        InstallArgs args = null;
15906        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15907        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15908
15909        void sendPackageRemovedBroadcasts(boolean killApp) {
15910            sendPackageRemovedBroadcastInternal(killApp);
15911            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15912            for (int i = 0; i < childCount; i++) {
15913                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15914                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15915            }
15916        }
15917
15918        void sendSystemPackageUpdatedBroadcasts() {
15919            if (isRemovedPackageSystemUpdate) {
15920                sendSystemPackageUpdatedBroadcastsInternal();
15921                final int childCount = (removedChildPackages != null)
15922                        ? removedChildPackages.size() : 0;
15923                for (int i = 0; i < childCount; i++) {
15924                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15925                    if (childInfo.isRemovedPackageSystemUpdate) {
15926                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15927                    }
15928                }
15929            }
15930        }
15931
15932        void sendSystemPackageAppearedBroadcasts() {
15933            final int packageCount = (appearedChildPackages != null)
15934                    ? appearedChildPackages.size() : 0;
15935            for (int i = 0; i < packageCount; i++) {
15936                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15937                for (int userId : installedInfo.newUsers) {
15938                    sendPackageAddedForUser(installedInfo.name, true,
15939                            UserHandle.getAppId(installedInfo.uid), userId);
15940                }
15941            }
15942        }
15943
15944        private void sendSystemPackageUpdatedBroadcastsInternal() {
15945            Bundle extras = new Bundle(2);
15946            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15947            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15948            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15949                    extras, 0, null, null, null);
15950            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15951                    extras, 0, null, null, null);
15952            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15953                    null, 0, removedPackage, null, null);
15954        }
15955
15956        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15957            Bundle extras = new Bundle(2);
15958            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15959            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15960            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15961            if (isUpdate || isRemovedPackageSystemUpdate) {
15962                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15963            }
15964            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15965            if (removedPackage != null) {
15966                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15967                        extras, 0, null, null, removedUsers);
15968                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15969                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15970                            removedPackage, extras, 0, null, null, removedUsers);
15971                }
15972            }
15973            if (removedAppId >= 0) {
15974                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15975                        removedUsers);
15976            }
15977        }
15978    }
15979
15980    /*
15981     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15982     * flag is not set, the data directory is removed as well.
15983     * make sure this flag is set for partially installed apps. If not its meaningless to
15984     * delete a partially installed application.
15985     */
15986    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15987            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15988        String packageName = ps.name;
15989        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15990        // Retrieve object to delete permissions for shared user later on
15991        final PackageParser.Package deletedPkg;
15992        final PackageSetting deletedPs;
15993        // reader
15994        synchronized (mPackages) {
15995            deletedPkg = mPackages.get(packageName);
15996            deletedPs = mSettings.mPackages.get(packageName);
15997            if (outInfo != null) {
15998                outInfo.removedPackage = packageName;
15999                outInfo.removedUsers = deletedPs != null
16000                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16001                        : null;
16002            }
16003        }
16004
16005        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16006
16007        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16008            final PackageParser.Package resolvedPkg;
16009            if (deletedPkg != null) {
16010                resolvedPkg = deletedPkg;
16011            } else {
16012                // We don't have a parsed package when it lives on an ejected
16013                // adopted storage device, so fake something together
16014                resolvedPkg = new PackageParser.Package(ps.name);
16015                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16016            }
16017            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16018                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16019            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16020            if (outInfo != null) {
16021                outInfo.dataRemoved = true;
16022            }
16023            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16024        }
16025
16026        // writer
16027        synchronized (mPackages) {
16028            if (deletedPs != null) {
16029                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16030                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16031                    clearDefaultBrowserIfNeeded(packageName);
16032                    if (outInfo != null) {
16033                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16034                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16035                    }
16036                    updatePermissionsLPw(deletedPs.name, null, 0);
16037                    if (deletedPs.sharedUser != null) {
16038                        // Remove permissions associated with package. Since runtime
16039                        // permissions are per user we have to kill the removed package
16040                        // or packages running under the shared user of the removed
16041                        // package if revoking the permissions requested only by the removed
16042                        // package is successful and this causes a change in gids.
16043                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16044                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16045                                    userId);
16046                            if (userIdToKill == UserHandle.USER_ALL
16047                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16048                                // If gids changed for this user, kill all affected packages.
16049                                mHandler.post(new Runnable() {
16050                                    @Override
16051                                    public void run() {
16052                                        // This has to happen with no lock held.
16053                                        killApplication(deletedPs.name, deletedPs.appId,
16054                                                KILL_APP_REASON_GIDS_CHANGED);
16055                                    }
16056                                });
16057                                break;
16058                            }
16059                        }
16060                    }
16061                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16062                }
16063                // make sure to preserve per-user disabled state if this removal was just
16064                // a downgrade of a system app to the factory package
16065                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16066                    if (DEBUG_REMOVE) {
16067                        Slog.d(TAG, "Propagating install state across downgrade");
16068                    }
16069                    for (int userId : allUserHandles) {
16070                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16071                        if (DEBUG_REMOVE) {
16072                            Slog.d(TAG, "    user " + userId + " => " + installed);
16073                        }
16074                        ps.setInstalled(installed, userId);
16075                    }
16076                }
16077            }
16078            // can downgrade to reader
16079            if (writeSettings) {
16080                // Save settings now
16081                mSettings.writeLPr();
16082            }
16083        }
16084        if (outInfo != null) {
16085            // A user ID was deleted here. Go through all users and remove it
16086            // from KeyStore.
16087            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16088        }
16089    }
16090
16091    static boolean locationIsPrivileged(File path) {
16092        try {
16093            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16094                    .getCanonicalPath();
16095            return path.getCanonicalPath().startsWith(privilegedAppDir);
16096        } catch (IOException e) {
16097            Slog.e(TAG, "Unable to access code path " + path);
16098        }
16099        return false;
16100    }
16101
16102    /*
16103     * Tries to delete system package.
16104     */
16105    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16106            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16107            boolean writeSettings) {
16108        if (deletedPs.parentPackageName != null) {
16109            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16110            return false;
16111        }
16112
16113        final boolean applyUserRestrictions
16114                = (allUserHandles != null) && (outInfo.origUsers != null);
16115        final PackageSetting disabledPs;
16116        // Confirm if the system package has been updated
16117        // An updated system app can be deleted. This will also have to restore
16118        // the system pkg from system partition
16119        // reader
16120        synchronized (mPackages) {
16121            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16122        }
16123
16124        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16125                + " disabledPs=" + disabledPs);
16126
16127        if (disabledPs == null) {
16128            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16129            return false;
16130        } else if (DEBUG_REMOVE) {
16131            Slog.d(TAG, "Deleting system pkg from data partition");
16132        }
16133
16134        if (DEBUG_REMOVE) {
16135            if (applyUserRestrictions) {
16136                Slog.d(TAG, "Remembering install states:");
16137                for (int userId : allUserHandles) {
16138                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16139                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16140                }
16141            }
16142        }
16143
16144        // Delete the updated package
16145        outInfo.isRemovedPackageSystemUpdate = true;
16146        if (outInfo.removedChildPackages != null) {
16147            final int childCount = (deletedPs.childPackageNames != null)
16148                    ? deletedPs.childPackageNames.size() : 0;
16149            for (int i = 0; i < childCount; i++) {
16150                String childPackageName = deletedPs.childPackageNames.get(i);
16151                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16152                        .contains(childPackageName)) {
16153                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16154                            childPackageName);
16155                    if (childInfo != null) {
16156                        childInfo.isRemovedPackageSystemUpdate = true;
16157                    }
16158                }
16159            }
16160        }
16161
16162        if (disabledPs.versionCode < deletedPs.versionCode) {
16163            // Delete data for downgrades
16164            flags &= ~PackageManager.DELETE_KEEP_DATA;
16165        } else {
16166            // Preserve data by setting flag
16167            flags |= PackageManager.DELETE_KEEP_DATA;
16168        }
16169
16170        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16171                outInfo, writeSettings, disabledPs.pkg);
16172        if (!ret) {
16173            return false;
16174        }
16175
16176        // writer
16177        synchronized (mPackages) {
16178            // Reinstate the old system package
16179            enableSystemPackageLPw(disabledPs.pkg);
16180            // Remove any native libraries from the upgraded package.
16181            removeNativeBinariesLI(deletedPs);
16182        }
16183
16184        // Install the system package
16185        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16186        int parseFlags = mDefParseFlags
16187                | PackageParser.PARSE_MUST_BE_APK
16188                | PackageParser.PARSE_IS_SYSTEM
16189                | PackageParser.PARSE_IS_SYSTEM_DIR;
16190        if (locationIsPrivileged(disabledPs.codePath)) {
16191            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16192        }
16193
16194        final PackageParser.Package newPkg;
16195        try {
16196            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16197        } catch (PackageManagerException e) {
16198            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16199                    + e.getMessage());
16200            return false;
16201        }
16202        try {
16203            // update shared libraries for the newly re-installed system package
16204            updateSharedLibrariesLPr(newPkg, null);
16205        } catch (PackageManagerException e) {
16206            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16207        }
16208
16209        prepareAppDataAfterInstallLIF(newPkg);
16210
16211        // writer
16212        synchronized (mPackages) {
16213            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16214
16215            // Propagate the permissions state as we do not want to drop on the floor
16216            // runtime permissions. The update permissions method below will take
16217            // care of removing obsolete permissions and grant install permissions.
16218            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16219            updatePermissionsLPw(newPkg.packageName, newPkg,
16220                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16221
16222            if (applyUserRestrictions) {
16223                if (DEBUG_REMOVE) {
16224                    Slog.d(TAG, "Propagating install state across reinstall");
16225                }
16226                for (int userId : allUserHandles) {
16227                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16228                    if (DEBUG_REMOVE) {
16229                        Slog.d(TAG, "    user " + userId + " => " + installed);
16230                    }
16231                    ps.setInstalled(installed, userId);
16232
16233                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16234                }
16235                // Regardless of writeSettings we need to ensure that this restriction
16236                // state propagation is persisted
16237                mSettings.writeAllUsersPackageRestrictionsLPr();
16238            }
16239            // can downgrade to reader here
16240            if (writeSettings) {
16241                mSettings.writeLPr();
16242            }
16243        }
16244        return true;
16245    }
16246
16247    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16248            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16249            PackageRemovedInfo outInfo, boolean writeSettings,
16250            PackageParser.Package replacingPackage) {
16251        synchronized (mPackages) {
16252            if (outInfo != null) {
16253                outInfo.uid = ps.appId;
16254            }
16255
16256            if (outInfo != null && outInfo.removedChildPackages != null) {
16257                final int childCount = (ps.childPackageNames != null)
16258                        ? ps.childPackageNames.size() : 0;
16259                for (int i = 0; i < childCount; i++) {
16260                    String childPackageName = ps.childPackageNames.get(i);
16261                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16262                    if (childPs == null) {
16263                        return false;
16264                    }
16265                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16266                            childPackageName);
16267                    if (childInfo != null) {
16268                        childInfo.uid = childPs.appId;
16269                    }
16270                }
16271            }
16272        }
16273
16274        // Delete package data from internal structures and also remove data if flag is set
16275        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16276
16277        // Delete the child packages data
16278        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16279        for (int i = 0; i < childCount; i++) {
16280            PackageSetting childPs;
16281            synchronized (mPackages) {
16282                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16283            }
16284            if (childPs != null) {
16285                PackageRemovedInfo childOutInfo = (outInfo != null
16286                        && outInfo.removedChildPackages != null)
16287                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16288                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16289                        && (replacingPackage != null
16290                        && !replacingPackage.hasChildPackage(childPs.name))
16291                        ? flags & ~DELETE_KEEP_DATA : flags;
16292                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16293                        deleteFlags, writeSettings);
16294            }
16295        }
16296
16297        // Delete application code and resources only for parent packages
16298        if (ps.parentPackageName == null) {
16299            if (deleteCodeAndResources && (outInfo != null)) {
16300                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16301                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16302                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16303            }
16304        }
16305
16306        return true;
16307    }
16308
16309    @Override
16310    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16311            int userId) {
16312        mContext.enforceCallingOrSelfPermission(
16313                android.Manifest.permission.DELETE_PACKAGES, null);
16314        synchronized (mPackages) {
16315            PackageSetting ps = mSettings.mPackages.get(packageName);
16316            if (ps == null) {
16317                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16318                return false;
16319            }
16320            if (!ps.getInstalled(userId)) {
16321                // Can't block uninstall for an app that is not installed or enabled.
16322                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16323                return false;
16324            }
16325            ps.setBlockUninstall(blockUninstall, userId);
16326            mSettings.writePackageRestrictionsLPr(userId);
16327        }
16328        return true;
16329    }
16330
16331    @Override
16332    public boolean getBlockUninstallForUser(String packageName, int userId) {
16333        synchronized (mPackages) {
16334            PackageSetting ps = mSettings.mPackages.get(packageName);
16335            if (ps == null) {
16336                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16337                return false;
16338            }
16339            return ps.getBlockUninstall(userId);
16340        }
16341    }
16342
16343    @Override
16344    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16345        int callingUid = Binder.getCallingUid();
16346        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16347            throw new SecurityException(
16348                    "setRequiredForSystemUser can only be run by the system or root");
16349        }
16350        synchronized (mPackages) {
16351            PackageSetting ps = mSettings.mPackages.get(packageName);
16352            if (ps == null) {
16353                Log.w(TAG, "Package doesn't exist: " + packageName);
16354                return false;
16355            }
16356            if (systemUserApp) {
16357                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16358            } else {
16359                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16360            }
16361            mSettings.writeLPr();
16362        }
16363        return true;
16364    }
16365
16366    /*
16367     * This method handles package deletion in general
16368     */
16369    private boolean deletePackageLIF(String packageName, UserHandle user,
16370            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16371            PackageRemovedInfo outInfo, boolean writeSettings,
16372            PackageParser.Package replacingPackage) {
16373        if (packageName == null) {
16374            Slog.w(TAG, "Attempt to delete null packageName.");
16375            return false;
16376        }
16377
16378        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16379
16380        PackageSetting ps;
16381
16382        synchronized (mPackages) {
16383            ps = mSettings.mPackages.get(packageName);
16384            if (ps == null) {
16385                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16386                return false;
16387            }
16388
16389            if (ps.parentPackageName != null && (!isSystemApp(ps)
16390                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16391                if (DEBUG_REMOVE) {
16392                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16393                            + ((user == null) ? UserHandle.USER_ALL : user));
16394                }
16395                final int removedUserId = (user != null) ? user.getIdentifier()
16396                        : UserHandle.USER_ALL;
16397                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16398                    return false;
16399                }
16400                markPackageUninstalledForUserLPw(ps, user);
16401                scheduleWritePackageRestrictionsLocked(user);
16402                return true;
16403            }
16404        }
16405
16406        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16407                && user.getIdentifier() != UserHandle.USER_ALL)) {
16408            // The caller is asking that the package only be deleted for a single
16409            // user.  To do this, we just mark its uninstalled state and delete
16410            // its data. If this is a system app, we only allow this to happen if
16411            // they have set the special DELETE_SYSTEM_APP which requests different
16412            // semantics than normal for uninstalling system apps.
16413            markPackageUninstalledForUserLPw(ps, user);
16414
16415            if (!isSystemApp(ps)) {
16416                // Do not uninstall the APK if an app should be cached
16417                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16418                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16419                    // Other user still have this package installed, so all
16420                    // we need to do is clear this user's data and save that
16421                    // it is uninstalled.
16422                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16423                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16424                        return false;
16425                    }
16426                    scheduleWritePackageRestrictionsLocked(user);
16427                    return true;
16428                } else {
16429                    // We need to set it back to 'installed' so the uninstall
16430                    // broadcasts will be sent correctly.
16431                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16432                    ps.setInstalled(true, user.getIdentifier());
16433                }
16434            } else {
16435                // This is a system app, so we assume that the
16436                // other users still have this package installed, so all
16437                // we need to do is clear this user's data and save that
16438                // it is uninstalled.
16439                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16440                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16441                    return false;
16442                }
16443                scheduleWritePackageRestrictionsLocked(user);
16444                return true;
16445            }
16446        }
16447
16448        // If we are deleting a composite package for all users, keep track
16449        // of result for each child.
16450        if (ps.childPackageNames != null && outInfo != null) {
16451            synchronized (mPackages) {
16452                final int childCount = ps.childPackageNames.size();
16453                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16454                for (int i = 0; i < childCount; i++) {
16455                    String childPackageName = ps.childPackageNames.get(i);
16456                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16457                    childInfo.removedPackage = childPackageName;
16458                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16459                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16460                    if (childPs != null) {
16461                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16462                    }
16463                }
16464            }
16465        }
16466
16467        boolean ret = false;
16468        if (isSystemApp(ps)) {
16469            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16470            // When an updated system application is deleted we delete the existing resources
16471            // as well and fall back to existing code in system partition
16472            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16473        } else {
16474            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16475            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16476                    outInfo, writeSettings, replacingPackage);
16477        }
16478
16479        // Take a note whether we deleted the package for all users
16480        if (outInfo != null) {
16481            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16482            if (outInfo.removedChildPackages != null) {
16483                synchronized (mPackages) {
16484                    final int childCount = outInfo.removedChildPackages.size();
16485                    for (int i = 0; i < childCount; i++) {
16486                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16487                        if (childInfo != null) {
16488                            childInfo.removedForAllUsers = mPackages.get(
16489                                    childInfo.removedPackage) == null;
16490                        }
16491                    }
16492                }
16493            }
16494            // If we uninstalled an update to a system app there may be some
16495            // child packages that appeared as they are declared in the system
16496            // app but were not declared in the update.
16497            if (isSystemApp(ps)) {
16498                synchronized (mPackages) {
16499                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16500                    final int childCount = (updatedPs.childPackageNames != null)
16501                            ? updatedPs.childPackageNames.size() : 0;
16502                    for (int i = 0; i < childCount; i++) {
16503                        String childPackageName = updatedPs.childPackageNames.get(i);
16504                        if (outInfo.removedChildPackages == null
16505                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16506                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16507                            if (childPs == null) {
16508                                continue;
16509                            }
16510                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16511                            installRes.name = childPackageName;
16512                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16513                            installRes.pkg = mPackages.get(childPackageName);
16514                            installRes.uid = childPs.pkg.applicationInfo.uid;
16515                            if (outInfo.appearedChildPackages == null) {
16516                                outInfo.appearedChildPackages = new ArrayMap<>();
16517                            }
16518                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16519                        }
16520                    }
16521                }
16522            }
16523        }
16524
16525        return ret;
16526    }
16527
16528    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16529        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16530                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16531        for (int nextUserId : userIds) {
16532            if (DEBUG_REMOVE) {
16533                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16534            }
16535            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16536                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16537                    false /*hidden*/, false /*suspended*/, null, null, null,
16538                    false /*blockUninstall*/,
16539                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16540        }
16541    }
16542
16543    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16544            PackageRemovedInfo outInfo) {
16545        final PackageParser.Package pkg;
16546        synchronized (mPackages) {
16547            pkg = mPackages.get(ps.name);
16548        }
16549
16550        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16551                : new int[] {userId};
16552        for (int nextUserId : userIds) {
16553            if (DEBUG_REMOVE) {
16554                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16555                        + nextUserId);
16556            }
16557
16558            destroyAppDataLIF(pkg, userId,
16559                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16560            destroyAppProfilesLIF(pkg, userId);
16561            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16562            schedulePackageCleaning(ps.name, nextUserId, false);
16563            synchronized (mPackages) {
16564                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16565                    scheduleWritePackageRestrictionsLocked(nextUserId);
16566                }
16567                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16568            }
16569        }
16570
16571        if (outInfo != null) {
16572            outInfo.removedPackage = ps.name;
16573            outInfo.removedAppId = ps.appId;
16574            outInfo.removedUsers = userIds;
16575        }
16576
16577        return true;
16578    }
16579
16580    private final class ClearStorageConnection implements ServiceConnection {
16581        IMediaContainerService mContainerService;
16582
16583        @Override
16584        public void onServiceConnected(ComponentName name, IBinder service) {
16585            synchronized (this) {
16586                mContainerService = IMediaContainerService.Stub.asInterface(service);
16587                notifyAll();
16588            }
16589        }
16590
16591        @Override
16592        public void onServiceDisconnected(ComponentName name) {
16593        }
16594    }
16595
16596    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16597        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16598
16599        final boolean mounted;
16600        if (Environment.isExternalStorageEmulated()) {
16601            mounted = true;
16602        } else {
16603            final String status = Environment.getExternalStorageState();
16604
16605            mounted = status.equals(Environment.MEDIA_MOUNTED)
16606                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16607        }
16608
16609        if (!mounted) {
16610            return;
16611        }
16612
16613        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16614        int[] users;
16615        if (userId == UserHandle.USER_ALL) {
16616            users = sUserManager.getUserIds();
16617        } else {
16618            users = new int[] { userId };
16619        }
16620        final ClearStorageConnection conn = new ClearStorageConnection();
16621        if (mContext.bindServiceAsUser(
16622                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16623            try {
16624                for (int curUser : users) {
16625                    long timeout = SystemClock.uptimeMillis() + 5000;
16626                    synchronized (conn) {
16627                        long now;
16628                        while (conn.mContainerService == null &&
16629                                (now = SystemClock.uptimeMillis()) < timeout) {
16630                            try {
16631                                conn.wait(timeout - now);
16632                            } catch (InterruptedException e) {
16633                            }
16634                        }
16635                    }
16636                    if (conn.mContainerService == null) {
16637                        return;
16638                    }
16639
16640                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16641                    clearDirectory(conn.mContainerService,
16642                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16643                    if (allData) {
16644                        clearDirectory(conn.mContainerService,
16645                                userEnv.buildExternalStorageAppDataDirs(packageName));
16646                        clearDirectory(conn.mContainerService,
16647                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16648                    }
16649                }
16650            } finally {
16651                mContext.unbindService(conn);
16652            }
16653        }
16654    }
16655
16656    @Override
16657    public void clearApplicationProfileData(String packageName) {
16658        enforceSystemOrRoot("Only the system can clear all profile data");
16659
16660        final PackageParser.Package pkg;
16661        synchronized (mPackages) {
16662            pkg = mPackages.get(packageName);
16663        }
16664
16665        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16666            synchronized (mInstallLock) {
16667                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16668                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16669                        true /* removeBaseMarker */);
16670            }
16671        }
16672    }
16673
16674    @Override
16675    public void clearApplicationUserData(final String packageName,
16676            final IPackageDataObserver observer, final int userId) {
16677        mContext.enforceCallingOrSelfPermission(
16678                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16679
16680        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16681                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16682
16683        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16684            throw new SecurityException("Cannot clear data for a protected package: "
16685                    + packageName);
16686        }
16687        // Queue up an async operation since the package deletion may take a little while.
16688        mHandler.post(new Runnable() {
16689            public void run() {
16690                mHandler.removeCallbacks(this);
16691                final boolean succeeded;
16692                try (PackageFreezer freezer = freezePackage(packageName,
16693                        "clearApplicationUserData")) {
16694                    synchronized (mInstallLock) {
16695                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16696                    }
16697                    clearExternalStorageDataSync(packageName, userId, true);
16698                }
16699                if (succeeded) {
16700                    // invoke DeviceStorageMonitor's update method to clear any notifications
16701                    DeviceStorageMonitorInternal dsm = LocalServices
16702                            .getService(DeviceStorageMonitorInternal.class);
16703                    if (dsm != null) {
16704                        dsm.checkMemory();
16705                    }
16706                }
16707                if(observer != null) {
16708                    try {
16709                        observer.onRemoveCompleted(packageName, succeeded);
16710                    } catch (RemoteException e) {
16711                        Log.i(TAG, "Observer no longer exists.");
16712                    }
16713                } //end if observer
16714            } //end run
16715        });
16716    }
16717
16718    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16719        if (packageName == null) {
16720            Slog.w(TAG, "Attempt to delete null packageName.");
16721            return false;
16722        }
16723
16724        // Try finding details about the requested package
16725        PackageParser.Package pkg;
16726        synchronized (mPackages) {
16727            pkg = mPackages.get(packageName);
16728            if (pkg == null) {
16729                final PackageSetting ps = mSettings.mPackages.get(packageName);
16730                if (ps != null) {
16731                    pkg = ps.pkg;
16732                }
16733            }
16734
16735            if (pkg == null) {
16736                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16737                return false;
16738            }
16739
16740            PackageSetting ps = (PackageSetting) pkg.mExtras;
16741            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16742        }
16743
16744        clearAppDataLIF(pkg, userId,
16745                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16746
16747        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16748        removeKeystoreDataIfNeeded(userId, appId);
16749
16750        UserManagerInternal umInternal = getUserManagerInternal();
16751        final int flags;
16752        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16753            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16754        } else if (umInternal.isUserRunning(userId)) {
16755            flags = StorageManager.FLAG_STORAGE_DE;
16756        } else {
16757            flags = 0;
16758        }
16759        prepareAppDataContentsLIF(pkg, userId, flags);
16760
16761        return true;
16762    }
16763
16764    /**
16765     * Reverts user permission state changes (permissions and flags) in
16766     * all packages for a given user.
16767     *
16768     * @param userId The device user for which to do a reset.
16769     */
16770    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16771        final int packageCount = mPackages.size();
16772        for (int i = 0; i < packageCount; i++) {
16773            PackageParser.Package pkg = mPackages.valueAt(i);
16774            PackageSetting ps = (PackageSetting) pkg.mExtras;
16775            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16776        }
16777    }
16778
16779    private void resetNetworkPolicies(int userId) {
16780        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16781    }
16782
16783    /**
16784     * Reverts user permission state changes (permissions and flags).
16785     *
16786     * @param ps The package for which to reset.
16787     * @param userId The device user for which to do a reset.
16788     */
16789    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16790            final PackageSetting ps, final int userId) {
16791        if (ps.pkg == null) {
16792            return;
16793        }
16794
16795        // These are flags that can change base on user actions.
16796        final int userSettableMask = FLAG_PERMISSION_USER_SET
16797                | FLAG_PERMISSION_USER_FIXED
16798                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16799                | FLAG_PERMISSION_REVIEW_REQUIRED;
16800
16801        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16802                | FLAG_PERMISSION_POLICY_FIXED;
16803
16804        boolean writeInstallPermissions = false;
16805        boolean writeRuntimePermissions = false;
16806
16807        final int permissionCount = ps.pkg.requestedPermissions.size();
16808        for (int i = 0; i < permissionCount; i++) {
16809            String permission = ps.pkg.requestedPermissions.get(i);
16810
16811            BasePermission bp = mSettings.mPermissions.get(permission);
16812            if (bp == null) {
16813                continue;
16814            }
16815
16816            // If shared user we just reset the state to which only this app contributed.
16817            if (ps.sharedUser != null) {
16818                boolean used = false;
16819                final int packageCount = ps.sharedUser.packages.size();
16820                for (int j = 0; j < packageCount; j++) {
16821                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16822                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16823                            && pkg.pkg.requestedPermissions.contains(permission)) {
16824                        used = true;
16825                        break;
16826                    }
16827                }
16828                if (used) {
16829                    continue;
16830                }
16831            }
16832
16833            PermissionsState permissionsState = ps.getPermissionsState();
16834
16835            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16836
16837            // Always clear the user settable flags.
16838            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16839                    bp.name) != null;
16840            // If permission review is enabled and this is a legacy app, mark the
16841            // permission as requiring a review as this is the initial state.
16842            int flags = 0;
16843            if (mPermissionReviewRequired
16844                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16845                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16846            }
16847            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16848                if (hasInstallState) {
16849                    writeInstallPermissions = true;
16850                } else {
16851                    writeRuntimePermissions = true;
16852                }
16853            }
16854
16855            // Below is only runtime permission handling.
16856            if (!bp.isRuntime()) {
16857                continue;
16858            }
16859
16860            // Never clobber system or policy.
16861            if ((oldFlags & policyOrSystemFlags) != 0) {
16862                continue;
16863            }
16864
16865            // If this permission was granted by default, make sure it is.
16866            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16867                if (permissionsState.grantRuntimePermission(bp, userId)
16868                        != PERMISSION_OPERATION_FAILURE) {
16869                    writeRuntimePermissions = true;
16870                }
16871            // If permission review is enabled the permissions for a legacy apps
16872            // are represented as constantly granted runtime ones, so don't revoke.
16873            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16874                // Otherwise, reset the permission.
16875                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16876                switch (revokeResult) {
16877                    case PERMISSION_OPERATION_SUCCESS:
16878                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16879                        writeRuntimePermissions = true;
16880                        final int appId = ps.appId;
16881                        mHandler.post(new Runnable() {
16882                            @Override
16883                            public void run() {
16884                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16885                            }
16886                        });
16887                    } break;
16888                }
16889            }
16890        }
16891
16892        // Synchronously write as we are taking permissions away.
16893        if (writeRuntimePermissions) {
16894            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16895        }
16896
16897        // Synchronously write as we are taking permissions away.
16898        if (writeInstallPermissions) {
16899            mSettings.writeLPr();
16900        }
16901    }
16902
16903    /**
16904     * Remove entries from the keystore daemon. Will only remove it if the
16905     * {@code appId} is valid.
16906     */
16907    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16908        if (appId < 0) {
16909            return;
16910        }
16911
16912        final KeyStore keyStore = KeyStore.getInstance();
16913        if (keyStore != null) {
16914            if (userId == UserHandle.USER_ALL) {
16915                for (final int individual : sUserManager.getUserIds()) {
16916                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16917                }
16918            } else {
16919                keyStore.clearUid(UserHandle.getUid(userId, appId));
16920            }
16921        } else {
16922            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16923        }
16924    }
16925
16926    @Override
16927    public void deleteApplicationCacheFiles(final String packageName,
16928            final IPackageDataObserver observer) {
16929        final int userId = UserHandle.getCallingUserId();
16930        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16931    }
16932
16933    @Override
16934    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16935            final IPackageDataObserver observer) {
16936        mContext.enforceCallingOrSelfPermission(
16937                android.Manifest.permission.DELETE_CACHE_FILES, null);
16938        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16939                /* requireFullPermission= */ true, /* checkShell= */ false,
16940                "delete application cache files");
16941
16942        final PackageParser.Package pkg;
16943        synchronized (mPackages) {
16944            pkg = mPackages.get(packageName);
16945        }
16946
16947        // Queue up an async operation since the package deletion may take a little while.
16948        mHandler.post(new Runnable() {
16949            public void run() {
16950                synchronized (mInstallLock) {
16951                    final int flags = StorageManager.FLAG_STORAGE_DE
16952                            | StorageManager.FLAG_STORAGE_CE;
16953                    // We're only clearing cache files, so we don't care if the
16954                    // app is unfrozen and still able to run
16955                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16956                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16957                }
16958                clearExternalStorageDataSync(packageName, userId, false);
16959                if (observer != null) {
16960                    try {
16961                        observer.onRemoveCompleted(packageName, true);
16962                    } catch (RemoteException e) {
16963                        Log.i(TAG, "Observer no longer exists.");
16964                    }
16965                }
16966            }
16967        });
16968    }
16969
16970    @Override
16971    public void getPackageSizeInfo(final String packageName, int userHandle,
16972            final IPackageStatsObserver observer) {
16973        mContext.enforceCallingOrSelfPermission(
16974                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16975        if (packageName == null) {
16976            throw new IllegalArgumentException("Attempt to get size of null packageName");
16977        }
16978
16979        PackageStats stats = new PackageStats(packageName, userHandle);
16980
16981        /*
16982         * Queue up an async operation since the package measurement may take a
16983         * little while.
16984         */
16985        Message msg = mHandler.obtainMessage(INIT_COPY);
16986        msg.obj = new MeasureParams(stats, observer);
16987        mHandler.sendMessage(msg);
16988    }
16989
16990    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16991        final PackageSetting ps;
16992        synchronized (mPackages) {
16993            ps = mSettings.mPackages.get(packageName);
16994            if (ps == null) {
16995                Slog.w(TAG, "Failed to find settings for " + packageName);
16996                return false;
16997            }
16998        }
16999        try {
17000            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17001                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17002                    ps.getCeDataInode(userId), ps.codePathString, stats);
17003        } catch (InstallerException e) {
17004            Slog.w(TAG, String.valueOf(e));
17005            return false;
17006        }
17007
17008        // For now, ignore code size of packages on system partition
17009        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17010            stats.codeSize = 0;
17011        }
17012
17013        return true;
17014    }
17015
17016    private int getUidTargetSdkVersionLockedLPr(int uid) {
17017        Object obj = mSettings.getUserIdLPr(uid);
17018        if (obj instanceof SharedUserSetting) {
17019            final SharedUserSetting sus = (SharedUserSetting) obj;
17020            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17021            final Iterator<PackageSetting> it = sus.packages.iterator();
17022            while (it.hasNext()) {
17023                final PackageSetting ps = it.next();
17024                if (ps.pkg != null) {
17025                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17026                    if (v < vers) vers = v;
17027                }
17028            }
17029            return vers;
17030        } else if (obj instanceof PackageSetting) {
17031            final PackageSetting ps = (PackageSetting) obj;
17032            if (ps.pkg != null) {
17033                return ps.pkg.applicationInfo.targetSdkVersion;
17034            }
17035        }
17036        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17037    }
17038
17039    @Override
17040    public void addPreferredActivity(IntentFilter filter, int match,
17041            ComponentName[] set, ComponentName activity, int userId) {
17042        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17043                "Adding preferred");
17044    }
17045
17046    private void addPreferredActivityInternal(IntentFilter filter, int match,
17047            ComponentName[] set, ComponentName activity, boolean always, int userId,
17048            String opname) {
17049        // writer
17050        int callingUid = Binder.getCallingUid();
17051        enforceCrossUserPermission(callingUid, userId,
17052                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17053        if (filter.countActions() == 0) {
17054            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17055            return;
17056        }
17057        synchronized (mPackages) {
17058            if (mContext.checkCallingOrSelfPermission(
17059                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17060                    != PackageManager.PERMISSION_GRANTED) {
17061                if (getUidTargetSdkVersionLockedLPr(callingUid)
17062                        < Build.VERSION_CODES.FROYO) {
17063                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17064                            + callingUid);
17065                    return;
17066                }
17067                mContext.enforceCallingOrSelfPermission(
17068                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17069            }
17070
17071            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17072            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17073                    + userId + ":");
17074            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17075            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17076            scheduleWritePackageRestrictionsLocked(userId);
17077            postPreferredActivityChangedBroadcast(userId);
17078        }
17079    }
17080
17081    private void postPreferredActivityChangedBroadcast(int userId) {
17082        mHandler.post(() -> {
17083            final IActivityManager am = ActivityManagerNative.getDefault();
17084            if (am == null) {
17085                return;
17086            }
17087
17088            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17089            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17090            try {
17091                am.broadcastIntent(null, intent, null, null,
17092                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17093                        null, false, false, userId);
17094            } catch (RemoteException e) {
17095            }
17096        });
17097    }
17098
17099    @Override
17100    public void replacePreferredActivity(IntentFilter filter, int match,
17101            ComponentName[] set, ComponentName activity, int userId) {
17102        if (filter.countActions() != 1) {
17103            throw new IllegalArgumentException(
17104                    "replacePreferredActivity expects filter to have only 1 action.");
17105        }
17106        if (filter.countDataAuthorities() != 0
17107                || filter.countDataPaths() != 0
17108                || filter.countDataSchemes() > 1
17109                || filter.countDataTypes() != 0) {
17110            throw new IllegalArgumentException(
17111                    "replacePreferredActivity expects filter to have no data authorities, " +
17112                    "paths, or types; and at most one scheme.");
17113        }
17114
17115        final int callingUid = Binder.getCallingUid();
17116        enforceCrossUserPermission(callingUid, userId,
17117                true /* requireFullPermission */, false /* checkShell */,
17118                "replace preferred activity");
17119        synchronized (mPackages) {
17120            if (mContext.checkCallingOrSelfPermission(
17121                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17122                    != PackageManager.PERMISSION_GRANTED) {
17123                if (getUidTargetSdkVersionLockedLPr(callingUid)
17124                        < Build.VERSION_CODES.FROYO) {
17125                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17126                            + Binder.getCallingUid());
17127                    return;
17128                }
17129                mContext.enforceCallingOrSelfPermission(
17130                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17131            }
17132
17133            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17134            if (pir != null) {
17135                // Get all of the existing entries that exactly match this filter.
17136                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17137                if (existing != null && existing.size() == 1) {
17138                    PreferredActivity cur = existing.get(0);
17139                    if (DEBUG_PREFERRED) {
17140                        Slog.i(TAG, "Checking replace of preferred:");
17141                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17142                        if (!cur.mPref.mAlways) {
17143                            Slog.i(TAG, "  -- CUR; not mAlways!");
17144                        } else {
17145                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17146                            Slog.i(TAG, "  -- CUR: mSet="
17147                                    + Arrays.toString(cur.mPref.mSetComponents));
17148                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17149                            Slog.i(TAG, "  -- NEW: mMatch="
17150                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17151                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17152                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17153                        }
17154                    }
17155                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17156                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17157                            && cur.mPref.sameSet(set)) {
17158                        // Setting the preferred activity to what it happens to be already
17159                        if (DEBUG_PREFERRED) {
17160                            Slog.i(TAG, "Replacing with same preferred activity "
17161                                    + cur.mPref.mShortComponent + " for user "
17162                                    + userId + ":");
17163                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17164                        }
17165                        return;
17166                    }
17167                }
17168
17169                if (existing != null) {
17170                    if (DEBUG_PREFERRED) {
17171                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17172                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17173                    }
17174                    for (int i = 0; i < existing.size(); i++) {
17175                        PreferredActivity pa = existing.get(i);
17176                        if (DEBUG_PREFERRED) {
17177                            Slog.i(TAG, "Removing existing preferred activity "
17178                                    + pa.mPref.mComponent + ":");
17179                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17180                        }
17181                        pir.removeFilter(pa);
17182                    }
17183                }
17184            }
17185            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17186                    "Replacing preferred");
17187        }
17188    }
17189
17190    @Override
17191    public void clearPackagePreferredActivities(String packageName) {
17192        final int uid = Binder.getCallingUid();
17193        // writer
17194        synchronized (mPackages) {
17195            PackageParser.Package pkg = mPackages.get(packageName);
17196            if (pkg == null || pkg.applicationInfo.uid != uid) {
17197                if (mContext.checkCallingOrSelfPermission(
17198                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17199                        != PackageManager.PERMISSION_GRANTED) {
17200                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17201                            < Build.VERSION_CODES.FROYO) {
17202                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17203                                + Binder.getCallingUid());
17204                        return;
17205                    }
17206                    mContext.enforceCallingOrSelfPermission(
17207                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17208                }
17209            }
17210
17211            int user = UserHandle.getCallingUserId();
17212            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17213                scheduleWritePackageRestrictionsLocked(user);
17214            }
17215        }
17216    }
17217
17218    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17219    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17220        ArrayList<PreferredActivity> removed = null;
17221        boolean changed = false;
17222        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17223            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17224            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17225            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17226                continue;
17227            }
17228            Iterator<PreferredActivity> it = pir.filterIterator();
17229            while (it.hasNext()) {
17230                PreferredActivity pa = it.next();
17231                // Mark entry for removal only if it matches the package name
17232                // and the entry is of type "always".
17233                if (packageName == null ||
17234                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17235                                && pa.mPref.mAlways)) {
17236                    if (removed == null) {
17237                        removed = new ArrayList<PreferredActivity>();
17238                    }
17239                    removed.add(pa);
17240                }
17241            }
17242            if (removed != null) {
17243                for (int j=0; j<removed.size(); j++) {
17244                    PreferredActivity pa = removed.get(j);
17245                    pir.removeFilter(pa);
17246                }
17247                changed = true;
17248            }
17249        }
17250        if (changed) {
17251            postPreferredActivityChangedBroadcast(userId);
17252        }
17253        return changed;
17254    }
17255
17256    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17257    private void clearIntentFilterVerificationsLPw(int userId) {
17258        final int packageCount = mPackages.size();
17259        for (int i = 0; i < packageCount; i++) {
17260            PackageParser.Package pkg = mPackages.valueAt(i);
17261            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17262        }
17263    }
17264
17265    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17266    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17267        if (userId == UserHandle.USER_ALL) {
17268            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17269                    sUserManager.getUserIds())) {
17270                for (int oneUserId : sUserManager.getUserIds()) {
17271                    scheduleWritePackageRestrictionsLocked(oneUserId);
17272                }
17273            }
17274        } else {
17275            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17276                scheduleWritePackageRestrictionsLocked(userId);
17277            }
17278        }
17279    }
17280
17281    void clearDefaultBrowserIfNeeded(String packageName) {
17282        for (int oneUserId : sUserManager.getUserIds()) {
17283            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17284            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17285            if (packageName.equals(defaultBrowserPackageName)) {
17286                setDefaultBrowserPackageName(null, oneUserId);
17287            }
17288        }
17289    }
17290
17291    @Override
17292    public void resetApplicationPreferences(int userId) {
17293        mContext.enforceCallingOrSelfPermission(
17294                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17295        final long identity = Binder.clearCallingIdentity();
17296        // writer
17297        try {
17298            synchronized (mPackages) {
17299                clearPackagePreferredActivitiesLPw(null, userId);
17300                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17301                // TODO: We have to reset the default SMS and Phone. This requires
17302                // significant refactoring to keep all default apps in the package
17303                // manager (cleaner but more work) or have the services provide
17304                // callbacks to the package manager to request a default app reset.
17305                applyFactoryDefaultBrowserLPw(userId);
17306                clearIntentFilterVerificationsLPw(userId);
17307                primeDomainVerificationsLPw(userId);
17308                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17309                scheduleWritePackageRestrictionsLocked(userId);
17310            }
17311            resetNetworkPolicies(userId);
17312        } finally {
17313            Binder.restoreCallingIdentity(identity);
17314        }
17315    }
17316
17317    @Override
17318    public int getPreferredActivities(List<IntentFilter> outFilters,
17319            List<ComponentName> outActivities, String packageName) {
17320
17321        int num = 0;
17322        final int userId = UserHandle.getCallingUserId();
17323        // reader
17324        synchronized (mPackages) {
17325            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17326            if (pir != null) {
17327                final Iterator<PreferredActivity> it = pir.filterIterator();
17328                while (it.hasNext()) {
17329                    final PreferredActivity pa = it.next();
17330                    if (packageName == null
17331                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17332                                    && pa.mPref.mAlways)) {
17333                        if (outFilters != null) {
17334                            outFilters.add(new IntentFilter(pa));
17335                        }
17336                        if (outActivities != null) {
17337                            outActivities.add(pa.mPref.mComponent);
17338                        }
17339                    }
17340                }
17341            }
17342        }
17343
17344        return num;
17345    }
17346
17347    @Override
17348    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17349            int userId) {
17350        int callingUid = Binder.getCallingUid();
17351        if (callingUid != Process.SYSTEM_UID) {
17352            throw new SecurityException(
17353                    "addPersistentPreferredActivity can only be run by the system");
17354        }
17355        if (filter.countActions() == 0) {
17356            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17357            return;
17358        }
17359        synchronized (mPackages) {
17360            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17361                    ":");
17362            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17363            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17364                    new PersistentPreferredActivity(filter, activity));
17365            scheduleWritePackageRestrictionsLocked(userId);
17366            postPreferredActivityChangedBroadcast(userId);
17367        }
17368    }
17369
17370    @Override
17371    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17372        int callingUid = Binder.getCallingUid();
17373        if (callingUid != Process.SYSTEM_UID) {
17374            throw new SecurityException(
17375                    "clearPackagePersistentPreferredActivities can only be run by the system");
17376        }
17377        ArrayList<PersistentPreferredActivity> removed = null;
17378        boolean changed = false;
17379        synchronized (mPackages) {
17380            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17381                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17382                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17383                        .valueAt(i);
17384                if (userId != thisUserId) {
17385                    continue;
17386                }
17387                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17388                while (it.hasNext()) {
17389                    PersistentPreferredActivity ppa = it.next();
17390                    // Mark entry for removal only if it matches the package name.
17391                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17392                        if (removed == null) {
17393                            removed = new ArrayList<PersistentPreferredActivity>();
17394                        }
17395                        removed.add(ppa);
17396                    }
17397                }
17398                if (removed != null) {
17399                    for (int j=0; j<removed.size(); j++) {
17400                        PersistentPreferredActivity ppa = removed.get(j);
17401                        ppir.removeFilter(ppa);
17402                    }
17403                    changed = true;
17404                }
17405            }
17406
17407            if (changed) {
17408                scheduleWritePackageRestrictionsLocked(userId);
17409                postPreferredActivityChangedBroadcast(userId);
17410            }
17411        }
17412    }
17413
17414    /**
17415     * Common machinery for picking apart a restored XML blob and passing
17416     * it to a caller-supplied functor to be applied to the running system.
17417     */
17418    private void restoreFromXml(XmlPullParser parser, int userId,
17419            String expectedStartTag, BlobXmlRestorer functor)
17420            throws IOException, XmlPullParserException {
17421        int type;
17422        while ((type = parser.next()) != XmlPullParser.START_TAG
17423                && type != XmlPullParser.END_DOCUMENT) {
17424        }
17425        if (type != XmlPullParser.START_TAG) {
17426            // oops didn't find a start tag?!
17427            if (DEBUG_BACKUP) {
17428                Slog.e(TAG, "Didn't find start tag during restore");
17429            }
17430            return;
17431        }
17432Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17433        // this is supposed to be TAG_PREFERRED_BACKUP
17434        if (!expectedStartTag.equals(parser.getName())) {
17435            if (DEBUG_BACKUP) {
17436                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17437            }
17438            return;
17439        }
17440
17441        // skip interfering stuff, then we're aligned with the backing implementation
17442        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17443Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17444        functor.apply(parser, userId);
17445    }
17446
17447    private interface BlobXmlRestorer {
17448        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17449    }
17450
17451    /**
17452     * Non-Binder method, support for the backup/restore mechanism: write the
17453     * full set of preferred activities in its canonical XML format.  Returns the
17454     * XML output as a byte array, or null if there is none.
17455     */
17456    @Override
17457    public byte[] getPreferredActivityBackup(int userId) {
17458        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17459            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17460        }
17461
17462        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17463        try {
17464            final XmlSerializer serializer = new FastXmlSerializer();
17465            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17466            serializer.startDocument(null, true);
17467            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17468
17469            synchronized (mPackages) {
17470                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17471            }
17472
17473            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17474            serializer.endDocument();
17475            serializer.flush();
17476        } catch (Exception e) {
17477            if (DEBUG_BACKUP) {
17478                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17479            }
17480            return null;
17481        }
17482
17483        return dataStream.toByteArray();
17484    }
17485
17486    @Override
17487    public void restorePreferredActivities(byte[] backup, int userId) {
17488        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17489            throw new SecurityException("Only the system may call restorePreferredActivities()");
17490        }
17491
17492        try {
17493            final XmlPullParser parser = Xml.newPullParser();
17494            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17495            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17496                    new BlobXmlRestorer() {
17497                        @Override
17498                        public void apply(XmlPullParser parser, int userId)
17499                                throws XmlPullParserException, IOException {
17500                            synchronized (mPackages) {
17501                                mSettings.readPreferredActivitiesLPw(parser, userId);
17502                            }
17503                        }
17504                    } );
17505        } catch (Exception e) {
17506            if (DEBUG_BACKUP) {
17507                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17508            }
17509        }
17510    }
17511
17512    /**
17513     * Non-Binder method, support for the backup/restore mechanism: write the
17514     * default browser (etc) settings in its canonical XML format.  Returns the default
17515     * browser XML representation as a byte array, or null if there is none.
17516     */
17517    @Override
17518    public byte[] getDefaultAppsBackup(int userId) {
17519        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17520            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17521        }
17522
17523        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17524        try {
17525            final XmlSerializer serializer = new FastXmlSerializer();
17526            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17527            serializer.startDocument(null, true);
17528            serializer.startTag(null, TAG_DEFAULT_APPS);
17529
17530            synchronized (mPackages) {
17531                mSettings.writeDefaultAppsLPr(serializer, userId);
17532            }
17533
17534            serializer.endTag(null, TAG_DEFAULT_APPS);
17535            serializer.endDocument();
17536            serializer.flush();
17537        } catch (Exception e) {
17538            if (DEBUG_BACKUP) {
17539                Slog.e(TAG, "Unable to write default apps for backup", e);
17540            }
17541            return null;
17542        }
17543
17544        return dataStream.toByteArray();
17545    }
17546
17547    @Override
17548    public void restoreDefaultApps(byte[] backup, int userId) {
17549        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17550            throw new SecurityException("Only the system may call restoreDefaultApps()");
17551        }
17552
17553        try {
17554            final XmlPullParser parser = Xml.newPullParser();
17555            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17556            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17557                    new BlobXmlRestorer() {
17558                        @Override
17559                        public void apply(XmlPullParser parser, int userId)
17560                                throws XmlPullParserException, IOException {
17561                            synchronized (mPackages) {
17562                                mSettings.readDefaultAppsLPw(parser, userId);
17563                            }
17564                        }
17565                    } );
17566        } catch (Exception e) {
17567            if (DEBUG_BACKUP) {
17568                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17569            }
17570        }
17571    }
17572
17573    @Override
17574    public byte[] getIntentFilterVerificationBackup(int userId) {
17575        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17576            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17577        }
17578
17579        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17580        try {
17581            final XmlSerializer serializer = new FastXmlSerializer();
17582            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17583            serializer.startDocument(null, true);
17584            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17585
17586            synchronized (mPackages) {
17587                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17588            }
17589
17590            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17591            serializer.endDocument();
17592            serializer.flush();
17593        } catch (Exception e) {
17594            if (DEBUG_BACKUP) {
17595                Slog.e(TAG, "Unable to write default apps for backup", e);
17596            }
17597            return null;
17598        }
17599
17600        return dataStream.toByteArray();
17601    }
17602
17603    @Override
17604    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17605        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17606            throw new SecurityException("Only the system may call restorePreferredActivities()");
17607        }
17608
17609        try {
17610            final XmlPullParser parser = Xml.newPullParser();
17611            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17612            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17613                    new BlobXmlRestorer() {
17614                        @Override
17615                        public void apply(XmlPullParser parser, int userId)
17616                                throws XmlPullParserException, IOException {
17617                            synchronized (mPackages) {
17618                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17619                                mSettings.writeLPr();
17620                            }
17621                        }
17622                    } );
17623        } catch (Exception e) {
17624            if (DEBUG_BACKUP) {
17625                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17626            }
17627        }
17628    }
17629
17630    @Override
17631    public byte[] getPermissionGrantBackup(int userId) {
17632        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17633            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17634        }
17635
17636        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17637        try {
17638            final XmlSerializer serializer = new FastXmlSerializer();
17639            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17640            serializer.startDocument(null, true);
17641            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17642
17643            synchronized (mPackages) {
17644                serializeRuntimePermissionGrantsLPr(serializer, userId);
17645            }
17646
17647            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17648            serializer.endDocument();
17649            serializer.flush();
17650        } catch (Exception e) {
17651            if (DEBUG_BACKUP) {
17652                Slog.e(TAG, "Unable to write default apps for backup", e);
17653            }
17654            return null;
17655        }
17656
17657        return dataStream.toByteArray();
17658    }
17659
17660    @Override
17661    public void restorePermissionGrants(byte[] backup, int userId) {
17662        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17663            throw new SecurityException("Only the system may call restorePermissionGrants()");
17664        }
17665
17666        try {
17667            final XmlPullParser parser = Xml.newPullParser();
17668            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17669            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17670                    new BlobXmlRestorer() {
17671                        @Override
17672                        public void apply(XmlPullParser parser, int userId)
17673                                throws XmlPullParserException, IOException {
17674                            synchronized (mPackages) {
17675                                processRestoredPermissionGrantsLPr(parser, userId);
17676                            }
17677                        }
17678                    } );
17679        } catch (Exception e) {
17680            if (DEBUG_BACKUP) {
17681                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17682            }
17683        }
17684    }
17685
17686    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17687            throws IOException {
17688        serializer.startTag(null, TAG_ALL_GRANTS);
17689
17690        final int N = mSettings.mPackages.size();
17691        for (int i = 0; i < N; i++) {
17692            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17693            boolean pkgGrantsKnown = false;
17694
17695            PermissionsState packagePerms = ps.getPermissionsState();
17696
17697            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17698                final int grantFlags = state.getFlags();
17699                // only look at grants that are not system/policy fixed
17700                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17701                    final boolean isGranted = state.isGranted();
17702                    // And only back up the user-twiddled state bits
17703                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17704                        final String packageName = mSettings.mPackages.keyAt(i);
17705                        if (!pkgGrantsKnown) {
17706                            serializer.startTag(null, TAG_GRANT);
17707                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17708                            pkgGrantsKnown = true;
17709                        }
17710
17711                        final boolean userSet =
17712                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17713                        final boolean userFixed =
17714                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17715                        final boolean revoke =
17716                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17717
17718                        serializer.startTag(null, TAG_PERMISSION);
17719                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17720                        if (isGranted) {
17721                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17722                        }
17723                        if (userSet) {
17724                            serializer.attribute(null, ATTR_USER_SET, "true");
17725                        }
17726                        if (userFixed) {
17727                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17728                        }
17729                        if (revoke) {
17730                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17731                        }
17732                        serializer.endTag(null, TAG_PERMISSION);
17733                    }
17734                }
17735            }
17736
17737            if (pkgGrantsKnown) {
17738                serializer.endTag(null, TAG_GRANT);
17739            }
17740        }
17741
17742        serializer.endTag(null, TAG_ALL_GRANTS);
17743    }
17744
17745    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17746            throws XmlPullParserException, IOException {
17747        String pkgName = null;
17748        int outerDepth = parser.getDepth();
17749        int type;
17750        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17751                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17752            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17753                continue;
17754            }
17755
17756            final String tagName = parser.getName();
17757            if (tagName.equals(TAG_GRANT)) {
17758                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17759                if (DEBUG_BACKUP) {
17760                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17761                }
17762            } else if (tagName.equals(TAG_PERMISSION)) {
17763
17764                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17765                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17766
17767                int newFlagSet = 0;
17768                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17769                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17770                }
17771                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17772                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17773                }
17774                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17775                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17776                }
17777                if (DEBUG_BACKUP) {
17778                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17779                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17780                }
17781                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17782                if (ps != null) {
17783                    // Already installed so we apply the grant immediately
17784                    if (DEBUG_BACKUP) {
17785                        Slog.v(TAG, "        + already installed; applying");
17786                    }
17787                    PermissionsState perms = ps.getPermissionsState();
17788                    BasePermission bp = mSettings.mPermissions.get(permName);
17789                    if (bp != null) {
17790                        if (isGranted) {
17791                            perms.grantRuntimePermission(bp, userId);
17792                        }
17793                        if (newFlagSet != 0) {
17794                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17795                        }
17796                    }
17797                } else {
17798                    // Need to wait for post-restore install to apply the grant
17799                    if (DEBUG_BACKUP) {
17800                        Slog.v(TAG, "        - not yet installed; saving for later");
17801                    }
17802                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17803                            isGranted, newFlagSet, userId);
17804                }
17805            } else {
17806                PackageManagerService.reportSettingsProblem(Log.WARN,
17807                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17808                XmlUtils.skipCurrentTag(parser);
17809            }
17810        }
17811
17812        scheduleWriteSettingsLocked();
17813        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17814    }
17815
17816    @Override
17817    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17818            int sourceUserId, int targetUserId, int flags) {
17819        mContext.enforceCallingOrSelfPermission(
17820                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17821        int callingUid = Binder.getCallingUid();
17822        enforceOwnerRights(ownerPackage, callingUid);
17823        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17824        if (intentFilter.countActions() == 0) {
17825            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17826            return;
17827        }
17828        synchronized (mPackages) {
17829            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17830                    ownerPackage, targetUserId, flags);
17831            CrossProfileIntentResolver resolver =
17832                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17833            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17834            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17835            if (existing != null) {
17836                int size = existing.size();
17837                for (int i = 0; i < size; i++) {
17838                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17839                        return;
17840                    }
17841                }
17842            }
17843            resolver.addFilter(newFilter);
17844            scheduleWritePackageRestrictionsLocked(sourceUserId);
17845        }
17846    }
17847
17848    @Override
17849    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17850        mContext.enforceCallingOrSelfPermission(
17851                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17852        int callingUid = Binder.getCallingUid();
17853        enforceOwnerRights(ownerPackage, callingUid);
17854        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17855        synchronized (mPackages) {
17856            CrossProfileIntentResolver resolver =
17857                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17858            ArraySet<CrossProfileIntentFilter> set =
17859                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17860            for (CrossProfileIntentFilter filter : set) {
17861                if (filter.getOwnerPackage().equals(ownerPackage)) {
17862                    resolver.removeFilter(filter);
17863                }
17864            }
17865            scheduleWritePackageRestrictionsLocked(sourceUserId);
17866        }
17867    }
17868
17869    // Enforcing that callingUid is owning pkg on userId
17870    private void enforceOwnerRights(String pkg, int callingUid) {
17871        // The system owns everything.
17872        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17873            return;
17874        }
17875        int callingUserId = UserHandle.getUserId(callingUid);
17876        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17877        if (pi == null) {
17878            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17879                    + callingUserId);
17880        }
17881        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17882            throw new SecurityException("Calling uid " + callingUid
17883                    + " does not own package " + pkg);
17884        }
17885    }
17886
17887    @Override
17888    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17889        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17890    }
17891
17892    private Intent getHomeIntent() {
17893        Intent intent = new Intent(Intent.ACTION_MAIN);
17894        intent.addCategory(Intent.CATEGORY_HOME);
17895        intent.addCategory(Intent.CATEGORY_DEFAULT);
17896        return intent;
17897    }
17898
17899    private IntentFilter getHomeFilter() {
17900        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17901        filter.addCategory(Intent.CATEGORY_HOME);
17902        filter.addCategory(Intent.CATEGORY_DEFAULT);
17903        return filter;
17904    }
17905
17906    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17907            int userId) {
17908        Intent intent  = getHomeIntent();
17909        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17910                PackageManager.GET_META_DATA, userId);
17911        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17912                true, false, false, userId);
17913
17914        allHomeCandidates.clear();
17915        if (list != null) {
17916            for (ResolveInfo ri : list) {
17917                allHomeCandidates.add(ri);
17918            }
17919        }
17920        return (preferred == null || preferred.activityInfo == null)
17921                ? null
17922                : new ComponentName(preferred.activityInfo.packageName,
17923                        preferred.activityInfo.name);
17924    }
17925
17926    @Override
17927    public void setHomeActivity(ComponentName comp, int userId) {
17928        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17929        getHomeActivitiesAsUser(homeActivities, userId);
17930
17931        boolean found = false;
17932
17933        final int size = homeActivities.size();
17934        final ComponentName[] set = new ComponentName[size];
17935        for (int i = 0; i < size; i++) {
17936            final ResolveInfo candidate = homeActivities.get(i);
17937            final ActivityInfo info = candidate.activityInfo;
17938            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17939            set[i] = activityName;
17940            if (!found && activityName.equals(comp)) {
17941                found = true;
17942            }
17943        }
17944        if (!found) {
17945            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17946                    + userId);
17947        }
17948        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17949                set, comp, userId);
17950    }
17951
17952    private @Nullable String getSetupWizardPackageName() {
17953        final Intent intent = new Intent(Intent.ACTION_MAIN);
17954        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17955
17956        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17957                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17958                        | MATCH_DISABLED_COMPONENTS,
17959                UserHandle.myUserId());
17960        if (matches.size() == 1) {
17961            return matches.get(0).getComponentInfo().packageName;
17962        } else {
17963            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17964                    + ": matches=" + matches);
17965            return null;
17966        }
17967    }
17968
17969    private @Nullable String getStorageManagerPackageName() {
17970        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17971
17972        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17973                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17974                        | MATCH_DISABLED_COMPONENTS,
17975                UserHandle.myUserId());
17976        if (matches.size() == 1) {
17977            return matches.get(0).getComponentInfo().packageName;
17978        } else {
17979            Slog.e(TAG, "There should probably be exactly one storage manager; found "
17980                    + matches.size() + ": matches=" + matches);
17981            return null;
17982        }
17983    }
17984
17985    @Override
17986    public void setApplicationEnabledSetting(String appPackageName,
17987            int newState, int flags, int userId, String callingPackage) {
17988        if (!sUserManager.exists(userId)) return;
17989        if (callingPackage == null) {
17990            callingPackage = Integer.toString(Binder.getCallingUid());
17991        }
17992        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17993    }
17994
17995    @Override
17996    public void setComponentEnabledSetting(ComponentName componentName,
17997            int newState, int flags, int userId) {
17998        if (!sUserManager.exists(userId)) return;
17999        setEnabledSetting(componentName.getPackageName(),
18000                componentName.getClassName(), newState, flags, userId, null);
18001    }
18002
18003    private void setEnabledSetting(final String packageName, String className, int newState,
18004            final int flags, int userId, String callingPackage) {
18005        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18006              || newState == COMPONENT_ENABLED_STATE_ENABLED
18007              || newState == COMPONENT_ENABLED_STATE_DISABLED
18008              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18009              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18010            throw new IllegalArgumentException("Invalid new component state: "
18011                    + newState);
18012        }
18013        PackageSetting pkgSetting;
18014        final int uid = Binder.getCallingUid();
18015        final int permission;
18016        if (uid == Process.SYSTEM_UID) {
18017            permission = PackageManager.PERMISSION_GRANTED;
18018        } else {
18019            permission = mContext.checkCallingOrSelfPermission(
18020                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18021        }
18022        enforceCrossUserPermission(uid, userId,
18023                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18024        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18025        boolean sendNow = false;
18026        boolean isApp = (className == null);
18027        String componentName = isApp ? packageName : className;
18028        int packageUid = -1;
18029        ArrayList<String> components;
18030
18031        // writer
18032        synchronized (mPackages) {
18033            pkgSetting = mSettings.mPackages.get(packageName);
18034            if (pkgSetting == null) {
18035                if (className == null) {
18036                    throw new IllegalArgumentException("Unknown package: " + packageName);
18037                }
18038                throw new IllegalArgumentException(
18039                        "Unknown component: " + packageName + "/" + className);
18040            }
18041        }
18042
18043        // Limit who can change which apps
18044        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18045            // Don't allow apps that don't have permission to modify other apps
18046            if (!allowedByPermission) {
18047                throw new SecurityException(
18048                        "Permission Denial: attempt to change component state from pid="
18049                        + Binder.getCallingPid()
18050                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18051            }
18052            // Don't allow changing protected packages.
18053            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18054                throw new SecurityException("Cannot disable a protected package: " + packageName);
18055            }
18056        }
18057
18058        synchronized (mPackages) {
18059            if (uid == Process.SHELL_UID) {
18060                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18061                int oldState = pkgSetting.getEnabled(userId);
18062                if (className == null
18063                    &&
18064                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18065                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18066                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18067                    &&
18068                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18069                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18070                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18071                    // ok
18072                } else {
18073                    throw new SecurityException(
18074                            "Shell cannot change component state for " + packageName + "/"
18075                            + className + " to " + newState);
18076                }
18077            }
18078            if (className == null) {
18079                // We're dealing with an application/package level state change
18080                if (pkgSetting.getEnabled(userId) == newState) {
18081                    // Nothing to do
18082                    return;
18083                }
18084                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18085                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18086                    // Don't care about who enables an app.
18087                    callingPackage = null;
18088                }
18089                pkgSetting.setEnabled(newState, userId, callingPackage);
18090                // pkgSetting.pkg.mSetEnabled = newState;
18091            } else {
18092                // We're dealing with a component level state change
18093                // First, verify that this is a valid class name.
18094                PackageParser.Package pkg = pkgSetting.pkg;
18095                if (pkg == null || !pkg.hasComponentClassName(className)) {
18096                    if (pkg != null &&
18097                            pkg.applicationInfo.targetSdkVersion >=
18098                                    Build.VERSION_CODES.JELLY_BEAN) {
18099                        throw new IllegalArgumentException("Component class " + className
18100                                + " does not exist in " + packageName);
18101                    } else {
18102                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18103                                + className + " does not exist in " + packageName);
18104                    }
18105                }
18106                switch (newState) {
18107                case COMPONENT_ENABLED_STATE_ENABLED:
18108                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18109                        return;
18110                    }
18111                    break;
18112                case COMPONENT_ENABLED_STATE_DISABLED:
18113                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18114                        return;
18115                    }
18116                    break;
18117                case COMPONENT_ENABLED_STATE_DEFAULT:
18118                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18119                        return;
18120                    }
18121                    break;
18122                default:
18123                    Slog.e(TAG, "Invalid new component state: " + newState);
18124                    return;
18125                }
18126            }
18127            scheduleWritePackageRestrictionsLocked(userId);
18128            components = mPendingBroadcasts.get(userId, packageName);
18129            final boolean newPackage = components == null;
18130            if (newPackage) {
18131                components = new ArrayList<String>();
18132            }
18133            if (!components.contains(componentName)) {
18134                components.add(componentName);
18135            }
18136            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18137                sendNow = true;
18138                // Purge entry from pending broadcast list if another one exists already
18139                // since we are sending one right away.
18140                mPendingBroadcasts.remove(userId, packageName);
18141            } else {
18142                if (newPackage) {
18143                    mPendingBroadcasts.put(userId, packageName, components);
18144                }
18145                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18146                    // Schedule a message
18147                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18148                }
18149            }
18150        }
18151
18152        long callingId = Binder.clearCallingIdentity();
18153        try {
18154            if (sendNow) {
18155                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18156                sendPackageChangedBroadcast(packageName,
18157                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18158            }
18159        } finally {
18160            Binder.restoreCallingIdentity(callingId);
18161        }
18162    }
18163
18164    @Override
18165    public void flushPackageRestrictionsAsUser(int userId) {
18166        if (!sUserManager.exists(userId)) {
18167            return;
18168        }
18169        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18170                false /* checkShell */, "flushPackageRestrictions");
18171        synchronized (mPackages) {
18172            mSettings.writePackageRestrictionsLPr(userId);
18173            mDirtyUsers.remove(userId);
18174            if (mDirtyUsers.isEmpty()) {
18175                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18176            }
18177        }
18178    }
18179
18180    private void sendPackageChangedBroadcast(String packageName,
18181            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18182        if (DEBUG_INSTALL)
18183            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18184                    + componentNames);
18185        Bundle extras = new Bundle(4);
18186        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18187        String nameList[] = new String[componentNames.size()];
18188        componentNames.toArray(nameList);
18189        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18190        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18191        extras.putInt(Intent.EXTRA_UID, packageUid);
18192        // If this is not reporting a change of the overall package, then only send it
18193        // to registered receivers.  We don't want to launch a swath of apps for every
18194        // little component state change.
18195        final int flags = !componentNames.contains(packageName)
18196                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18197        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18198                new int[] {UserHandle.getUserId(packageUid)});
18199    }
18200
18201    @Override
18202    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18203        if (!sUserManager.exists(userId)) return;
18204        final int uid = Binder.getCallingUid();
18205        final int permission = mContext.checkCallingOrSelfPermission(
18206                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18207        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18208        enforceCrossUserPermission(uid, userId,
18209                true /* requireFullPermission */, true /* checkShell */, "stop package");
18210        // writer
18211        synchronized (mPackages) {
18212            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18213                    allowedByPermission, uid, userId)) {
18214                scheduleWritePackageRestrictionsLocked(userId);
18215            }
18216        }
18217    }
18218
18219    @Override
18220    public String getInstallerPackageName(String packageName) {
18221        // reader
18222        synchronized (mPackages) {
18223            return mSettings.getInstallerPackageNameLPr(packageName);
18224        }
18225    }
18226
18227    public boolean isOrphaned(String packageName) {
18228        // reader
18229        synchronized (mPackages) {
18230            return mSettings.isOrphaned(packageName);
18231        }
18232    }
18233
18234    @Override
18235    public int getApplicationEnabledSetting(String packageName, int userId) {
18236        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18237        int uid = Binder.getCallingUid();
18238        enforceCrossUserPermission(uid, userId,
18239                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18240        // reader
18241        synchronized (mPackages) {
18242            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18243        }
18244    }
18245
18246    @Override
18247    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18248        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18249        int uid = Binder.getCallingUid();
18250        enforceCrossUserPermission(uid, userId,
18251                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18252        // reader
18253        synchronized (mPackages) {
18254            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18255        }
18256    }
18257
18258    @Override
18259    public void enterSafeMode() {
18260        enforceSystemOrRoot("Only the system can request entering safe mode");
18261
18262        if (!mSystemReady) {
18263            mSafeMode = true;
18264        }
18265    }
18266
18267    @Override
18268    public void systemReady() {
18269        mSystemReady = true;
18270
18271        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18272        // disabled after already being started.
18273        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18274                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18275
18276        // Read the compatibilty setting when the system is ready.
18277        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18278                mContext.getContentResolver(),
18279                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18280        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18281        if (DEBUG_SETTINGS) {
18282            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18283        }
18284
18285        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18286
18287        synchronized (mPackages) {
18288            // Verify that all of the preferred activity components actually
18289            // exist.  It is possible for applications to be updated and at
18290            // that point remove a previously declared activity component that
18291            // had been set as a preferred activity.  We try to clean this up
18292            // the next time we encounter that preferred activity, but it is
18293            // possible for the user flow to never be able to return to that
18294            // situation so here we do a sanity check to make sure we haven't
18295            // left any junk around.
18296            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18297            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18298                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18299                removed.clear();
18300                for (PreferredActivity pa : pir.filterSet()) {
18301                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18302                        removed.add(pa);
18303                    }
18304                }
18305                if (removed.size() > 0) {
18306                    for (int r=0; r<removed.size(); r++) {
18307                        PreferredActivity pa = removed.get(r);
18308                        Slog.w(TAG, "Removing dangling preferred activity: "
18309                                + pa.mPref.mComponent);
18310                        pir.removeFilter(pa);
18311                    }
18312                    mSettings.writePackageRestrictionsLPr(
18313                            mSettings.mPreferredActivities.keyAt(i));
18314                }
18315            }
18316
18317            for (int userId : UserManagerService.getInstance().getUserIds()) {
18318                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18319                    grantPermissionsUserIds = ArrayUtils.appendInt(
18320                            grantPermissionsUserIds, userId);
18321                }
18322            }
18323        }
18324        sUserManager.systemReady();
18325
18326        // If we upgraded grant all default permissions before kicking off.
18327        for (int userId : grantPermissionsUserIds) {
18328            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18329        }
18330
18331        // If we did not grant default permissions, we preload from this the
18332        // default permission exceptions lazily to ensure we don't hit the
18333        // disk on a new user creation.
18334        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18335            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18336        }
18337
18338        // Kick off any messages waiting for system ready
18339        if (mPostSystemReadyMessages != null) {
18340            for (Message msg : mPostSystemReadyMessages) {
18341                msg.sendToTarget();
18342            }
18343            mPostSystemReadyMessages = null;
18344        }
18345
18346        // Watch for external volumes that come and go over time
18347        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18348        storage.registerListener(mStorageListener);
18349
18350        mInstallerService.systemReady();
18351        mPackageDexOptimizer.systemReady();
18352
18353        MountServiceInternal mountServiceInternal = LocalServices.getService(
18354                MountServiceInternal.class);
18355        mountServiceInternal.addExternalStoragePolicy(
18356                new MountServiceInternal.ExternalStorageMountPolicy() {
18357            @Override
18358            public int getMountMode(int uid, String packageName) {
18359                if (Process.isIsolated(uid)) {
18360                    return Zygote.MOUNT_EXTERNAL_NONE;
18361                }
18362                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18363                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18364                }
18365                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18366                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18367                }
18368                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18369                    return Zygote.MOUNT_EXTERNAL_READ;
18370                }
18371                return Zygote.MOUNT_EXTERNAL_WRITE;
18372            }
18373
18374            @Override
18375            public boolean hasExternalStorage(int uid, String packageName) {
18376                return true;
18377            }
18378        });
18379
18380        // Now that we're mostly running, clean up stale users and apps
18381        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18382        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18383    }
18384
18385    @Override
18386    public boolean isSafeMode() {
18387        return mSafeMode;
18388    }
18389
18390    @Override
18391    public boolean hasSystemUidErrors() {
18392        return mHasSystemUidErrors;
18393    }
18394
18395    static String arrayToString(int[] array) {
18396        StringBuffer buf = new StringBuffer(128);
18397        buf.append('[');
18398        if (array != null) {
18399            for (int i=0; i<array.length; i++) {
18400                if (i > 0) buf.append(", ");
18401                buf.append(array[i]);
18402            }
18403        }
18404        buf.append(']');
18405        return buf.toString();
18406    }
18407
18408    static class DumpState {
18409        public static final int DUMP_LIBS = 1 << 0;
18410        public static final int DUMP_FEATURES = 1 << 1;
18411        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18412        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18413        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18414        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18415        public static final int DUMP_PERMISSIONS = 1 << 6;
18416        public static final int DUMP_PACKAGES = 1 << 7;
18417        public static final int DUMP_SHARED_USERS = 1 << 8;
18418        public static final int DUMP_MESSAGES = 1 << 9;
18419        public static final int DUMP_PROVIDERS = 1 << 10;
18420        public static final int DUMP_VERIFIERS = 1 << 11;
18421        public static final int DUMP_PREFERRED = 1 << 12;
18422        public static final int DUMP_PREFERRED_XML = 1 << 13;
18423        public static final int DUMP_KEYSETS = 1 << 14;
18424        public static final int DUMP_VERSION = 1 << 15;
18425        public static final int DUMP_INSTALLS = 1 << 16;
18426        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18427        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18428        public static final int DUMP_FROZEN = 1 << 19;
18429        public static final int DUMP_DEXOPT = 1 << 20;
18430        public static final int DUMP_COMPILER_STATS = 1 << 21;
18431
18432        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18433
18434        private int mTypes;
18435
18436        private int mOptions;
18437
18438        private boolean mTitlePrinted;
18439
18440        private SharedUserSetting mSharedUser;
18441
18442        public boolean isDumping(int type) {
18443            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18444                return true;
18445            }
18446
18447            return (mTypes & type) != 0;
18448        }
18449
18450        public void setDump(int type) {
18451            mTypes |= type;
18452        }
18453
18454        public boolean isOptionEnabled(int option) {
18455            return (mOptions & option) != 0;
18456        }
18457
18458        public void setOptionEnabled(int option) {
18459            mOptions |= option;
18460        }
18461
18462        public boolean onTitlePrinted() {
18463            final boolean printed = mTitlePrinted;
18464            mTitlePrinted = true;
18465            return printed;
18466        }
18467
18468        public boolean getTitlePrinted() {
18469            return mTitlePrinted;
18470        }
18471
18472        public void setTitlePrinted(boolean enabled) {
18473            mTitlePrinted = enabled;
18474        }
18475
18476        public SharedUserSetting getSharedUser() {
18477            return mSharedUser;
18478        }
18479
18480        public void setSharedUser(SharedUserSetting user) {
18481            mSharedUser = user;
18482        }
18483    }
18484
18485    @Override
18486    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18487            FileDescriptor err, String[] args, ShellCallback callback,
18488            ResultReceiver resultReceiver) {
18489        (new PackageManagerShellCommand(this)).exec(
18490                this, in, out, err, args, callback, resultReceiver);
18491    }
18492
18493    @Override
18494    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18495        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18496                != PackageManager.PERMISSION_GRANTED) {
18497            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18498                    + Binder.getCallingPid()
18499                    + ", uid=" + Binder.getCallingUid()
18500                    + " without permission "
18501                    + android.Manifest.permission.DUMP);
18502            return;
18503        }
18504
18505        DumpState dumpState = new DumpState();
18506        boolean fullPreferred = false;
18507        boolean checkin = false;
18508
18509        String packageName = null;
18510        ArraySet<String> permissionNames = null;
18511
18512        int opti = 0;
18513        while (opti < args.length) {
18514            String opt = args[opti];
18515            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18516                break;
18517            }
18518            opti++;
18519
18520            if ("-a".equals(opt)) {
18521                // Right now we only know how to print all.
18522            } else if ("-h".equals(opt)) {
18523                pw.println("Package manager dump options:");
18524                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18525                pw.println("    --checkin: dump for a checkin");
18526                pw.println("    -f: print details of intent filters");
18527                pw.println("    -h: print this help");
18528                pw.println("  cmd may be one of:");
18529                pw.println("    l[ibraries]: list known shared libraries");
18530                pw.println("    f[eatures]: list device features");
18531                pw.println("    k[eysets]: print known keysets");
18532                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18533                pw.println("    perm[issions]: dump permissions");
18534                pw.println("    permission [name ...]: dump declaration and use of given permission");
18535                pw.println("    pref[erred]: print preferred package settings");
18536                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18537                pw.println("    prov[iders]: dump content providers");
18538                pw.println("    p[ackages]: dump installed packages");
18539                pw.println("    s[hared-users]: dump shared user IDs");
18540                pw.println("    m[essages]: print collected runtime messages");
18541                pw.println("    v[erifiers]: print package verifier info");
18542                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18543                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18544                pw.println("    version: print database version info");
18545                pw.println("    write: write current settings now");
18546                pw.println("    installs: details about install sessions");
18547                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18548                pw.println("    dexopt: dump dexopt state");
18549                pw.println("    compiler-stats: dump compiler statistics");
18550                pw.println("    <package.name>: info about given package");
18551                return;
18552            } else if ("--checkin".equals(opt)) {
18553                checkin = true;
18554            } else if ("-f".equals(opt)) {
18555                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18556            } else {
18557                pw.println("Unknown argument: " + opt + "; use -h for help");
18558            }
18559        }
18560
18561        // Is the caller requesting to dump a particular piece of data?
18562        if (opti < args.length) {
18563            String cmd = args[opti];
18564            opti++;
18565            // Is this a package name?
18566            if ("android".equals(cmd) || cmd.contains(".")) {
18567                packageName = cmd;
18568                // When dumping a single package, we always dump all of its
18569                // filter information since the amount of data will be reasonable.
18570                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18571            } else if ("check-permission".equals(cmd)) {
18572                if (opti >= args.length) {
18573                    pw.println("Error: check-permission missing permission argument");
18574                    return;
18575                }
18576                String perm = args[opti];
18577                opti++;
18578                if (opti >= args.length) {
18579                    pw.println("Error: check-permission missing package argument");
18580                    return;
18581                }
18582                String pkg = args[opti];
18583                opti++;
18584                int user = UserHandle.getUserId(Binder.getCallingUid());
18585                if (opti < args.length) {
18586                    try {
18587                        user = Integer.parseInt(args[opti]);
18588                    } catch (NumberFormatException e) {
18589                        pw.println("Error: check-permission user argument is not a number: "
18590                                + args[opti]);
18591                        return;
18592                    }
18593                }
18594                pw.println(checkPermission(perm, pkg, user));
18595                return;
18596            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18597                dumpState.setDump(DumpState.DUMP_LIBS);
18598            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18599                dumpState.setDump(DumpState.DUMP_FEATURES);
18600            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18601                if (opti >= args.length) {
18602                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18603                            | DumpState.DUMP_SERVICE_RESOLVERS
18604                            | DumpState.DUMP_RECEIVER_RESOLVERS
18605                            | DumpState.DUMP_CONTENT_RESOLVERS);
18606                } else {
18607                    while (opti < args.length) {
18608                        String name = args[opti];
18609                        if ("a".equals(name) || "activity".equals(name)) {
18610                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18611                        } else if ("s".equals(name) || "service".equals(name)) {
18612                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18613                        } else if ("r".equals(name) || "receiver".equals(name)) {
18614                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18615                        } else if ("c".equals(name) || "content".equals(name)) {
18616                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18617                        } else {
18618                            pw.println("Error: unknown resolver table type: " + name);
18619                            return;
18620                        }
18621                        opti++;
18622                    }
18623                }
18624            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18625                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18626            } else if ("permission".equals(cmd)) {
18627                if (opti >= args.length) {
18628                    pw.println("Error: permission requires permission name");
18629                    return;
18630                }
18631                permissionNames = new ArraySet<>();
18632                while (opti < args.length) {
18633                    permissionNames.add(args[opti]);
18634                    opti++;
18635                }
18636                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18637                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18638            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18639                dumpState.setDump(DumpState.DUMP_PREFERRED);
18640            } else if ("preferred-xml".equals(cmd)) {
18641                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18642                if (opti < args.length && "--full".equals(args[opti])) {
18643                    fullPreferred = true;
18644                    opti++;
18645                }
18646            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18647                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18648            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18649                dumpState.setDump(DumpState.DUMP_PACKAGES);
18650            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18651                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18652            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18653                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18654            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18655                dumpState.setDump(DumpState.DUMP_MESSAGES);
18656            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18657                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18658            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18659                    || "intent-filter-verifiers".equals(cmd)) {
18660                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18661            } else if ("version".equals(cmd)) {
18662                dumpState.setDump(DumpState.DUMP_VERSION);
18663            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18664                dumpState.setDump(DumpState.DUMP_KEYSETS);
18665            } else if ("installs".equals(cmd)) {
18666                dumpState.setDump(DumpState.DUMP_INSTALLS);
18667            } else if ("frozen".equals(cmd)) {
18668                dumpState.setDump(DumpState.DUMP_FROZEN);
18669            } else if ("dexopt".equals(cmd)) {
18670                dumpState.setDump(DumpState.DUMP_DEXOPT);
18671            } else if ("compiler-stats".equals(cmd)) {
18672                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18673            } else if ("write".equals(cmd)) {
18674                synchronized (mPackages) {
18675                    mSettings.writeLPr();
18676                    pw.println("Settings written.");
18677                    return;
18678                }
18679            }
18680        }
18681
18682        if (checkin) {
18683            pw.println("vers,1");
18684        }
18685
18686        // reader
18687        synchronized (mPackages) {
18688            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18689                if (!checkin) {
18690                    if (dumpState.onTitlePrinted())
18691                        pw.println();
18692                    pw.println("Database versions:");
18693                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18694                }
18695            }
18696
18697            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18698                if (!checkin) {
18699                    if (dumpState.onTitlePrinted())
18700                        pw.println();
18701                    pw.println("Verifiers:");
18702                    pw.print("  Required: ");
18703                    pw.print(mRequiredVerifierPackage);
18704                    pw.print(" (uid=");
18705                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18706                            UserHandle.USER_SYSTEM));
18707                    pw.println(")");
18708                } else if (mRequiredVerifierPackage != null) {
18709                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18710                    pw.print(",");
18711                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18712                            UserHandle.USER_SYSTEM));
18713                }
18714            }
18715
18716            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18717                    packageName == null) {
18718                if (mIntentFilterVerifierComponent != null) {
18719                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18720                    if (!checkin) {
18721                        if (dumpState.onTitlePrinted())
18722                            pw.println();
18723                        pw.println("Intent Filter Verifier:");
18724                        pw.print("  Using: ");
18725                        pw.print(verifierPackageName);
18726                        pw.print(" (uid=");
18727                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18728                                UserHandle.USER_SYSTEM));
18729                        pw.println(")");
18730                    } else if (verifierPackageName != null) {
18731                        pw.print("ifv,"); pw.print(verifierPackageName);
18732                        pw.print(",");
18733                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18734                                UserHandle.USER_SYSTEM));
18735                    }
18736                } else {
18737                    pw.println();
18738                    pw.println("No Intent Filter Verifier available!");
18739                }
18740            }
18741
18742            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18743                boolean printedHeader = false;
18744                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18745                while (it.hasNext()) {
18746                    String name = it.next();
18747                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18748                    if (!checkin) {
18749                        if (!printedHeader) {
18750                            if (dumpState.onTitlePrinted())
18751                                pw.println();
18752                            pw.println("Libraries:");
18753                            printedHeader = true;
18754                        }
18755                        pw.print("  ");
18756                    } else {
18757                        pw.print("lib,");
18758                    }
18759                    pw.print(name);
18760                    if (!checkin) {
18761                        pw.print(" -> ");
18762                    }
18763                    if (ent.path != null) {
18764                        if (!checkin) {
18765                            pw.print("(jar) ");
18766                            pw.print(ent.path);
18767                        } else {
18768                            pw.print(",jar,");
18769                            pw.print(ent.path);
18770                        }
18771                    } else {
18772                        if (!checkin) {
18773                            pw.print("(apk) ");
18774                            pw.print(ent.apk);
18775                        } else {
18776                            pw.print(",apk,");
18777                            pw.print(ent.apk);
18778                        }
18779                    }
18780                    pw.println();
18781                }
18782            }
18783
18784            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18785                if (dumpState.onTitlePrinted())
18786                    pw.println();
18787                if (!checkin) {
18788                    pw.println("Features:");
18789                }
18790
18791                for (FeatureInfo feat : mAvailableFeatures.values()) {
18792                    if (checkin) {
18793                        pw.print("feat,");
18794                        pw.print(feat.name);
18795                        pw.print(",");
18796                        pw.println(feat.version);
18797                    } else {
18798                        pw.print("  ");
18799                        pw.print(feat.name);
18800                        if (feat.version > 0) {
18801                            pw.print(" version=");
18802                            pw.print(feat.version);
18803                        }
18804                        pw.println();
18805                    }
18806                }
18807            }
18808
18809            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18810                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18811                        : "Activity Resolver Table:", "  ", packageName,
18812                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18813                    dumpState.setTitlePrinted(true);
18814                }
18815            }
18816            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18817                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18818                        : "Receiver Resolver Table:", "  ", packageName,
18819                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18820                    dumpState.setTitlePrinted(true);
18821                }
18822            }
18823            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18824                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18825                        : "Service Resolver Table:", "  ", packageName,
18826                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18827                    dumpState.setTitlePrinted(true);
18828                }
18829            }
18830            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18831                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18832                        : "Provider Resolver Table:", "  ", packageName,
18833                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18834                    dumpState.setTitlePrinted(true);
18835                }
18836            }
18837
18838            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18839                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18840                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18841                    int user = mSettings.mPreferredActivities.keyAt(i);
18842                    if (pir.dump(pw,
18843                            dumpState.getTitlePrinted()
18844                                ? "\nPreferred Activities User " + user + ":"
18845                                : "Preferred Activities User " + user + ":", "  ",
18846                            packageName, true, false)) {
18847                        dumpState.setTitlePrinted(true);
18848                    }
18849                }
18850            }
18851
18852            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18853                pw.flush();
18854                FileOutputStream fout = new FileOutputStream(fd);
18855                BufferedOutputStream str = new BufferedOutputStream(fout);
18856                XmlSerializer serializer = new FastXmlSerializer();
18857                try {
18858                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18859                    serializer.startDocument(null, true);
18860                    serializer.setFeature(
18861                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18862                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18863                    serializer.endDocument();
18864                    serializer.flush();
18865                } catch (IllegalArgumentException e) {
18866                    pw.println("Failed writing: " + e);
18867                } catch (IllegalStateException e) {
18868                    pw.println("Failed writing: " + e);
18869                } catch (IOException e) {
18870                    pw.println("Failed writing: " + e);
18871                }
18872            }
18873
18874            if (!checkin
18875                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18876                    && packageName == null) {
18877                pw.println();
18878                int count = mSettings.mPackages.size();
18879                if (count == 0) {
18880                    pw.println("No applications!");
18881                    pw.println();
18882                } else {
18883                    final String prefix = "  ";
18884                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18885                    if (allPackageSettings.size() == 0) {
18886                        pw.println("No domain preferred apps!");
18887                        pw.println();
18888                    } else {
18889                        pw.println("App verification status:");
18890                        pw.println();
18891                        count = 0;
18892                        for (PackageSetting ps : allPackageSettings) {
18893                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18894                            if (ivi == null || ivi.getPackageName() == null) continue;
18895                            pw.println(prefix + "Package: " + ivi.getPackageName());
18896                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18897                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18898                            pw.println();
18899                            count++;
18900                        }
18901                        if (count == 0) {
18902                            pw.println(prefix + "No app verification established.");
18903                            pw.println();
18904                        }
18905                        for (int userId : sUserManager.getUserIds()) {
18906                            pw.println("App linkages for user " + userId + ":");
18907                            pw.println();
18908                            count = 0;
18909                            for (PackageSetting ps : allPackageSettings) {
18910                                final long status = ps.getDomainVerificationStatusForUser(userId);
18911                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18912                                    continue;
18913                                }
18914                                pw.println(prefix + "Package: " + ps.name);
18915                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18916                                String statusStr = IntentFilterVerificationInfo.
18917                                        getStatusStringFromValue(status);
18918                                pw.println(prefix + "Status:  " + statusStr);
18919                                pw.println();
18920                                count++;
18921                            }
18922                            if (count == 0) {
18923                                pw.println(prefix + "No configured app linkages.");
18924                                pw.println();
18925                            }
18926                        }
18927                    }
18928                }
18929            }
18930
18931            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18932                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18933                if (packageName == null && permissionNames == null) {
18934                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18935                        if (iperm == 0) {
18936                            if (dumpState.onTitlePrinted())
18937                                pw.println();
18938                            pw.println("AppOp Permissions:");
18939                        }
18940                        pw.print("  AppOp Permission ");
18941                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18942                        pw.println(":");
18943                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18944                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18945                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18946                        }
18947                    }
18948                }
18949            }
18950
18951            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18952                boolean printedSomething = false;
18953                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18954                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18955                        continue;
18956                    }
18957                    if (!printedSomething) {
18958                        if (dumpState.onTitlePrinted())
18959                            pw.println();
18960                        pw.println("Registered ContentProviders:");
18961                        printedSomething = true;
18962                    }
18963                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18964                    pw.print("    "); pw.println(p.toString());
18965                }
18966                printedSomething = false;
18967                for (Map.Entry<String, PackageParser.Provider> entry :
18968                        mProvidersByAuthority.entrySet()) {
18969                    PackageParser.Provider p = entry.getValue();
18970                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18971                        continue;
18972                    }
18973                    if (!printedSomething) {
18974                        if (dumpState.onTitlePrinted())
18975                            pw.println();
18976                        pw.println("ContentProvider Authorities:");
18977                        printedSomething = true;
18978                    }
18979                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18980                    pw.print("    "); pw.println(p.toString());
18981                    if (p.info != null && p.info.applicationInfo != null) {
18982                        final String appInfo = p.info.applicationInfo.toString();
18983                        pw.print("      applicationInfo="); pw.println(appInfo);
18984                    }
18985                }
18986            }
18987
18988            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18989                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18990            }
18991
18992            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18993                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18994            }
18995
18996            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18997                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18998            }
18999
19000            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19001                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19002            }
19003
19004            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19005                // XXX should handle packageName != null by dumping only install data that
19006                // the given package is involved with.
19007                if (dumpState.onTitlePrinted()) pw.println();
19008                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19009            }
19010
19011            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19012                // XXX should handle packageName != null by dumping only install data that
19013                // the given package is involved with.
19014                if (dumpState.onTitlePrinted()) pw.println();
19015
19016                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19017                ipw.println();
19018                ipw.println("Frozen packages:");
19019                ipw.increaseIndent();
19020                if (mFrozenPackages.size() == 0) {
19021                    ipw.println("(none)");
19022                } else {
19023                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19024                        ipw.println(mFrozenPackages.valueAt(i));
19025                    }
19026                }
19027                ipw.decreaseIndent();
19028            }
19029
19030            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19031                if (dumpState.onTitlePrinted()) pw.println();
19032                dumpDexoptStateLPr(pw, packageName);
19033            }
19034
19035            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19036                if (dumpState.onTitlePrinted()) pw.println();
19037                dumpCompilerStatsLPr(pw, packageName);
19038            }
19039
19040            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19041                if (dumpState.onTitlePrinted()) pw.println();
19042                mSettings.dumpReadMessagesLPr(pw, dumpState);
19043
19044                pw.println();
19045                pw.println("Package warning messages:");
19046                BufferedReader in = null;
19047                String line = null;
19048                try {
19049                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19050                    while ((line = in.readLine()) != null) {
19051                        if (line.contains("ignored: updated version")) continue;
19052                        pw.println(line);
19053                    }
19054                } catch (IOException ignored) {
19055                } finally {
19056                    IoUtils.closeQuietly(in);
19057                }
19058            }
19059
19060            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19061                BufferedReader in = null;
19062                String line = null;
19063                try {
19064                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19065                    while ((line = in.readLine()) != null) {
19066                        if (line.contains("ignored: updated version")) continue;
19067                        pw.print("msg,");
19068                        pw.println(line);
19069                    }
19070                } catch (IOException ignored) {
19071                } finally {
19072                    IoUtils.closeQuietly(in);
19073                }
19074            }
19075        }
19076    }
19077
19078    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19079        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19080        ipw.println();
19081        ipw.println("Dexopt state:");
19082        ipw.increaseIndent();
19083        Collection<PackageParser.Package> packages = null;
19084        if (packageName != null) {
19085            PackageParser.Package targetPackage = mPackages.get(packageName);
19086            if (targetPackage != null) {
19087                packages = Collections.singletonList(targetPackage);
19088            } else {
19089                ipw.println("Unable to find package: " + packageName);
19090                return;
19091            }
19092        } else {
19093            packages = mPackages.values();
19094        }
19095
19096        for (PackageParser.Package pkg : packages) {
19097            ipw.println("[" + pkg.packageName + "]");
19098            ipw.increaseIndent();
19099            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19100            ipw.decreaseIndent();
19101        }
19102    }
19103
19104    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19105        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19106        ipw.println();
19107        ipw.println("Compiler stats:");
19108        ipw.increaseIndent();
19109        Collection<PackageParser.Package> packages = null;
19110        if (packageName != null) {
19111            PackageParser.Package targetPackage = mPackages.get(packageName);
19112            if (targetPackage != null) {
19113                packages = Collections.singletonList(targetPackage);
19114            } else {
19115                ipw.println("Unable to find package: " + packageName);
19116                return;
19117            }
19118        } else {
19119            packages = mPackages.values();
19120        }
19121
19122        for (PackageParser.Package pkg : packages) {
19123            ipw.println("[" + pkg.packageName + "]");
19124            ipw.increaseIndent();
19125
19126            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19127            if (stats == null) {
19128                ipw.println("(No recorded stats)");
19129            } else {
19130                stats.dump(ipw);
19131            }
19132            ipw.decreaseIndent();
19133        }
19134    }
19135
19136    private String dumpDomainString(String packageName) {
19137        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19138                .getList();
19139        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19140
19141        ArraySet<String> result = new ArraySet<>();
19142        if (iviList.size() > 0) {
19143            for (IntentFilterVerificationInfo ivi : iviList) {
19144                for (String host : ivi.getDomains()) {
19145                    result.add(host);
19146                }
19147            }
19148        }
19149        if (filters != null && filters.size() > 0) {
19150            for (IntentFilter filter : filters) {
19151                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19152                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19153                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19154                    result.addAll(filter.getHostsList());
19155                }
19156            }
19157        }
19158
19159        StringBuilder sb = new StringBuilder(result.size() * 16);
19160        for (String domain : result) {
19161            if (sb.length() > 0) sb.append(" ");
19162            sb.append(domain);
19163        }
19164        return sb.toString();
19165    }
19166
19167    // ------- apps on sdcard specific code -------
19168    static final boolean DEBUG_SD_INSTALL = false;
19169
19170    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19171
19172    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19173
19174    private boolean mMediaMounted = false;
19175
19176    static String getEncryptKey() {
19177        try {
19178            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19179                    SD_ENCRYPTION_KEYSTORE_NAME);
19180            if (sdEncKey == null) {
19181                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19182                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19183                if (sdEncKey == null) {
19184                    Slog.e(TAG, "Failed to create encryption keys");
19185                    return null;
19186                }
19187            }
19188            return sdEncKey;
19189        } catch (NoSuchAlgorithmException nsae) {
19190            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19191            return null;
19192        } catch (IOException ioe) {
19193            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19194            return null;
19195        }
19196    }
19197
19198    /*
19199     * Update media status on PackageManager.
19200     */
19201    @Override
19202    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19203        int callingUid = Binder.getCallingUid();
19204        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19205            throw new SecurityException("Media status can only be updated by the system");
19206        }
19207        // reader; this apparently protects mMediaMounted, but should probably
19208        // be a different lock in that case.
19209        synchronized (mPackages) {
19210            Log.i(TAG, "Updating external media status from "
19211                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19212                    + (mediaStatus ? "mounted" : "unmounted"));
19213            if (DEBUG_SD_INSTALL)
19214                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19215                        + ", mMediaMounted=" + mMediaMounted);
19216            if (mediaStatus == mMediaMounted) {
19217                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19218                        : 0, -1);
19219                mHandler.sendMessage(msg);
19220                return;
19221            }
19222            mMediaMounted = mediaStatus;
19223        }
19224        // Queue up an async operation since the package installation may take a
19225        // little while.
19226        mHandler.post(new Runnable() {
19227            public void run() {
19228                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19229            }
19230        });
19231    }
19232
19233    /**
19234     * Called by MountService when the initial ASECs to scan are available.
19235     * Should block until all the ASEC containers are finished being scanned.
19236     */
19237    public void scanAvailableAsecs() {
19238        updateExternalMediaStatusInner(true, false, false);
19239    }
19240
19241    /*
19242     * Collect information of applications on external media, map them against
19243     * existing containers and update information based on current mount status.
19244     * Please note that we always have to report status if reportStatus has been
19245     * set to true especially when unloading packages.
19246     */
19247    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19248            boolean externalStorage) {
19249        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19250        int[] uidArr = EmptyArray.INT;
19251
19252        final String[] list = PackageHelper.getSecureContainerList();
19253        if (ArrayUtils.isEmpty(list)) {
19254            Log.i(TAG, "No secure containers found");
19255        } else {
19256            // Process list of secure containers and categorize them
19257            // as active or stale based on their package internal state.
19258
19259            // reader
19260            synchronized (mPackages) {
19261                for (String cid : list) {
19262                    // Leave stages untouched for now; installer service owns them
19263                    if (PackageInstallerService.isStageName(cid)) continue;
19264
19265                    if (DEBUG_SD_INSTALL)
19266                        Log.i(TAG, "Processing container " + cid);
19267                    String pkgName = getAsecPackageName(cid);
19268                    if (pkgName == null) {
19269                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19270                        continue;
19271                    }
19272                    if (DEBUG_SD_INSTALL)
19273                        Log.i(TAG, "Looking for pkg : " + pkgName);
19274
19275                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19276                    if (ps == null) {
19277                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19278                        continue;
19279                    }
19280
19281                    /*
19282                     * Skip packages that are not external if we're unmounting
19283                     * external storage.
19284                     */
19285                    if (externalStorage && !isMounted && !isExternal(ps)) {
19286                        continue;
19287                    }
19288
19289                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19290                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19291                    // The package status is changed only if the code path
19292                    // matches between settings and the container id.
19293                    if (ps.codePathString != null
19294                            && ps.codePathString.startsWith(args.getCodePath())) {
19295                        if (DEBUG_SD_INSTALL) {
19296                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19297                                    + " at code path: " + ps.codePathString);
19298                        }
19299
19300                        // We do have a valid package installed on sdcard
19301                        processCids.put(args, ps.codePathString);
19302                        final int uid = ps.appId;
19303                        if (uid != -1) {
19304                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19305                        }
19306                    } else {
19307                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19308                                + ps.codePathString);
19309                    }
19310                }
19311            }
19312
19313            Arrays.sort(uidArr);
19314        }
19315
19316        // Process packages with valid entries.
19317        if (isMounted) {
19318            if (DEBUG_SD_INSTALL)
19319                Log.i(TAG, "Loading packages");
19320            loadMediaPackages(processCids, uidArr, externalStorage);
19321            startCleaningPackages();
19322            mInstallerService.onSecureContainersAvailable();
19323        } else {
19324            if (DEBUG_SD_INSTALL)
19325                Log.i(TAG, "Unloading packages");
19326            unloadMediaPackages(processCids, uidArr, reportStatus);
19327        }
19328    }
19329
19330    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19331            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19332        final int size = infos.size();
19333        final String[] packageNames = new String[size];
19334        final int[] packageUids = new int[size];
19335        for (int i = 0; i < size; i++) {
19336            final ApplicationInfo info = infos.get(i);
19337            packageNames[i] = info.packageName;
19338            packageUids[i] = info.uid;
19339        }
19340        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19341                finishedReceiver);
19342    }
19343
19344    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19345            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19346        sendResourcesChangedBroadcast(mediaStatus, replacing,
19347                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19348    }
19349
19350    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19351            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19352        int size = pkgList.length;
19353        if (size > 0) {
19354            // Send broadcasts here
19355            Bundle extras = new Bundle();
19356            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19357            if (uidArr != null) {
19358                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19359            }
19360            if (replacing) {
19361                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19362            }
19363            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19364                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19365            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19366        }
19367    }
19368
19369   /*
19370     * Look at potentially valid container ids from processCids If package
19371     * information doesn't match the one on record or package scanning fails,
19372     * the cid is added to list of removeCids. We currently don't delete stale
19373     * containers.
19374     */
19375    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19376            boolean externalStorage) {
19377        ArrayList<String> pkgList = new ArrayList<String>();
19378        Set<AsecInstallArgs> keys = processCids.keySet();
19379
19380        for (AsecInstallArgs args : keys) {
19381            String codePath = processCids.get(args);
19382            if (DEBUG_SD_INSTALL)
19383                Log.i(TAG, "Loading container : " + args.cid);
19384            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19385            try {
19386                // Make sure there are no container errors first.
19387                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19388                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19389                            + " when installing from sdcard");
19390                    continue;
19391                }
19392                // Check code path here.
19393                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19394                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19395                            + " does not match one in settings " + codePath);
19396                    continue;
19397                }
19398                // Parse package
19399                int parseFlags = mDefParseFlags;
19400                if (args.isExternalAsec()) {
19401                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19402                }
19403                if (args.isFwdLocked()) {
19404                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19405                }
19406
19407                synchronized (mInstallLock) {
19408                    PackageParser.Package pkg = null;
19409                    try {
19410                        // Sadly we don't know the package name yet to freeze it
19411                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19412                                SCAN_IGNORE_FROZEN, 0, null);
19413                    } catch (PackageManagerException e) {
19414                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19415                    }
19416                    // Scan the package
19417                    if (pkg != null) {
19418                        /*
19419                         * TODO why is the lock being held? doPostInstall is
19420                         * called in other places without the lock. This needs
19421                         * to be straightened out.
19422                         */
19423                        // writer
19424                        synchronized (mPackages) {
19425                            retCode = PackageManager.INSTALL_SUCCEEDED;
19426                            pkgList.add(pkg.packageName);
19427                            // Post process args
19428                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19429                                    pkg.applicationInfo.uid);
19430                        }
19431                    } else {
19432                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19433                    }
19434                }
19435
19436            } finally {
19437                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19438                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19439                }
19440            }
19441        }
19442        // writer
19443        synchronized (mPackages) {
19444            // If the platform SDK has changed since the last time we booted,
19445            // we need to re-grant app permission to catch any new ones that
19446            // appear. This is really a hack, and means that apps can in some
19447            // cases get permissions that the user didn't initially explicitly
19448            // allow... it would be nice to have some better way to handle
19449            // this situation.
19450            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19451                    : mSettings.getInternalVersion();
19452            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19453                    : StorageManager.UUID_PRIVATE_INTERNAL;
19454
19455            int updateFlags = UPDATE_PERMISSIONS_ALL;
19456            if (ver.sdkVersion != mSdkVersion) {
19457                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19458                        + mSdkVersion + "; regranting permissions for external");
19459                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19460            }
19461            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19462
19463            // Yay, everything is now upgraded
19464            ver.forceCurrent();
19465
19466            // can downgrade to reader
19467            // Persist settings
19468            mSettings.writeLPr();
19469        }
19470        // Send a broadcast to let everyone know we are done processing
19471        if (pkgList.size() > 0) {
19472            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19473        }
19474    }
19475
19476   /*
19477     * Utility method to unload a list of specified containers
19478     */
19479    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19480        // Just unmount all valid containers.
19481        for (AsecInstallArgs arg : cidArgs) {
19482            synchronized (mInstallLock) {
19483                arg.doPostDeleteLI(false);
19484           }
19485       }
19486   }
19487
19488    /*
19489     * Unload packages mounted on external media. This involves deleting package
19490     * data from internal structures, sending broadcasts about disabled packages,
19491     * gc'ing to free up references, unmounting all secure containers
19492     * corresponding to packages on external media, and posting a
19493     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19494     * that we always have to post this message if status has been requested no
19495     * matter what.
19496     */
19497    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19498            final boolean reportStatus) {
19499        if (DEBUG_SD_INSTALL)
19500            Log.i(TAG, "unloading media packages");
19501        ArrayList<String> pkgList = new ArrayList<String>();
19502        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19503        final Set<AsecInstallArgs> keys = processCids.keySet();
19504        for (AsecInstallArgs args : keys) {
19505            String pkgName = args.getPackageName();
19506            if (DEBUG_SD_INSTALL)
19507                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19508            // Delete package internally
19509            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19510            synchronized (mInstallLock) {
19511                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19512                final boolean res;
19513                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19514                        "unloadMediaPackages")) {
19515                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19516                            null);
19517                }
19518                if (res) {
19519                    pkgList.add(pkgName);
19520                } else {
19521                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19522                    failedList.add(args);
19523                }
19524            }
19525        }
19526
19527        // reader
19528        synchronized (mPackages) {
19529            // We didn't update the settings after removing each package;
19530            // write them now for all packages.
19531            mSettings.writeLPr();
19532        }
19533
19534        // We have to absolutely send UPDATED_MEDIA_STATUS only
19535        // after confirming that all the receivers processed the ordered
19536        // broadcast when packages get disabled, force a gc to clean things up.
19537        // and unload all the containers.
19538        if (pkgList.size() > 0) {
19539            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19540                    new IIntentReceiver.Stub() {
19541                public void performReceive(Intent intent, int resultCode, String data,
19542                        Bundle extras, boolean ordered, boolean sticky,
19543                        int sendingUser) throws RemoteException {
19544                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19545                            reportStatus ? 1 : 0, 1, keys);
19546                    mHandler.sendMessage(msg);
19547                }
19548            });
19549        } else {
19550            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19551                    keys);
19552            mHandler.sendMessage(msg);
19553        }
19554    }
19555
19556    private void loadPrivatePackages(final VolumeInfo vol) {
19557        mHandler.post(new Runnable() {
19558            @Override
19559            public void run() {
19560                loadPrivatePackagesInner(vol);
19561            }
19562        });
19563    }
19564
19565    private void loadPrivatePackagesInner(VolumeInfo vol) {
19566        final String volumeUuid = vol.fsUuid;
19567        if (TextUtils.isEmpty(volumeUuid)) {
19568            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19569            return;
19570        }
19571
19572        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19573        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19574        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19575
19576        final VersionInfo ver;
19577        final List<PackageSetting> packages;
19578        synchronized (mPackages) {
19579            ver = mSettings.findOrCreateVersion(volumeUuid);
19580            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19581        }
19582
19583        for (PackageSetting ps : packages) {
19584            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19585            synchronized (mInstallLock) {
19586                final PackageParser.Package pkg;
19587                try {
19588                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19589                    loaded.add(pkg.applicationInfo);
19590
19591                } catch (PackageManagerException e) {
19592                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19593                }
19594
19595                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19596                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19597                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19598                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19599                }
19600            }
19601        }
19602
19603        // Reconcile app data for all started/unlocked users
19604        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19605        final UserManager um = mContext.getSystemService(UserManager.class);
19606        UserManagerInternal umInternal = getUserManagerInternal();
19607        for (UserInfo user : um.getUsers()) {
19608            final int flags;
19609            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19610                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19611            } else if (umInternal.isUserRunning(user.id)) {
19612                flags = StorageManager.FLAG_STORAGE_DE;
19613            } else {
19614                continue;
19615            }
19616
19617            try {
19618                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19619                synchronized (mInstallLock) {
19620                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19621                }
19622            } catch (IllegalStateException e) {
19623                // Device was probably ejected, and we'll process that event momentarily
19624                Slog.w(TAG, "Failed to prepare storage: " + e);
19625            }
19626        }
19627
19628        synchronized (mPackages) {
19629            int updateFlags = UPDATE_PERMISSIONS_ALL;
19630            if (ver.sdkVersion != mSdkVersion) {
19631                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19632                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19633                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19634            }
19635            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19636
19637            // Yay, everything is now upgraded
19638            ver.forceCurrent();
19639
19640            mSettings.writeLPr();
19641        }
19642
19643        for (PackageFreezer freezer : freezers) {
19644            freezer.close();
19645        }
19646
19647        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19648        sendResourcesChangedBroadcast(true, false, loaded, null);
19649    }
19650
19651    private void unloadPrivatePackages(final VolumeInfo vol) {
19652        mHandler.post(new Runnable() {
19653            @Override
19654            public void run() {
19655                unloadPrivatePackagesInner(vol);
19656            }
19657        });
19658    }
19659
19660    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19661        final String volumeUuid = vol.fsUuid;
19662        if (TextUtils.isEmpty(volumeUuid)) {
19663            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19664            return;
19665        }
19666
19667        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19668        synchronized (mInstallLock) {
19669        synchronized (mPackages) {
19670            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19671            for (PackageSetting ps : packages) {
19672                if (ps.pkg == null) continue;
19673
19674                final ApplicationInfo info = ps.pkg.applicationInfo;
19675                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19676                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19677
19678                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19679                        "unloadPrivatePackagesInner")) {
19680                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19681                            false, null)) {
19682                        unloaded.add(info);
19683                    } else {
19684                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19685                    }
19686                }
19687
19688                // Try very hard to release any references to this package
19689                // so we don't risk the system server being killed due to
19690                // open FDs
19691                AttributeCache.instance().removePackage(ps.name);
19692            }
19693
19694            mSettings.writeLPr();
19695        }
19696        }
19697
19698        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19699        sendResourcesChangedBroadcast(false, false, unloaded, null);
19700
19701        // Try very hard to release any references to this path so we don't risk
19702        // the system server being killed due to open FDs
19703        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19704
19705        for (int i = 0; i < 3; i++) {
19706            System.gc();
19707            System.runFinalization();
19708        }
19709    }
19710
19711    /**
19712     * Prepare storage areas for given user on all mounted devices.
19713     */
19714    void prepareUserData(int userId, int userSerial, int flags) {
19715        synchronized (mInstallLock) {
19716            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19717            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19718                final String volumeUuid = vol.getFsUuid();
19719                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19720            }
19721        }
19722    }
19723
19724    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19725            boolean allowRecover) {
19726        // Prepare storage and verify that serial numbers are consistent; if
19727        // there's a mismatch we need to destroy to avoid leaking data
19728        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19729        try {
19730            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19731
19732            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19733                UserManagerService.enforceSerialNumber(
19734                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19735                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19736                    UserManagerService.enforceSerialNumber(
19737                            Environment.getDataSystemDeDirectory(userId), userSerial);
19738                }
19739            }
19740            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19741                UserManagerService.enforceSerialNumber(
19742                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19743                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19744                    UserManagerService.enforceSerialNumber(
19745                            Environment.getDataSystemCeDirectory(userId), userSerial);
19746                }
19747            }
19748
19749            synchronized (mInstallLock) {
19750                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19751            }
19752        } catch (Exception e) {
19753            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19754                    + " because we failed to prepare: " + e);
19755            destroyUserDataLI(volumeUuid, userId,
19756                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19757
19758            if (allowRecover) {
19759                // Try one last time; if we fail again we're really in trouble
19760                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19761            }
19762        }
19763    }
19764
19765    /**
19766     * Destroy storage areas for given user on all mounted devices.
19767     */
19768    void destroyUserData(int userId, int flags) {
19769        synchronized (mInstallLock) {
19770            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19771            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19772                final String volumeUuid = vol.getFsUuid();
19773                destroyUserDataLI(volumeUuid, userId, flags);
19774            }
19775        }
19776    }
19777
19778    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19779        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19780        try {
19781            // Clean up app data, profile data, and media data
19782            mInstaller.destroyUserData(volumeUuid, userId, flags);
19783
19784            // Clean up system data
19785            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19786                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19787                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19788                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19789                }
19790                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19791                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19792                }
19793            }
19794
19795            // Data with special labels is now gone, so finish the job
19796            storage.destroyUserStorage(volumeUuid, userId, flags);
19797
19798        } catch (Exception e) {
19799            logCriticalInfo(Log.WARN,
19800                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19801        }
19802    }
19803
19804    /**
19805     * Examine all users present on given mounted volume, and destroy data
19806     * belonging to users that are no longer valid, or whose user ID has been
19807     * recycled.
19808     */
19809    private void reconcileUsers(String volumeUuid) {
19810        final List<File> files = new ArrayList<>();
19811        Collections.addAll(files, FileUtils
19812                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19813        Collections.addAll(files, FileUtils
19814                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19815        Collections.addAll(files, FileUtils
19816                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19817        Collections.addAll(files, FileUtils
19818                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19819        for (File file : files) {
19820            if (!file.isDirectory()) continue;
19821
19822            final int userId;
19823            final UserInfo info;
19824            try {
19825                userId = Integer.parseInt(file.getName());
19826                info = sUserManager.getUserInfo(userId);
19827            } catch (NumberFormatException e) {
19828                Slog.w(TAG, "Invalid user directory " + file);
19829                continue;
19830            }
19831
19832            boolean destroyUser = false;
19833            if (info == null) {
19834                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19835                        + " because no matching user was found");
19836                destroyUser = true;
19837            } else if (!mOnlyCore) {
19838                try {
19839                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19840                } catch (IOException e) {
19841                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19842                            + " because we failed to enforce serial number: " + e);
19843                    destroyUser = true;
19844                }
19845            }
19846
19847            if (destroyUser) {
19848                synchronized (mInstallLock) {
19849                    destroyUserDataLI(volumeUuid, userId,
19850                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19851                }
19852            }
19853        }
19854    }
19855
19856    private void assertPackageKnown(String volumeUuid, String packageName)
19857            throws PackageManagerException {
19858        synchronized (mPackages) {
19859            final PackageSetting ps = mSettings.mPackages.get(packageName);
19860            if (ps == null) {
19861                throw new PackageManagerException("Package " + packageName + " is unknown");
19862            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19863                throw new PackageManagerException(
19864                        "Package " + packageName + " found on unknown volume " + volumeUuid
19865                                + "; expected volume " + ps.volumeUuid);
19866            }
19867        }
19868    }
19869
19870    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19871            throws PackageManagerException {
19872        synchronized (mPackages) {
19873            final PackageSetting ps = mSettings.mPackages.get(packageName);
19874            if (ps == null) {
19875                throw new PackageManagerException("Package " + packageName + " is unknown");
19876            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19877                throw new PackageManagerException(
19878                        "Package " + packageName + " found on unknown volume " + volumeUuid
19879                                + "; expected volume " + ps.volumeUuid);
19880            } else if (!ps.getInstalled(userId)) {
19881                throw new PackageManagerException(
19882                        "Package " + packageName + " not installed for user " + userId);
19883            }
19884        }
19885    }
19886
19887    /**
19888     * Examine all apps present on given mounted volume, and destroy apps that
19889     * aren't expected, either due to uninstallation or reinstallation on
19890     * another volume.
19891     */
19892    private void reconcileApps(String volumeUuid) {
19893        final File[] files = FileUtils
19894                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19895        for (File file : files) {
19896            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19897                    && !PackageInstallerService.isStageName(file.getName());
19898            if (!isPackage) {
19899                // Ignore entries which are not packages
19900                continue;
19901            }
19902
19903            try {
19904                final PackageLite pkg = PackageParser.parsePackageLite(file,
19905                        PackageParser.PARSE_MUST_BE_APK);
19906                assertPackageKnown(volumeUuid, pkg.packageName);
19907
19908            } catch (PackageParserException | PackageManagerException e) {
19909                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19910                synchronized (mInstallLock) {
19911                    removeCodePathLI(file);
19912                }
19913            }
19914        }
19915    }
19916
19917    /**
19918     * Reconcile all app data for the given user.
19919     * <p>
19920     * Verifies that directories exist and that ownership and labeling is
19921     * correct for all installed apps on all mounted volumes.
19922     */
19923    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19924        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19925        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19926            final String volumeUuid = vol.getFsUuid();
19927            synchronized (mInstallLock) {
19928                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19929            }
19930        }
19931    }
19932
19933    /**
19934     * Reconcile all app data on given mounted volume.
19935     * <p>
19936     * Destroys app data that isn't expected, either due to uninstallation or
19937     * reinstallation on another volume.
19938     * <p>
19939     * Verifies that directories exist and that ownership and labeling is
19940     * correct for all installed apps.
19941     */
19942    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19943            boolean migrateAppData) {
19944        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19945                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19946
19947        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19948        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19949
19950        // First look for stale data that doesn't belong, and check if things
19951        // have changed since we did our last restorecon
19952        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19953            if (StorageManager.isFileEncryptedNativeOrEmulated()
19954                    && !StorageManager.isUserKeyUnlocked(userId)) {
19955                throw new RuntimeException(
19956                        "Yikes, someone asked us to reconcile CE storage while " + userId
19957                                + " was still locked; this would have caused massive data loss!");
19958            }
19959
19960            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19961            for (File file : files) {
19962                final String packageName = file.getName();
19963                try {
19964                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19965                } catch (PackageManagerException e) {
19966                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19967                    try {
19968                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19969                                StorageManager.FLAG_STORAGE_CE, 0);
19970                    } catch (InstallerException e2) {
19971                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19972                    }
19973                }
19974            }
19975        }
19976        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19977            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19978            for (File file : files) {
19979                final String packageName = file.getName();
19980                try {
19981                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19982                } catch (PackageManagerException e) {
19983                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19984                    try {
19985                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19986                                StorageManager.FLAG_STORAGE_DE, 0);
19987                    } catch (InstallerException e2) {
19988                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19989                    }
19990                }
19991            }
19992        }
19993
19994        // Ensure that data directories are ready to roll for all packages
19995        // installed for this volume and user
19996        final List<PackageSetting> packages;
19997        synchronized (mPackages) {
19998            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19999        }
20000        int preparedCount = 0;
20001        for (PackageSetting ps : packages) {
20002            final String packageName = ps.name;
20003            if (ps.pkg == null) {
20004                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20005                // TODO: might be due to legacy ASEC apps; we should circle back
20006                // and reconcile again once they're scanned
20007                continue;
20008            }
20009
20010            if (ps.getInstalled(userId)) {
20011                prepareAppDataLIF(ps.pkg, userId, flags);
20012
20013                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20014                    // We may have just shuffled around app data directories, so
20015                    // prepare them one more time
20016                    prepareAppDataLIF(ps.pkg, userId, flags);
20017                }
20018
20019                preparedCount++;
20020            }
20021        }
20022
20023        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20024    }
20025
20026    /**
20027     * Prepare app data for the given app just after it was installed or
20028     * upgraded. This method carefully only touches users that it's installed
20029     * for, and it forces a restorecon to handle any seinfo changes.
20030     * <p>
20031     * Verifies that directories exist and that ownership and labeling is
20032     * correct for all installed apps. If there is an ownership mismatch, it
20033     * will try recovering system apps by wiping data; third-party app data is
20034     * left intact.
20035     * <p>
20036     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20037     */
20038    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20039        final PackageSetting ps;
20040        synchronized (mPackages) {
20041            ps = mSettings.mPackages.get(pkg.packageName);
20042            mSettings.writeKernelMappingLPr(ps);
20043        }
20044
20045        final UserManager um = mContext.getSystemService(UserManager.class);
20046        UserManagerInternal umInternal = getUserManagerInternal();
20047        for (UserInfo user : um.getUsers()) {
20048            final int flags;
20049            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20050                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20051            } else if (umInternal.isUserRunning(user.id)) {
20052                flags = StorageManager.FLAG_STORAGE_DE;
20053            } else {
20054                continue;
20055            }
20056
20057            if (ps.getInstalled(user.id)) {
20058                // TODO: when user data is locked, mark that we're still dirty
20059                prepareAppDataLIF(pkg, user.id, flags);
20060            }
20061        }
20062    }
20063
20064    /**
20065     * Prepare app data for the given app.
20066     * <p>
20067     * Verifies that directories exist and that ownership and labeling is
20068     * correct for all installed apps. If there is an ownership mismatch, this
20069     * will try recovering system apps by wiping data; third-party app data is
20070     * left intact.
20071     */
20072    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20073        if (pkg == null) {
20074            Slog.wtf(TAG, "Package was null!", new Throwable());
20075            return;
20076        }
20077        prepareAppDataLeafLIF(pkg, userId, flags);
20078        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20079        for (int i = 0; i < childCount; i++) {
20080            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20081        }
20082    }
20083
20084    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20085        if (DEBUG_APP_DATA) {
20086            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20087                    + Integer.toHexString(flags));
20088        }
20089
20090        final String volumeUuid = pkg.volumeUuid;
20091        final String packageName = pkg.packageName;
20092        final ApplicationInfo app = pkg.applicationInfo;
20093        final int appId = UserHandle.getAppId(app.uid);
20094
20095        Preconditions.checkNotNull(app.seinfo);
20096
20097        try {
20098            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20099                    appId, app.seinfo, app.targetSdkVersion);
20100        } catch (InstallerException e) {
20101            if (app.isSystemApp()) {
20102                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20103                        + ", but trying to recover: " + e);
20104                destroyAppDataLeafLIF(pkg, userId, flags);
20105                try {
20106                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20107                            appId, app.seinfo, app.targetSdkVersion);
20108                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20109                } catch (InstallerException e2) {
20110                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20111                }
20112            } else {
20113                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20114            }
20115        }
20116
20117        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20118            try {
20119                // CE storage is unlocked right now, so read out the inode and
20120                // remember for use later when it's locked
20121                // TODO: mark this structure as dirty so we persist it!
20122                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20123                        StorageManager.FLAG_STORAGE_CE);
20124                synchronized (mPackages) {
20125                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20126                    if (ps != null) {
20127                        ps.setCeDataInode(ceDataInode, userId);
20128                    }
20129                }
20130            } catch (InstallerException e) {
20131                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20132            }
20133        }
20134
20135        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20136    }
20137
20138    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20139        if (pkg == null) {
20140            Slog.wtf(TAG, "Package was null!", new Throwable());
20141            return;
20142        }
20143        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20144        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20145        for (int i = 0; i < childCount; i++) {
20146            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20147        }
20148    }
20149
20150    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20151        final String volumeUuid = pkg.volumeUuid;
20152        final String packageName = pkg.packageName;
20153        final ApplicationInfo app = pkg.applicationInfo;
20154
20155        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20156            // Create a native library symlink only if we have native libraries
20157            // and if the native libraries are 32 bit libraries. We do not provide
20158            // this symlink for 64 bit libraries.
20159            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20160                final String nativeLibPath = app.nativeLibraryDir;
20161                try {
20162                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20163                            nativeLibPath, userId);
20164                } catch (InstallerException e) {
20165                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20166                }
20167            }
20168        }
20169    }
20170
20171    /**
20172     * For system apps on non-FBE devices, this method migrates any existing
20173     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20174     * requested by the app.
20175     */
20176    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20177        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20178                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20179            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20180                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20181            try {
20182                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20183                        storageTarget);
20184            } catch (InstallerException e) {
20185                logCriticalInfo(Log.WARN,
20186                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20187            }
20188            return true;
20189        } else {
20190            return false;
20191        }
20192    }
20193
20194    public PackageFreezer freezePackage(String packageName, String killReason) {
20195        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20196    }
20197
20198    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20199        return new PackageFreezer(packageName, userId, killReason);
20200    }
20201
20202    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20203            String killReason) {
20204        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20205    }
20206
20207    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20208            String killReason) {
20209        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20210            return new PackageFreezer();
20211        } else {
20212            return freezePackage(packageName, userId, killReason);
20213        }
20214    }
20215
20216    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20217            String killReason) {
20218        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20219    }
20220
20221    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20222            String killReason) {
20223        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20224            return new PackageFreezer();
20225        } else {
20226            return freezePackage(packageName, userId, killReason);
20227        }
20228    }
20229
20230    /**
20231     * Class that freezes and kills the given package upon creation, and
20232     * unfreezes it upon closing. This is typically used when doing surgery on
20233     * app code/data to prevent the app from running while you're working.
20234     */
20235    private class PackageFreezer implements AutoCloseable {
20236        private final String mPackageName;
20237        private final PackageFreezer[] mChildren;
20238
20239        private final boolean mWeFroze;
20240
20241        private final AtomicBoolean mClosed = new AtomicBoolean();
20242        private final CloseGuard mCloseGuard = CloseGuard.get();
20243
20244        /**
20245         * Create and return a stub freezer that doesn't actually do anything,
20246         * typically used when someone requested
20247         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20248         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20249         */
20250        public PackageFreezer() {
20251            mPackageName = null;
20252            mChildren = null;
20253            mWeFroze = false;
20254            mCloseGuard.open("close");
20255        }
20256
20257        public PackageFreezer(String packageName, int userId, String killReason) {
20258            synchronized (mPackages) {
20259                mPackageName = packageName;
20260                mWeFroze = mFrozenPackages.add(mPackageName);
20261
20262                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20263                if (ps != null) {
20264                    killApplication(ps.name, ps.appId, userId, killReason);
20265                }
20266
20267                final PackageParser.Package p = mPackages.get(packageName);
20268                if (p != null && p.childPackages != null) {
20269                    final int N = p.childPackages.size();
20270                    mChildren = new PackageFreezer[N];
20271                    for (int i = 0; i < N; i++) {
20272                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20273                                userId, killReason);
20274                    }
20275                } else {
20276                    mChildren = null;
20277                }
20278            }
20279            mCloseGuard.open("close");
20280        }
20281
20282        @Override
20283        protected void finalize() throws Throwable {
20284            try {
20285                mCloseGuard.warnIfOpen();
20286                close();
20287            } finally {
20288                super.finalize();
20289            }
20290        }
20291
20292        @Override
20293        public void close() {
20294            mCloseGuard.close();
20295            if (mClosed.compareAndSet(false, true)) {
20296                synchronized (mPackages) {
20297                    if (mWeFroze) {
20298                        mFrozenPackages.remove(mPackageName);
20299                    }
20300
20301                    if (mChildren != null) {
20302                        for (PackageFreezer freezer : mChildren) {
20303                            freezer.close();
20304                        }
20305                    }
20306                }
20307            }
20308        }
20309    }
20310
20311    /**
20312     * Verify that given package is currently frozen.
20313     */
20314    private void checkPackageFrozen(String packageName) {
20315        synchronized (mPackages) {
20316            if (!mFrozenPackages.contains(packageName)) {
20317                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20318            }
20319        }
20320    }
20321
20322    @Override
20323    public int movePackage(final String packageName, final String volumeUuid) {
20324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20325
20326        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20327        final int moveId = mNextMoveId.getAndIncrement();
20328        mHandler.post(new Runnable() {
20329            @Override
20330            public void run() {
20331                try {
20332                    movePackageInternal(packageName, volumeUuid, moveId, user);
20333                } catch (PackageManagerException e) {
20334                    Slog.w(TAG, "Failed to move " + packageName, e);
20335                    mMoveCallbacks.notifyStatusChanged(moveId,
20336                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20337                }
20338            }
20339        });
20340        return moveId;
20341    }
20342
20343    private void movePackageInternal(final String packageName, final String volumeUuid,
20344            final int moveId, UserHandle user) throws PackageManagerException {
20345        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20346        final PackageManager pm = mContext.getPackageManager();
20347
20348        final boolean currentAsec;
20349        final String currentVolumeUuid;
20350        final File codeFile;
20351        final String installerPackageName;
20352        final String packageAbiOverride;
20353        final int appId;
20354        final String seinfo;
20355        final String label;
20356        final int targetSdkVersion;
20357        final PackageFreezer freezer;
20358        final int[] installedUserIds;
20359
20360        // reader
20361        synchronized (mPackages) {
20362            final PackageParser.Package pkg = mPackages.get(packageName);
20363            final PackageSetting ps = mSettings.mPackages.get(packageName);
20364            if (pkg == null || ps == null) {
20365                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20366            }
20367
20368            if (pkg.applicationInfo.isSystemApp()) {
20369                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20370                        "Cannot move system application");
20371            }
20372
20373            if (pkg.applicationInfo.isExternalAsec()) {
20374                currentAsec = true;
20375                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20376            } else if (pkg.applicationInfo.isForwardLocked()) {
20377                currentAsec = true;
20378                currentVolumeUuid = "forward_locked";
20379            } else {
20380                currentAsec = false;
20381                currentVolumeUuid = ps.volumeUuid;
20382
20383                final File probe = new File(pkg.codePath);
20384                final File probeOat = new File(probe, "oat");
20385                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20386                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20387                            "Move only supported for modern cluster style installs");
20388                }
20389            }
20390
20391            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20392                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20393                        "Package already moved to " + volumeUuid);
20394            }
20395            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20396                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20397                        "Device admin cannot be moved");
20398            }
20399
20400            if (mFrozenPackages.contains(packageName)) {
20401                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20402                        "Failed to move already frozen package");
20403            }
20404
20405            codeFile = new File(pkg.codePath);
20406            installerPackageName = ps.installerPackageName;
20407            packageAbiOverride = ps.cpuAbiOverrideString;
20408            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20409            seinfo = pkg.applicationInfo.seinfo;
20410            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20411            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20412            freezer = freezePackage(packageName, "movePackageInternal");
20413            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20414        }
20415
20416        final Bundle extras = new Bundle();
20417        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20418        extras.putString(Intent.EXTRA_TITLE, label);
20419        mMoveCallbacks.notifyCreated(moveId, extras);
20420
20421        int installFlags;
20422        final boolean moveCompleteApp;
20423        final File measurePath;
20424
20425        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20426            installFlags = INSTALL_INTERNAL;
20427            moveCompleteApp = !currentAsec;
20428            measurePath = Environment.getDataAppDirectory(volumeUuid);
20429        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20430            installFlags = INSTALL_EXTERNAL;
20431            moveCompleteApp = false;
20432            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20433        } else {
20434            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20435            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20436                    || !volume.isMountedWritable()) {
20437                freezer.close();
20438                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20439                        "Move location not mounted private volume");
20440            }
20441
20442            Preconditions.checkState(!currentAsec);
20443
20444            installFlags = INSTALL_INTERNAL;
20445            moveCompleteApp = true;
20446            measurePath = Environment.getDataAppDirectory(volumeUuid);
20447        }
20448
20449        final PackageStats stats = new PackageStats(null, -1);
20450        synchronized (mInstaller) {
20451            for (int userId : installedUserIds) {
20452                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20453                    freezer.close();
20454                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20455                            "Failed to measure package size");
20456                }
20457            }
20458        }
20459
20460        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20461                + stats.dataSize);
20462
20463        final long startFreeBytes = measurePath.getFreeSpace();
20464        final long sizeBytes;
20465        if (moveCompleteApp) {
20466            sizeBytes = stats.codeSize + stats.dataSize;
20467        } else {
20468            sizeBytes = stats.codeSize;
20469        }
20470
20471        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20472            freezer.close();
20473            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20474                    "Not enough free space to move");
20475        }
20476
20477        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20478
20479        final CountDownLatch installedLatch = new CountDownLatch(1);
20480        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20481            @Override
20482            public void onUserActionRequired(Intent intent) throws RemoteException {
20483                throw new IllegalStateException();
20484            }
20485
20486            @Override
20487            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20488                    Bundle extras) throws RemoteException {
20489                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20490                        + PackageManager.installStatusToString(returnCode, msg));
20491
20492                installedLatch.countDown();
20493                freezer.close();
20494
20495                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20496                switch (status) {
20497                    case PackageInstaller.STATUS_SUCCESS:
20498                        mMoveCallbacks.notifyStatusChanged(moveId,
20499                                PackageManager.MOVE_SUCCEEDED);
20500                        break;
20501                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20502                        mMoveCallbacks.notifyStatusChanged(moveId,
20503                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20504                        break;
20505                    default:
20506                        mMoveCallbacks.notifyStatusChanged(moveId,
20507                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20508                        break;
20509                }
20510            }
20511        };
20512
20513        final MoveInfo move;
20514        if (moveCompleteApp) {
20515            // Kick off a thread to report progress estimates
20516            new Thread() {
20517                @Override
20518                public void run() {
20519                    while (true) {
20520                        try {
20521                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20522                                break;
20523                            }
20524                        } catch (InterruptedException ignored) {
20525                        }
20526
20527                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20528                        final int progress = 10 + (int) MathUtils.constrain(
20529                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20530                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20531                    }
20532                }
20533            }.start();
20534
20535            final String dataAppName = codeFile.getName();
20536            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20537                    dataAppName, appId, seinfo, targetSdkVersion);
20538        } else {
20539            move = null;
20540        }
20541
20542        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20543
20544        final Message msg = mHandler.obtainMessage(INIT_COPY);
20545        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20546        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20547                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20548                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20549        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20550        msg.obj = params;
20551
20552        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20553                System.identityHashCode(msg.obj));
20554        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20555                System.identityHashCode(msg.obj));
20556
20557        mHandler.sendMessage(msg);
20558    }
20559
20560    @Override
20561    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20562        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20563
20564        final int realMoveId = mNextMoveId.getAndIncrement();
20565        final Bundle extras = new Bundle();
20566        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20567        mMoveCallbacks.notifyCreated(realMoveId, extras);
20568
20569        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20570            @Override
20571            public void onCreated(int moveId, Bundle extras) {
20572                // Ignored
20573            }
20574
20575            @Override
20576            public void onStatusChanged(int moveId, int status, long estMillis) {
20577                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20578            }
20579        };
20580
20581        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20582        storage.setPrimaryStorageUuid(volumeUuid, callback);
20583        return realMoveId;
20584    }
20585
20586    @Override
20587    public int getMoveStatus(int moveId) {
20588        mContext.enforceCallingOrSelfPermission(
20589                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20590        return mMoveCallbacks.mLastStatus.get(moveId);
20591    }
20592
20593    @Override
20594    public void registerMoveCallback(IPackageMoveObserver callback) {
20595        mContext.enforceCallingOrSelfPermission(
20596                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20597        mMoveCallbacks.register(callback);
20598    }
20599
20600    @Override
20601    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20602        mContext.enforceCallingOrSelfPermission(
20603                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20604        mMoveCallbacks.unregister(callback);
20605    }
20606
20607    @Override
20608    public boolean setInstallLocation(int loc) {
20609        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20610                null);
20611        if (getInstallLocation() == loc) {
20612            return true;
20613        }
20614        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20615                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20616            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20617                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20618            return true;
20619        }
20620        return false;
20621   }
20622
20623    @Override
20624    public int getInstallLocation() {
20625        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20626                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20627                PackageHelper.APP_INSTALL_AUTO);
20628    }
20629
20630    /** Called by UserManagerService */
20631    void cleanUpUser(UserManagerService userManager, int userHandle) {
20632        synchronized (mPackages) {
20633            mDirtyUsers.remove(userHandle);
20634            mUserNeedsBadging.delete(userHandle);
20635            mSettings.removeUserLPw(userHandle);
20636            mPendingBroadcasts.remove(userHandle);
20637            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20638            removeUnusedPackagesLPw(userManager, userHandle);
20639        }
20640    }
20641
20642    /**
20643     * We're removing userHandle and would like to remove any downloaded packages
20644     * that are no longer in use by any other user.
20645     * @param userHandle the user being removed
20646     */
20647    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20648        final boolean DEBUG_CLEAN_APKS = false;
20649        int [] users = userManager.getUserIds();
20650        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20651        while (psit.hasNext()) {
20652            PackageSetting ps = psit.next();
20653            if (ps.pkg == null) {
20654                continue;
20655            }
20656            final String packageName = ps.pkg.packageName;
20657            // Skip over if system app
20658            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20659                continue;
20660            }
20661            if (DEBUG_CLEAN_APKS) {
20662                Slog.i(TAG, "Checking package " + packageName);
20663            }
20664            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20665            if (keep) {
20666                if (DEBUG_CLEAN_APKS) {
20667                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20668                }
20669            } else {
20670                for (int i = 0; i < users.length; i++) {
20671                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20672                        keep = true;
20673                        if (DEBUG_CLEAN_APKS) {
20674                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20675                                    + users[i]);
20676                        }
20677                        break;
20678                    }
20679                }
20680            }
20681            if (!keep) {
20682                if (DEBUG_CLEAN_APKS) {
20683                    Slog.i(TAG, "  Removing package " + packageName);
20684                }
20685                mHandler.post(new Runnable() {
20686                    public void run() {
20687                        deletePackageX(packageName, userHandle, 0);
20688                    } //end run
20689                });
20690            }
20691        }
20692    }
20693
20694    /** Called by UserManagerService */
20695    void createNewUser(int userId, String[] disallowedPackages) {
20696        synchronized (mInstallLock) {
20697            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20698        }
20699        synchronized (mPackages) {
20700            scheduleWritePackageRestrictionsLocked(userId);
20701            scheduleWritePackageListLocked(userId);
20702            applyFactoryDefaultBrowserLPw(userId);
20703            primeDomainVerificationsLPw(userId);
20704        }
20705    }
20706
20707    void onNewUserCreated(final int userId) {
20708        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20709        // If permission review for legacy apps is required, we represent
20710        // dagerous permissions for such apps as always granted runtime
20711        // permissions to keep per user flag state whether review is needed.
20712        // Hence, if a new user is added we have to propagate dangerous
20713        // permission grants for these legacy apps.
20714        if (mPermissionReviewRequired) {
20715            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20716                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20717        }
20718    }
20719
20720    @Override
20721    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20722        mContext.enforceCallingOrSelfPermission(
20723                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20724                "Only package verification agents can read the verifier device identity");
20725
20726        synchronized (mPackages) {
20727            return mSettings.getVerifierDeviceIdentityLPw();
20728        }
20729    }
20730
20731    @Override
20732    public void setPermissionEnforced(String permission, boolean enforced) {
20733        // TODO: Now that we no longer change GID for storage, this should to away.
20734        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20735                "setPermissionEnforced");
20736        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20737            synchronized (mPackages) {
20738                if (mSettings.mReadExternalStorageEnforced == null
20739                        || mSettings.mReadExternalStorageEnforced != enforced) {
20740                    mSettings.mReadExternalStorageEnforced = enforced;
20741                    mSettings.writeLPr();
20742                }
20743            }
20744            // kill any non-foreground processes so we restart them and
20745            // grant/revoke the GID.
20746            final IActivityManager am = ActivityManagerNative.getDefault();
20747            if (am != null) {
20748                final long token = Binder.clearCallingIdentity();
20749                try {
20750                    am.killProcessesBelowForeground("setPermissionEnforcement");
20751                } catch (RemoteException e) {
20752                } finally {
20753                    Binder.restoreCallingIdentity(token);
20754                }
20755            }
20756        } else {
20757            throw new IllegalArgumentException("No selective enforcement for " + permission);
20758        }
20759    }
20760
20761    @Override
20762    @Deprecated
20763    public boolean isPermissionEnforced(String permission) {
20764        return true;
20765    }
20766
20767    @Override
20768    public boolean isStorageLow() {
20769        final long token = Binder.clearCallingIdentity();
20770        try {
20771            final DeviceStorageMonitorInternal
20772                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20773            if (dsm != null) {
20774                return dsm.isMemoryLow();
20775            } else {
20776                return false;
20777            }
20778        } finally {
20779            Binder.restoreCallingIdentity(token);
20780        }
20781    }
20782
20783    @Override
20784    public IPackageInstaller getPackageInstaller() {
20785        return mInstallerService;
20786    }
20787
20788    private boolean userNeedsBadging(int userId) {
20789        int index = mUserNeedsBadging.indexOfKey(userId);
20790        if (index < 0) {
20791            final UserInfo userInfo;
20792            final long token = Binder.clearCallingIdentity();
20793            try {
20794                userInfo = sUserManager.getUserInfo(userId);
20795            } finally {
20796                Binder.restoreCallingIdentity(token);
20797            }
20798            final boolean b;
20799            if (userInfo != null && userInfo.isManagedProfile()) {
20800                b = true;
20801            } else {
20802                b = false;
20803            }
20804            mUserNeedsBadging.put(userId, b);
20805            return b;
20806        }
20807        return mUserNeedsBadging.valueAt(index);
20808    }
20809
20810    @Override
20811    public KeySet getKeySetByAlias(String packageName, String alias) {
20812        if (packageName == null || alias == null) {
20813            return null;
20814        }
20815        synchronized(mPackages) {
20816            final PackageParser.Package pkg = mPackages.get(packageName);
20817            if (pkg == null) {
20818                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20819                throw new IllegalArgumentException("Unknown package: " + packageName);
20820            }
20821            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20822            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20823        }
20824    }
20825
20826    @Override
20827    public KeySet getSigningKeySet(String packageName) {
20828        if (packageName == null) {
20829            return null;
20830        }
20831        synchronized(mPackages) {
20832            final PackageParser.Package pkg = mPackages.get(packageName);
20833            if (pkg == null) {
20834                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20835                throw new IllegalArgumentException("Unknown package: " + packageName);
20836            }
20837            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20838                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20839                throw new SecurityException("May not access signing KeySet of other apps.");
20840            }
20841            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20842            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20843        }
20844    }
20845
20846    @Override
20847    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20848        if (packageName == null || ks == null) {
20849            return false;
20850        }
20851        synchronized(mPackages) {
20852            final PackageParser.Package pkg = mPackages.get(packageName);
20853            if (pkg == null) {
20854                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20855                throw new IllegalArgumentException("Unknown package: " + packageName);
20856            }
20857            IBinder ksh = ks.getToken();
20858            if (ksh instanceof KeySetHandle) {
20859                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20860                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20861            }
20862            return false;
20863        }
20864    }
20865
20866    @Override
20867    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20868        if (packageName == null || ks == null) {
20869            return false;
20870        }
20871        synchronized(mPackages) {
20872            final PackageParser.Package pkg = mPackages.get(packageName);
20873            if (pkg == null) {
20874                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20875                throw new IllegalArgumentException("Unknown package: " + packageName);
20876            }
20877            IBinder ksh = ks.getToken();
20878            if (ksh instanceof KeySetHandle) {
20879                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20880                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20881            }
20882            return false;
20883        }
20884    }
20885
20886    private void deletePackageIfUnusedLPr(final String packageName) {
20887        PackageSetting ps = mSettings.mPackages.get(packageName);
20888        if (ps == null) {
20889            return;
20890        }
20891        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20892            // TODO Implement atomic delete if package is unused
20893            // It is currently possible that the package will be deleted even if it is installed
20894            // after this method returns.
20895            mHandler.post(new Runnable() {
20896                public void run() {
20897                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20898                }
20899            });
20900        }
20901    }
20902
20903    /**
20904     * Check and throw if the given before/after packages would be considered a
20905     * downgrade.
20906     */
20907    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20908            throws PackageManagerException {
20909        if (after.versionCode < before.mVersionCode) {
20910            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20911                    "Update version code " + after.versionCode + " is older than current "
20912                    + before.mVersionCode);
20913        } else if (after.versionCode == before.mVersionCode) {
20914            if (after.baseRevisionCode < before.baseRevisionCode) {
20915                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20916                        "Update base revision code " + after.baseRevisionCode
20917                        + " is older than current " + before.baseRevisionCode);
20918            }
20919
20920            if (!ArrayUtils.isEmpty(after.splitNames)) {
20921                for (int i = 0; i < after.splitNames.length; i++) {
20922                    final String splitName = after.splitNames[i];
20923                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20924                    if (j != -1) {
20925                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20926                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20927                                    "Update split " + splitName + " revision code "
20928                                    + after.splitRevisionCodes[i] + " is older than current "
20929                                    + before.splitRevisionCodes[j]);
20930                        }
20931                    }
20932                }
20933            }
20934        }
20935    }
20936
20937    private static class MoveCallbacks extends Handler {
20938        private static final int MSG_CREATED = 1;
20939        private static final int MSG_STATUS_CHANGED = 2;
20940
20941        private final RemoteCallbackList<IPackageMoveObserver>
20942                mCallbacks = new RemoteCallbackList<>();
20943
20944        private final SparseIntArray mLastStatus = new SparseIntArray();
20945
20946        public MoveCallbacks(Looper looper) {
20947            super(looper);
20948        }
20949
20950        public void register(IPackageMoveObserver callback) {
20951            mCallbacks.register(callback);
20952        }
20953
20954        public void unregister(IPackageMoveObserver callback) {
20955            mCallbacks.unregister(callback);
20956        }
20957
20958        @Override
20959        public void handleMessage(Message msg) {
20960            final SomeArgs args = (SomeArgs) msg.obj;
20961            final int n = mCallbacks.beginBroadcast();
20962            for (int i = 0; i < n; i++) {
20963                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20964                try {
20965                    invokeCallback(callback, msg.what, args);
20966                } catch (RemoteException ignored) {
20967                }
20968            }
20969            mCallbacks.finishBroadcast();
20970            args.recycle();
20971        }
20972
20973        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20974                throws RemoteException {
20975            switch (what) {
20976                case MSG_CREATED: {
20977                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20978                    break;
20979                }
20980                case MSG_STATUS_CHANGED: {
20981                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20982                    break;
20983                }
20984            }
20985        }
20986
20987        private void notifyCreated(int moveId, Bundle extras) {
20988            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20989
20990            final SomeArgs args = SomeArgs.obtain();
20991            args.argi1 = moveId;
20992            args.arg2 = extras;
20993            obtainMessage(MSG_CREATED, args).sendToTarget();
20994        }
20995
20996        private void notifyStatusChanged(int moveId, int status) {
20997            notifyStatusChanged(moveId, status, -1);
20998        }
20999
21000        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21001            Slog.v(TAG, "Move " + moveId + " status " + status);
21002
21003            final SomeArgs args = SomeArgs.obtain();
21004            args.argi1 = moveId;
21005            args.argi2 = status;
21006            args.arg3 = estMillis;
21007            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21008
21009            synchronized (mLastStatus) {
21010                mLastStatus.put(moveId, status);
21011            }
21012        }
21013    }
21014
21015    private final static class OnPermissionChangeListeners extends Handler {
21016        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21017
21018        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21019                new RemoteCallbackList<>();
21020
21021        public OnPermissionChangeListeners(Looper looper) {
21022            super(looper);
21023        }
21024
21025        @Override
21026        public void handleMessage(Message msg) {
21027            switch (msg.what) {
21028                case MSG_ON_PERMISSIONS_CHANGED: {
21029                    final int uid = msg.arg1;
21030                    handleOnPermissionsChanged(uid);
21031                } break;
21032            }
21033        }
21034
21035        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21036            mPermissionListeners.register(listener);
21037
21038        }
21039
21040        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21041            mPermissionListeners.unregister(listener);
21042        }
21043
21044        public void onPermissionsChanged(int uid) {
21045            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21046                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21047            }
21048        }
21049
21050        private void handleOnPermissionsChanged(int uid) {
21051            final int count = mPermissionListeners.beginBroadcast();
21052            try {
21053                for (int i = 0; i < count; i++) {
21054                    IOnPermissionsChangeListener callback = mPermissionListeners
21055                            .getBroadcastItem(i);
21056                    try {
21057                        callback.onPermissionsChanged(uid);
21058                    } catch (RemoteException e) {
21059                        Log.e(TAG, "Permission listener is dead", e);
21060                    }
21061                }
21062            } finally {
21063                mPermissionListeners.finishBroadcast();
21064            }
21065        }
21066    }
21067
21068    private class PackageManagerInternalImpl extends PackageManagerInternal {
21069        @Override
21070        public void setLocationPackagesProvider(PackagesProvider provider) {
21071            synchronized (mPackages) {
21072                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21073            }
21074        }
21075
21076        @Override
21077        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21078            synchronized (mPackages) {
21079                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21080            }
21081        }
21082
21083        @Override
21084        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21085            synchronized (mPackages) {
21086                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21087            }
21088        }
21089
21090        @Override
21091        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21092            synchronized (mPackages) {
21093                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21094            }
21095        }
21096
21097        @Override
21098        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21099            synchronized (mPackages) {
21100                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21101            }
21102        }
21103
21104        @Override
21105        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21106            synchronized (mPackages) {
21107                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21108            }
21109        }
21110
21111        @Override
21112        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21113            synchronized (mPackages) {
21114                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21115                        packageName, userId);
21116            }
21117        }
21118
21119        @Override
21120        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21121            synchronized (mPackages) {
21122                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21123                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21124                        packageName, userId);
21125            }
21126        }
21127
21128        @Override
21129        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21130            synchronized (mPackages) {
21131                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21132                        packageName, userId);
21133            }
21134        }
21135
21136        @Override
21137        public void setKeepUninstalledPackages(final List<String> packageList) {
21138            Preconditions.checkNotNull(packageList);
21139            List<String> removedFromList = null;
21140            synchronized (mPackages) {
21141                if (mKeepUninstalledPackages != null) {
21142                    final int packagesCount = mKeepUninstalledPackages.size();
21143                    for (int i = 0; i < packagesCount; i++) {
21144                        String oldPackage = mKeepUninstalledPackages.get(i);
21145                        if (packageList != null && packageList.contains(oldPackage)) {
21146                            continue;
21147                        }
21148                        if (removedFromList == null) {
21149                            removedFromList = new ArrayList<>();
21150                        }
21151                        removedFromList.add(oldPackage);
21152                    }
21153                }
21154                mKeepUninstalledPackages = new ArrayList<>(packageList);
21155                if (removedFromList != null) {
21156                    final int removedCount = removedFromList.size();
21157                    for (int i = 0; i < removedCount; i++) {
21158                        deletePackageIfUnusedLPr(removedFromList.get(i));
21159                    }
21160                }
21161            }
21162        }
21163
21164        @Override
21165        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21166            synchronized (mPackages) {
21167                // If we do not support permission review, done.
21168                if (!mPermissionReviewRequired) {
21169                    return false;
21170                }
21171
21172                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21173                if (packageSetting == null) {
21174                    return false;
21175                }
21176
21177                // Permission review applies only to apps not supporting the new permission model.
21178                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21179                    return false;
21180                }
21181
21182                // Legacy apps have the permission and get user consent on launch.
21183                PermissionsState permissionsState = packageSetting.getPermissionsState();
21184                return permissionsState.isPermissionReviewRequired(userId);
21185            }
21186        }
21187
21188        @Override
21189        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21190            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21191        }
21192
21193        @Override
21194        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21195                int userId) {
21196            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21197        }
21198
21199        @Override
21200        public void setDeviceAndProfileOwnerPackages(
21201                int deviceOwnerUserId, String deviceOwnerPackage,
21202                SparseArray<String> profileOwnerPackages) {
21203            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21204                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21205        }
21206
21207        @Override
21208        public boolean isPackageDataProtected(int userId, String packageName) {
21209            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21210        }
21211
21212        @Override
21213        public boolean wasPackageEverLaunched(String packageName, int userId) {
21214            synchronized (mPackages) {
21215                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21216            }
21217        }
21218
21219        @Override
21220        public void grantRuntimePermission(String packageName, String name, int userId,
21221                boolean overridePolicy) {
21222            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21223                    overridePolicy);
21224        }
21225
21226        @Override
21227        public void revokeRuntimePermission(String packageName, String name, int userId,
21228                boolean overridePolicy) {
21229            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21230                    overridePolicy);
21231        }
21232    }
21233
21234    @Override
21235    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21236        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21237        synchronized (mPackages) {
21238            final long identity = Binder.clearCallingIdentity();
21239            try {
21240                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21241                        packageNames, userId);
21242            } finally {
21243                Binder.restoreCallingIdentity(identity);
21244            }
21245        }
21246    }
21247
21248    private static void enforceSystemOrPhoneCaller(String tag) {
21249        int callingUid = Binder.getCallingUid();
21250        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21251            throw new SecurityException(
21252                    "Cannot call " + tag + " from UID " + callingUid);
21253        }
21254    }
21255
21256    boolean isHistoricalPackageUsageAvailable() {
21257        return mPackageUsage.isHistoricalPackageUsageAvailable();
21258    }
21259
21260    /**
21261     * Return a <b>copy</b> of the collection of packages known to the package manager.
21262     * @return A copy of the values of mPackages.
21263     */
21264    Collection<PackageParser.Package> getPackages() {
21265        synchronized (mPackages) {
21266            return new ArrayList<>(mPackages.values());
21267        }
21268    }
21269
21270    /**
21271     * Logs process start information (including base APK hash) to the security log.
21272     * @hide
21273     */
21274    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21275            String apkFile, int pid) {
21276        if (!SecurityLog.isLoggingEnabled()) {
21277            return;
21278        }
21279        Bundle data = new Bundle();
21280        data.putLong("startTimestamp", System.currentTimeMillis());
21281        data.putString("processName", processName);
21282        data.putInt("uid", uid);
21283        data.putString("seinfo", seinfo);
21284        data.putString("apkFile", apkFile);
21285        data.putInt("pid", pid);
21286        Message msg = mProcessLoggingHandler.obtainMessage(
21287                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21288        msg.setData(data);
21289        mProcessLoggingHandler.sendMessage(msg);
21290    }
21291
21292    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21293        return mCompilerStats.getPackageStats(pkgName);
21294    }
21295
21296    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21297        return getOrCreateCompilerPackageStats(pkg.packageName);
21298    }
21299
21300    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21301        return mCompilerStats.getOrCreatePackageStats(pkgName);
21302    }
21303
21304    public void deleteCompilerPackageStats(String pkgName) {
21305        mCompilerStats.deletePackageStats(pkgName);
21306    }
21307}
21308