PackageManagerService.java revision fe939916a6d9bd092b782e6fd21856b574467d88
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
68import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
69import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
70import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
71import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
72import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
73import static android.content.pm.PackageManager.PERMISSION_DENIED;
74import static android.content.pm.PackageManager.PERMISSION_GRANTED;
75import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
76import static android.content.pm.PackageParser.isApkFile;
77import static android.os.Process.PACKAGE_INFO_GID;
78import static android.os.Process.SYSTEM_UID;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
97
98import android.Manifest;
99import android.annotation.NonNull;
100import android.annotation.Nullable;
101import android.app.ActivityManager;
102import android.app.ActivityManagerNative;
103import android.app.IActivityManager;
104import android.app.admin.IDevicePolicyManager;
105import android.app.backup.IBackupManager;
106import android.content.BroadcastReceiver;
107import android.content.ComponentName;
108import android.content.Context;
109import android.content.IIntentReceiver;
110import android.content.Intent;
111import android.content.IntentFilter;
112import android.content.IntentSender;
113import android.content.IntentSender.SendIntentException;
114import android.content.ServiceConnection;
115import android.content.pm.ActivityInfo;
116import android.content.pm.ApplicationInfo;
117import android.content.pm.AppsQueryHelper;
118import android.content.pm.ComponentInfo;
119import android.content.pm.EphemeralApplicationInfo;
120import android.content.pm.EphemeralResolveInfo;
121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
122import android.content.pm.FeatureInfo;
123import android.content.pm.IOnPermissionsChangeListener;
124import android.content.pm.IPackageDataObserver;
125import android.content.pm.IPackageDeleteObserver;
126import android.content.pm.IPackageDeleteObserver2;
127import android.content.pm.IPackageInstallObserver2;
128import android.content.pm.IPackageInstaller;
129import android.content.pm.IPackageManager;
130import android.content.pm.IPackageMoveObserver;
131import android.content.pm.IPackageStatsObserver;
132import android.content.pm.InstrumentationInfo;
133import android.content.pm.IntentFilterVerificationInfo;
134import android.content.pm.KeySet;
135import android.content.pm.PackageCleanItem;
136import android.content.pm.PackageInfo;
137import android.content.pm.PackageInfoLite;
138import android.content.pm.PackageInstaller;
139import android.content.pm.PackageManager;
140import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
141import android.content.pm.PackageManagerInternal;
142import android.content.pm.PackageParser;
143import android.content.pm.PackageParser.ActivityIntentInfo;
144import android.content.pm.PackageParser.PackageLite;
145import android.content.pm.PackageParser.PackageParserException;
146import android.content.pm.PackageStats;
147import android.content.pm.PackageUserState;
148import android.content.pm.ParceledListSlice;
149import android.content.pm.PermissionGroupInfo;
150import android.content.pm.PermissionInfo;
151import android.content.pm.ProviderInfo;
152import android.content.pm.ResolveInfo;
153import android.content.pm.ServiceInfo;
154import android.content.pm.Signature;
155import android.content.pm.UserInfo;
156import android.content.pm.VerifierDeviceIdentity;
157import android.content.pm.VerifierInfo;
158import android.content.res.Resources;
159import android.graphics.Bitmap;
160import android.hardware.display.DisplayManager;
161import android.net.Uri;
162import android.os.Binder;
163import android.os.Build;
164import android.os.Bundle;
165import android.os.Debug;
166import android.os.Environment;
167import android.os.Environment.UserEnvironment;
168import android.os.FileUtils;
169import android.os.Handler;
170import android.os.IBinder;
171import android.os.Looper;
172import android.os.Message;
173import android.os.Parcel;
174import android.os.ParcelFileDescriptor;
175import android.os.Parcelable;
176import android.os.Process;
177import android.os.RemoteCallbackList;
178import android.os.RemoteException;
179import android.os.ResultReceiver;
180import android.os.SELinux;
181import android.os.ServiceManager;
182import android.os.SystemClock;
183import android.os.SystemProperties;
184import android.os.Trace;
185import android.os.UserHandle;
186import android.os.UserManager;
187import android.os.storage.IMountService;
188import android.os.storage.MountServiceInternal;
189import android.os.storage.StorageEventListener;
190import android.os.storage.StorageManager;
191import android.os.storage.VolumeInfo;
192import android.os.storage.VolumeRecord;
193import android.security.KeyStore;
194import android.security.SystemKeyStore;
195import android.system.ErrnoException;
196import android.system.Os;
197import android.text.TextUtils;
198import android.text.format.DateUtils;
199import android.util.ArrayMap;
200import android.util.ArraySet;
201import android.util.AtomicFile;
202import android.util.DisplayMetrics;
203import android.util.EventLog;
204import android.util.ExceptionUtils;
205import android.util.Log;
206import android.util.LogPrinter;
207import android.util.MathUtils;
208import android.util.PrintStreamPrinter;
209import android.util.Slog;
210import android.util.SparseArray;
211import android.util.SparseBooleanArray;
212import android.util.SparseIntArray;
213import android.util.Xml;
214import android.view.Display;
215
216import com.android.internal.R;
217import com.android.internal.annotations.GuardedBy;
218import com.android.internal.app.IMediaContainerService;
219import com.android.internal.app.ResolverActivity;
220import com.android.internal.content.NativeLibraryHelper;
221import com.android.internal.content.PackageHelper;
222import com.android.internal.os.IParcelFileDescriptorFactory;
223import com.android.internal.os.InstallerConnection.InstallerException;
224import com.android.internal.os.SomeArgs;
225import com.android.internal.os.Zygote;
226import com.android.internal.util.ArrayUtils;
227import com.android.internal.util.FastPrintWriter;
228import com.android.internal.util.FastXmlSerializer;
229import com.android.internal.util.IndentingPrintWriter;
230import com.android.internal.util.Preconditions;
231import com.android.internal.util.XmlUtils;
232import com.android.server.EventLogTags;
233import com.android.server.FgThread;
234import com.android.server.IntentResolver;
235import com.android.server.LocalServices;
236import com.android.server.ServiceThread;
237import com.android.server.SystemConfig;
238import com.android.server.Watchdog;
239import com.android.server.pm.PermissionsState.PermissionState;
240import com.android.server.pm.Settings.DatabaseVersion;
241import com.android.server.pm.Settings.VersionInfo;
242import com.android.server.storage.DeviceStorageMonitorInternal;
243
244import dalvik.system.DexFile;
245import dalvik.system.VMRuntime;
246
247import libcore.io.IoUtils;
248import libcore.util.EmptyArray;
249
250import org.xmlpull.v1.XmlPullParser;
251import org.xmlpull.v1.XmlPullParserException;
252import org.xmlpull.v1.XmlSerializer;
253
254import java.io.BufferedInputStream;
255import java.io.BufferedOutputStream;
256import java.io.BufferedReader;
257import java.io.ByteArrayInputStream;
258import java.io.ByteArrayOutputStream;
259import java.io.File;
260import java.io.FileDescriptor;
261import java.io.FileNotFoundException;
262import java.io.FileOutputStream;
263import java.io.FileReader;
264import java.io.FilenameFilter;
265import java.io.IOException;
266import java.io.InputStream;
267import java.io.PrintWriter;
268import java.nio.charset.StandardCharsets;
269import java.security.MessageDigest;
270import java.security.NoSuchAlgorithmException;
271import java.security.PublicKey;
272import java.security.cert.CertificateEncodingException;
273import java.security.cert.CertificateException;
274import java.text.SimpleDateFormat;
275import java.util.ArrayList;
276import java.util.Arrays;
277import java.util.Collection;
278import java.util.Collections;
279import java.util.Comparator;
280import java.util.Date;
281import java.util.HashSet;
282import java.util.Iterator;
283import java.util.List;
284import java.util.Map;
285import java.util.Objects;
286import java.util.Set;
287import java.util.concurrent.CountDownLatch;
288import java.util.concurrent.TimeUnit;
289import java.util.concurrent.atomic.AtomicBoolean;
290import java.util.concurrent.atomic.AtomicInteger;
291import java.util.concurrent.atomic.AtomicLong;
292
293/**
294 * Keep track of all those .apks everywhere.
295 *
296 * This is very central to the platform's security; please run the unit
297 * tests whenever making modifications here:
298 *
299runtest -c android.content.pm.PackageManagerTests frameworks-core
300 *
301 * {@hide}
302 */
303public class PackageManagerService extends IPackageManager.Stub {
304    static final String TAG = "PackageManager";
305    static final boolean DEBUG_SETTINGS = false;
306    static final boolean DEBUG_PREFERRED = false;
307    static final boolean DEBUG_UPGRADE = false;
308    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
309    private static final boolean DEBUG_BACKUP = false;
310    private static final boolean DEBUG_INSTALL = false;
311    private static final boolean DEBUG_REMOVE = false;
312    private static final boolean DEBUG_BROADCASTS = false;
313    private static final boolean DEBUG_SHOW_INFO = false;
314    private static final boolean DEBUG_PACKAGE_INFO = false;
315    private static final boolean DEBUG_INTENT_MATCHING = false;
316    private static final boolean DEBUG_PACKAGE_SCANNING = false;
317    private static final boolean DEBUG_VERIFY = false;
318
319    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
320    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
321    // user, but by default initialize to this.
322    static final boolean DEBUG_DEXOPT = false;
323
324    private static final boolean DEBUG_ABI_SELECTION = false;
325    private static final boolean DEBUG_EPHEMERAL = false;
326    private static final boolean DEBUG_TRIAGED_MISSING = false;
327    private static final boolean DEBUG_APP_DATA = false;
328
329    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
330
331    private static final boolean DISABLE_EPHEMERAL_APPS = true;
332
333    private static final int RADIO_UID = Process.PHONE_UID;
334    private static final int LOG_UID = Process.LOG_UID;
335    private static final int NFC_UID = Process.NFC_UID;
336    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
337    private static final int SHELL_UID = Process.SHELL_UID;
338
339    // Cap the size of permission trees that 3rd party apps can define
340    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
341
342    // Suffix used during package installation when copying/moving
343    // package apks to install directory.
344    private static final String INSTALL_PACKAGE_SUFFIX = "-";
345
346    static final int SCAN_NO_DEX = 1<<1;
347    static final int SCAN_FORCE_DEX = 1<<2;
348    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
349    static final int SCAN_NEW_INSTALL = 1<<4;
350    static final int SCAN_NO_PATHS = 1<<5;
351    static final int SCAN_UPDATE_TIME = 1<<6;
352    static final int SCAN_DEFER_DEX = 1<<7;
353    static final int SCAN_BOOTING = 1<<8;
354    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
355    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
356    static final int SCAN_REPLACING = 1<<11;
357    static final int SCAN_REQUIRE_KNOWN = 1<<12;
358    static final int SCAN_MOVE = 1<<13;
359    static final int SCAN_INITIAL = 1<<14;
360    static final int SCAN_CHECK_ONLY = 1<<15;
361
362    static final int REMOVE_CHATTY = 1<<16;
363
364    private static final int[] EMPTY_INT_ARRAY = new int[0];
365
366    /**
367     * Timeout (in milliseconds) after which the watchdog should declare that
368     * our handler thread is wedged.  The usual default for such things is one
369     * minute but we sometimes do very lengthy I/O operations on this thread,
370     * such as installing multi-gigabyte applications, so ours needs to be longer.
371     */
372    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
373
374    /**
375     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
376     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
377     * settings entry if available, otherwise we use the hardcoded default.  If it's been
378     * more than this long since the last fstrim, we force one during the boot sequence.
379     *
380     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
381     * one gets run at the next available charging+idle time.  This final mandatory
382     * no-fstrim check kicks in only of the other scheduling criteria is never met.
383     */
384    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
385
386    /**
387     * Whether verification is enabled by default.
388     */
389    private static final boolean DEFAULT_VERIFY_ENABLE = true;
390
391    /**
392     * The default maximum time to wait for the verification agent to return in
393     * milliseconds.
394     */
395    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
396
397    /**
398     * The default response for package verification timeout.
399     *
400     * This can be either PackageManager.VERIFICATION_ALLOW or
401     * PackageManager.VERIFICATION_REJECT.
402     */
403    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
404
405    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
406
407    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
408            DEFAULT_CONTAINER_PACKAGE,
409            "com.android.defcontainer.DefaultContainerService");
410
411    private static final String KILL_APP_REASON_GIDS_CHANGED =
412            "permission grant or revoke changed gids";
413
414    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
415            "permissions revoked";
416
417    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
418
419    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
420
421    /** Permission grant: not grant the permission. */
422    private static final int GRANT_DENIED = 1;
423
424    /** Permission grant: grant the permission as an install permission. */
425    private static final int GRANT_INSTALL = 2;
426
427    /** Permission grant: grant the permission as a runtime one. */
428    private static final int GRANT_RUNTIME = 3;
429
430    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
431    private static final int GRANT_UPGRADE = 4;
432
433    /** Canonical intent used to identify what counts as a "web browser" app */
434    private static final Intent sBrowserIntent;
435    static {
436        sBrowserIntent = new Intent();
437        sBrowserIntent.setAction(Intent.ACTION_VIEW);
438        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
439        sBrowserIntent.setData(Uri.parse("http:"));
440    }
441
442    final ServiceThread mHandlerThread;
443
444    final PackageHandler mHandler;
445
446    /**
447     * Messages for {@link #mHandler} that need to wait for system ready before
448     * being dispatched.
449     */
450    private ArrayList<Message> mPostSystemReadyMessages;
451
452    final int mSdkVersion = Build.VERSION.SDK_INT;
453
454    final Context mContext;
455    final boolean mFactoryTest;
456    final boolean mOnlyCore;
457    final DisplayMetrics mMetrics;
458    final int mDefParseFlags;
459    final String[] mSeparateProcesses;
460    final boolean mIsUpgrade;
461
462    /** The location for ASEC container files on internal storage. */
463    final String mAsecInternalPath;
464
465    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
466    // LOCK HELD.  Can be called with mInstallLock held.
467    @GuardedBy("mInstallLock")
468    final Installer mInstaller;
469
470    /** Directory where installed third-party apps stored */
471    final File mAppInstallDir;
472    final File mEphemeralInstallDir;
473
474    /**
475     * Directory to which applications installed internally have their
476     * 32 bit native libraries copied.
477     */
478    private File mAppLib32InstallDir;
479
480    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
481    // apps.
482    final File mDrmAppPrivateInstallDir;
483
484    // ----------------------------------------------------------------
485
486    // Lock for state used when installing and doing other long running
487    // operations.  Methods that must be called with this lock held have
488    // the suffix "LI".
489    final Object mInstallLock = new Object();
490
491    // ----------------------------------------------------------------
492
493    // Keys are String (package name), values are Package.  This also serves
494    // as the lock for the global state.  Methods that must be called with
495    // this lock held have the prefix "LP".
496    @GuardedBy("mPackages")
497    final ArrayMap<String, PackageParser.Package> mPackages =
498            new ArrayMap<String, PackageParser.Package>();
499
500    // Tracks available target package names -> overlay package paths.
501    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
502        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
503
504    /**
505     * Tracks new system packages [received in an OTA] that we expect to
506     * find updated user-installed versions. Keys are package name, values
507     * are package location.
508     */
509    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
510
511    /**
512     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
513     */
514    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
515    /**
516     * Whether or not system app permissions should be promoted from install to runtime.
517     */
518    boolean mPromoteSystemApps;
519
520    final Settings mSettings;
521    boolean mRestoredSettings;
522
523    // System configuration read by SystemConfig.
524    final int[] mGlobalGids;
525    final SparseArray<ArraySet<String>> mSystemPermissions;
526    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
527
528    // If mac_permissions.xml was found for seinfo labeling.
529    boolean mFoundPolicyFile;
530
531    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
532
533    public static final class SharedLibraryEntry {
534        public final String path;
535        public final String apk;
536
537        SharedLibraryEntry(String _path, String _apk) {
538            path = _path;
539            apk = _apk;
540        }
541    }
542
543    // Currently known shared libraries.
544    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
545            new ArrayMap<String, SharedLibraryEntry>();
546
547    // All available activities, for your resolving pleasure.
548    final ActivityIntentResolver mActivities =
549            new ActivityIntentResolver();
550
551    // All available receivers, for your resolving pleasure.
552    final ActivityIntentResolver mReceivers =
553            new ActivityIntentResolver();
554
555    // All available services, for your resolving pleasure.
556    final ServiceIntentResolver mServices = new ServiceIntentResolver();
557
558    // All available providers, for your resolving pleasure.
559    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
560
561    // Mapping from provider base names (first directory in content URI codePath)
562    // to the provider information.
563    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
564            new ArrayMap<String, PackageParser.Provider>();
565
566    // Mapping from instrumentation class names to info about them.
567    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
568            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
569
570    // Mapping from permission names to info about them.
571    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
572            new ArrayMap<String, PackageParser.PermissionGroup>();
573
574    // Packages whose data we have transfered into another package, thus
575    // should no longer exist.
576    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
577
578    // Broadcast actions that are only available to the system.
579    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
580
581    /** List of packages waiting for verification. */
582    final SparseArray<PackageVerificationState> mPendingVerification
583            = new SparseArray<PackageVerificationState>();
584
585    /** Set of packages associated with each app op permission. */
586    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
587
588    final PackageInstallerService mInstallerService;
589
590    private final PackageDexOptimizer mPackageDexOptimizer;
591
592    private AtomicInteger mNextMoveId = new AtomicInteger();
593    private final MoveCallbacks mMoveCallbacks;
594
595    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
596
597    // Cache of users who need badging.
598    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
599
600    /** Token for keys in mPendingVerification. */
601    private int mPendingVerificationToken = 0;
602
603    volatile boolean mSystemReady;
604    volatile boolean mSafeMode;
605    volatile boolean mHasSystemUidErrors;
606
607    ApplicationInfo mAndroidApplication;
608    final ActivityInfo mResolveActivity = new ActivityInfo();
609    final ResolveInfo mResolveInfo = new ResolveInfo();
610    ComponentName mResolveComponentName;
611    PackageParser.Package mPlatformPackage;
612    ComponentName mCustomResolverComponentName;
613
614    boolean mResolverReplaced = false;
615
616    private final @Nullable ComponentName mIntentFilterVerifierComponent;
617    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
618
619    private int mIntentFilterVerificationToken = 0;
620
621    /** Component that knows whether or not an ephemeral application exists */
622    final ComponentName mEphemeralResolverComponent;
623    /** The service connection to the ephemeral resolver */
624    final EphemeralResolverConnection mEphemeralResolverConnection;
625
626    /** Component used to install ephemeral applications */
627    final ComponentName mEphemeralInstallerComponent;
628    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
629    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
630
631    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
632            = new SparseArray<IntentFilterVerificationState>();
633
634    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
635            new DefaultPermissionGrantPolicy(this);
636
637    // List of packages names to keep cached, even if they are uninstalled for all users
638    private List<String> mKeepUninstalledPackages;
639
640    private boolean mUseJitProfiles =
641            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
642
643    private static class IFVerificationParams {
644        PackageParser.Package pkg;
645        boolean replacing;
646        int userId;
647        int verifierUid;
648
649        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
650                int _userId, int _verifierUid) {
651            pkg = _pkg;
652            replacing = _replacing;
653            userId = _userId;
654            replacing = _replacing;
655            verifierUid = _verifierUid;
656        }
657    }
658
659    private interface IntentFilterVerifier<T extends IntentFilter> {
660        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
661                                               T filter, String packageName);
662        void startVerifications(int userId);
663        void receiveVerificationResponse(int verificationId);
664    }
665
666    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
667        private Context mContext;
668        private ComponentName mIntentFilterVerifierComponent;
669        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
670
671        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
672            mContext = context;
673            mIntentFilterVerifierComponent = verifierComponent;
674        }
675
676        private String getDefaultScheme() {
677            return IntentFilter.SCHEME_HTTPS;
678        }
679
680        @Override
681        public void startVerifications(int userId) {
682            // Launch verifications requests
683            int count = mCurrentIntentFilterVerifications.size();
684            for (int n=0; n<count; n++) {
685                int verificationId = mCurrentIntentFilterVerifications.get(n);
686                final IntentFilterVerificationState ivs =
687                        mIntentFilterVerificationStates.get(verificationId);
688
689                String packageName = ivs.getPackageName();
690
691                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
692                final int filterCount = filters.size();
693                ArraySet<String> domainsSet = new ArraySet<>();
694                for (int m=0; m<filterCount; m++) {
695                    PackageParser.ActivityIntentInfo filter = filters.get(m);
696                    domainsSet.addAll(filter.getHostsList());
697                }
698                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
699                synchronized (mPackages) {
700                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
701                            packageName, domainsList) != null) {
702                        scheduleWriteSettingsLocked();
703                    }
704                }
705                sendVerificationRequest(userId, verificationId, ivs);
706            }
707            mCurrentIntentFilterVerifications.clear();
708        }
709
710        private void sendVerificationRequest(int userId, int verificationId,
711                IntentFilterVerificationState ivs) {
712
713            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
714            verificationIntent.putExtra(
715                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
716                    verificationId);
717            verificationIntent.putExtra(
718                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
719                    getDefaultScheme());
720            verificationIntent.putExtra(
721                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
722                    ivs.getHostsString());
723            verificationIntent.putExtra(
724                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
725                    ivs.getPackageName());
726            verificationIntent.setComponent(mIntentFilterVerifierComponent);
727            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
728
729            UserHandle user = new UserHandle(userId);
730            mContext.sendBroadcastAsUser(verificationIntent, user);
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Sending IntentFilter verification broadcast");
733        }
734
735        public void receiveVerificationResponse(int verificationId) {
736            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
737
738            final boolean verified = ivs.isVerified();
739
740            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
741            final int count = filters.size();
742            if (DEBUG_DOMAIN_VERIFICATION) {
743                Slog.i(TAG, "Received verification response " + verificationId
744                        + " for " + count + " filters, verified=" + verified);
745            }
746            for (int n=0; n<count; n++) {
747                PackageParser.ActivityIntentInfo filter = filters.get(n);
748                filter.setVerified(verified);
749
750                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
751                        + " verified with result:" + verified + " and hosts:"
752                        + ivs.getHostsString());
753            }
754
755            mIntentFilterVerificationStates.remove(verificationId);
756
757            final String packageName = ivs.getPackageName();
758            IntentFilterVerificationInfo ivi = null;
759
760            synchronized (mPackages) {
761                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
762            }
763            if (ivi == null) {
764                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
765                        + verificationId + " packageName:" + packageName);
766                return;
767            }
768            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
769                    "Updating IntentFilterVerificationInfo for package " + packageName
770                            +" verificationId:" + verificationId);
771
772            synchronized (mPackages) {
773                if (verified) {
774                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
775                } else {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
777                }
778                scheduleWriteSettingsLocked();
779
780                final int userId = ivs.getUserId();
781                if (userId != UserHandle.USER_ALL) {
782                    final int userStatus =
783                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
784
785                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
786                    boolean needUpdate = false;
787
788                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
789                    // already been set by the User thru the Disambiguation dialog
790                    switch (userStatus) {
791                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
792                            if (verified) {
793                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
794                            } else {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
796                            }
797                            needUpdate = true;
798                            break;
799
800                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
801                            if (verified) {
802                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
803                                needUpdate = true;
804                            }
805                            break;
806
807                        default:
808                            // Nothing to do
809                    }
810
811                    if (needUpdate) {
812                        mSettings.updateIntentFilterVerificationStatusLPw(
813                                packageName, updatedStatus, userId);
814                        scheduleWritePackageRestrictionsLocked(userId);
815                    }
816                }
817            }
818        }
819
820        @Override
821        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
822                    ActivityIntentInfo filter, String packageName) {
823            if (!hasValidDomains(filter)) {
824                return false;
825            }
826            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
827            if (ivs == null) {
828                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
829                        packageName);
830            }
831            if (DEBUG_DOMAIN_VERIFICATION) {
832                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
833            }
834            ivs.addFilter(filter);
835            return true;
836        }
837
838        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
839                int userId, int verificationId, String packageName) {
840            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
841                    verifierUid, userId, packageName);
842            ivs.setPendingState();
843            synchronized (mPackages) {
844                mIntentFilterVerificationStates.append(verificationId, ivs);
845                mCurrentIntentFilterVerifications.add(verificationId);
846            }
847            return ivs;
848        }
849    }
850
851    private static boolean hasValidDomains(ActivityIntentInfo filter) {
852        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
853                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
854                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
855    }
856
857    // Set of pending broadcasts for aggregating enable/disable of components.
858    static class PendingPackageBroadcasts {
859        // for each user id, a map of <package name -> components within that package>
860        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
861
862        public PendingPackageBroadcasts() {
863            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
864        }
865
866        public ArrayList<String> get(int userId, String packageName) {
867            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
868            return packages.get(packageName);
869        }
870
871        public void put(int userId, String packageName, ArrayList<String> components) {
872            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
873            packages.put(packageName, components);
874        }
875
876        public void remove(int userId, String packageName) {
877            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
878            if (packages != null) {
879                packages.remove(packageName);
880            }
881        }
882
883        public void remove(int userId) {
884            mUidMap.remove(userId);
885        }
886
887        public int userIdCount() {
888            return mUidMap.size();
889        }
890
891        public int userIdAt(int n) {
892            return mUidMap.keyAt(n);
893        }
894
895        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
896            return mUidMap.get(userId);
897        }
898
899        public int size() {
900            // total number of pending broadcast entries across all userIds
901            int num = 0;
902            for (int i = 0; i< mUidMap.size(); i++) {
903                num += mUidMap.valueAt(i).size();
904            }
905            return num;
906        }
907
908        public void clear() {
909            mUidMap.clear();
910        }
911
912        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
913            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
914            if (map == null) {
915                map = new ArrayMap<String, ArrayList<String>>();
916                mUidMap.put(userId, map);
917            }
918            return map;
919        }
920    }
921    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
922
923    // Service Connection to remote media container service to copy
924    // package uri's from external media onto secure containers
925    // or internal storage.
926    private IMediaContainerService mContainerService = null;
927
928    static final int SEND_PENDING_BROADCAST = 1;
929    static final int MCS_BOUND = 3;
930    static final int END_COPY = 4;
931    static final int INIT_COPY = 5;
932    static final int MCS_UNBIND = 6;
933    static final int START_CLEANING_PACKAGE = 7;
934    static final int FIND_INSTALL_LOC = 8;
935    static final int POST_INSTALL = 9;
936    static final int MCS_RECONNECT = 10;
937    static final int MCS_GIVE_UP = 11;
938    static final int UPDATED_MEDIA_STATUS = 12;
939    static final int WRITE_SETTINGS = 13;
940    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
941    static final int PACKAGE_VERIFIED = 15;
942    static final int CHECK_PENDING_VERIFICATION = 16;
943    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
944    static final int INTENT_FILTER_VERIFIED = 18;
945
946    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
947
948    // Delay time in millisecs
949    static final int BROADCAST_DELAY = 10 * 1000;
950
951    static UserManagerService sUserManager;
952
953    // Stores a list of users whose package restrictions file needs to be updated
954    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
955
956    final private DefaultContainerConnection mDefContainerConn =
957            new DefaultContainerConnection();
958    class DefaultContainerConnection implements ServiceConnection {
959        public void onServiceConnected(ComponentName name, IBinder service) {
960            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
961            IMediaContainerService imcs =
962                IMediaContainerService.Stub.asInterface(service);
963            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
964        }
965
966        public void onServiceDisconnected(ComponentName name) {
967            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
968        }
969    }
970
971    // Recordkeeping of restore-after-install operations that are currently in flight
972    // between the Package Manager and the Backup Manager
973    static class PostInstallData {
974        public InstallArgs args;
975        public PackageInstalledInfo res;
976
977        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
978            args = _a;
979            res = _r;
980        }
981    }
982
983    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
984    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
985
986    // XML tags for backup/restore of various bits of state
987    private static final String TAG_PREFERRED_BACKUP = "pa";
988    private static final String TAG_DEFAULT_APPS = "da";
989    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
990
991    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
992    private static final String TAG_ALL_GRANTS = "rt-grants";
993    private static final String TAG_GRANT = "grant";
994    private static final String ATTR_PACKAGE_NAME = "pkg";
995
996    private static final String TAG_PERMISSION = "perm";
997    private static final String ATTR_PERMISSION_NAME = "name";
998    private static final String ATTR_IS_GRANTED = "g";
999    private static final String ATTR_USER_SET = "set";
1000    private static final String ATTR_USER_FIXED = "fixed";
1001    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1002
1003    // System/policy permission grants are not backed up
1004    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1005            FLAG_PERMISSION_POLICY_FIXED
1006            | FLAG_PERMISSION_SYSTEM_FIXED
1007            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1008
1009    // And we back up these user-adjusted states
1010    private static final int USER_RUNTIME_GRANT_MASK =
1011            FLAG_PERMISSION_USER_SET
1012            | FLAG_PERMISSION_USER_FIXED
1013            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1014
1015    final @Nullable String mRequiredVerifierPackage;
1016    final @Nullable String mRequiredInstallerPackage;
1017
1018    private final PackageUsage mPackageUsage = new PackageUsage();
1019
1020    private class PackageUsage {
1021        private static final int WRITE_INTERVAL
1022            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1023
1024        private final Object mFileLock = new Object();
1025        private final AtomicLong mLastWritten = new AtomicLong(0);
1026        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1027
1028        private boolean mIsHistoricalPackageUsageAvailable = true;
1029
1030        boolean isHistoricalPackageUsageAvailable() {
1031            return mIsHistoricalPackageUsageAvailable;
1032        }
1033
1034        void write(boolean force) {
1035            if (force) {
1036                writeInternal();
1037                return;
1038            }
1039            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1040                && !DEBUG_DEXOPT) {
1041                return;
1042            }
1043            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1044                new Thread("PackageUsage_DiskWriter") {
1045                    @Override
1046                    public void run() {
1047                        try {
1048                            writeInternal();
1049                        } finally {
1050                            mBackgroundWriteRunning.set(false);
1051                        }
1052                    }
1053                }.start();
1054            }
1055        }
1056
1057        private void writeInternal() {
1058            synchronized (mPackages) {
1059                synchronized (mFileLock) {
1060                    AtomicFile file = getFile();
1061                    FileOutputStream f = null;
1062                    try {
1063                        f = file.startWrite();
1064                        BufferedOutputStream out = new BufferedOutputStream(f);
1065                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1066                        StringBuilder sb = new StringBuilder();
1067                        for (PackageParser.Package pkg : mPackages.values()) {
1068                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1069                                continue;
1070                            }
1071                            sb.setLength(0);
1072                            sb.append(pkg.packageName);
1073                            sb.append(' ');
1074                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1075                            sb.append('\n');
1076                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1077                        }
1078                        out.flush();
1079                        file.finishWrite(f);
1080                    } catch (IOException e) {
1081                        if (f != null) {
1082                            file.failWrite(f);
1083                        }
1084                        Log.e(TAG, "Failed to write package usage times", e);
1085                    }
1086                }
1087            }
1088            mLastWritten.set(SystemClock.elapsedRealtime());
1089        }
1090
1091        void readLP() {
1092            synchronized (mFileLock) {
1093                AtomicFile file = getFile();
1094                BufferedInputStream in = null;
1095                try {
1096                    in = new BufferedInputStream(file.openRead());
1097                    StringBuffer sb = new StringBuffer();
1098                    while (true) {
1099                        String packageName = readToken(in, sb, ' ');
1100                        if (packageName == null) {
1101                            break;
1102                        }
1103                        String timeInMillisString = readToken(in, sb, '\n');
1104                        if (timeInMillisString == null) {
1105                            throw new IOException("Failed to find last usage time for package "
1106                                                  + packageName);
1107                        }
1108                        PackageParser.Package pkg = mPackages.get(packageName);
1109                        if (pkg == null) {
1110                            continue;
1111                        }
1112                        long timeInMillis;
1113                        try {
1114                            timeInMillis = Long.parseLong(timeInMillisString);
1115                        } catch (NumberFormatException e) {
1116                            throw new IOException("Failed to parse " + timeInMillisString
1117                                                  + " as a long.", e);
1118                        }
1119                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1120                    }
1121                } catch (FileNotFoundException expected) {
1122                    mIsHistoricalPackageUsageAvailable = false;
1123                } catch (IOException e) {
1124                    Log.w(TAG, "Failed to read package usage times", e);
1125                } finally {
1126                    IoUtils.closeQuietly(in);
1127                }
1128            }
1129            mLastWritten.set(SystemClock.elapsedRealtime());
1130        }
1131
1132        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1133                throws IOException {
1134            sb.setLength(0);
1135            while (true) {
1136                int ch = in.read();
1137                if (ch == -1) {
1138                    if (sb.length() == 0) {
1139                        return null;
1140                    }
1141                    throw new IOException("Unexpected EOF");
1142                }
1143                if (ch == endOfToken) {
1144                    return sb.toString();
1145                }
1146                sb.append((char)ch);
1147            }
1148        }
1149
1150        private AtomicFile getFile() {
1151            File dataDir = Environment.getDataDirectory();
1152            File systemDir = new File(dataDir, "system");
1153            File fname = new File(systemDir, "package-usage.list");
1154            return new AtomicFile(fname);
1155        }
1156    }
1157
1158    class PackageHandler extends Handler {
1159        private boolean mBound = false;
1160        final ArrayList<HandlerParams> mPendingInstalls =
1161            new ArrayList<HandlerParams>();
1162
1163        private boolean connectToService() {
1164            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1165                    " DefaultContainerService");
1166            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1167            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1168            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1169                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1170                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171                mBound = true;
1172                return true;
1173            }
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175            return false;
1176        }
1177
1178        private void disconnectService() {
1179            mContainerService = null;
1180            mBound = false;
1181            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1182            mContext.unbindService(mDefContainerConn);
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1184        }
1185
1186        PackageHandler(Looper looper) {
1187            super(looper);
1188        }
1189
1190        public void handleMessage(Message msg) {
1191            try {
1192                doHandleMessage(msg);
1193            } finally {
1194                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1195            }
1196        }
1197
1198        void doHandleMessage(Message msg) {
1199            switch (msg.what) {
1200                case INIT_COPY: {
1201                    HandlerParams params = (HandlerParams) msg.obj;
1202                    int idx = mPendingInstalls.size();
1203                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1204                    // If a bind was already initiated we dont really
1205                    // need to do anything. The pending install
1206                    // will be processed later on.
1207                    if (!mBound) {
1208                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1209                                System.identityHashCode(mHandler));
1210                        // If this is the only one pending we might
1211                        // have to bind to the service again.
1212                        if (!connectToService()) {
1213                            Slog.e(TAG, "Failed to bind to media container service");
1214                            params.serviceError();
1215                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1216                                    System.identityHashCode(mHandler));
1217                            if (params.traceMethod != null) {
1218                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1219                                        params.traceCookie);
1220                            }
1221                            return;
1222                        } else {
1223                            // Once we bind to the service, the first
1224                            // pending request will be processed.
1225                            mPendingInstalls.add(idx, params);
1226                        }
1227                    } else {
1228                        mPendingInstalls.add(idx, params);
1229                        // Already bound to the service. Just make
1230                        // sure we trigger off processing the first request.
1231                        if (idx == 0) {
1232                            mHandler.sendEmptyMessage(MCS_BOUND);
1233                        }
1234                    }
1235                    break;
1236                }
1237                case MCS_BOUND: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1239                    if (msg.obj != null) {
1240                        mContainerService = (IMediaContainerService) msg.obj;
1241                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1242                                System.identityHashCode(mHandler));
1243                    }
1244                    if (mContainerService == null) {
1245                        if (!mBound) {
1246                            // Something seriously wrong since we are not bound and we are not
1247                            // waiting for connection. Bail out.
1248                            Slog.e(TAG, "Cannot bind to media container service");
1249                            for (HandlerParams params : mPendingInstalls) {
1250                                // Indicate service bind error
1251                                params.serviceError();
1252                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1253                                        System.identityHashCode(params));
1254                                if (params.traceMethod != null) {
1255                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1256                                            params.traceMethod, params.traceCookie);
1257                                }
1258                                return;
1259                            }
1260                            mPendingInstalls.clear();
1261                        } else {
1262                            Slog.w(TAG, "Waiting to connect to media container service");
1263                        }
1264                    } else if (mPendingInstalls.size() > 0) {
1265                        HandlerParams params = mPendingInstalls.get(0);
1266                        if (params != null) {
1267                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1268                                    System.identityHashCode(params));
1269                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1270                            if (params.startCopy()) {
1271                                // We are done...  look for more work or to
1272                                // go idle.
1273                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1274                                        "Checking for more work or unbind...");
1275                                // Delete pending install
1276                                if (mPendingInstalls.size() > 0) {
1277                                    mPendingInstalls.remove(0);
1278                                }
1279                                if (mPendingInstalls.size() == 0) {
1280                                    if (mBound) {
1281                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1282                                                "Posting delayed MCS_UNBIND");
1283                                        removeMessages(MCS_UNBIND);
1284                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1285                                        // Unbind after a little delay, to avoid
1286                                        // continual thrashing.
1287                                        sendMessageDelayed(ubmsg, 10000);
1288                                    }
1289                                } else {
1290                                    // There are more pending requests in queue.
1291                                    // Just post MCS_BOUND message to trigger processing
1292                                    // of next pending install.
1293                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1294                                            "Posting MCS_BOUND for next work");
1295                                    mHandler.sendEmptyMessage(MCS_BOUND);
1296                                }
1297                            }
1298                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1299                        }
1300                    } else {
1301                        // Should never happen ideally.
1302                        Slog.w(TAG, "Empty queue");
1303                    }
1304                    break;
1305                }
1306                case MCS_RECONNECT: {
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1308                    if (mPendingInstalls.size() > 0) {
1309                        if (mBound) {
1310                            disconnectService();
1311                        }
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            for (HandlerParams params : mPendingInstalls) {
1315                                // Indicate service bind error
1316                                params.serviceError();
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1318                                        System.identityHashCode(params));
1319                            }
1320                            mPendingInstalls.clear();
1321                        }
1322                    }
1323                    break;
1324                }
1325                case MCS_UNBIND: {
1326                    // If there is no actual work left, then time to unbind.
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1328
1329                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1330                        if (mBound) {
1331                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1332
1333                            disconnectService();
1334                        }
1335                    } else if (mPendingInstalls.size() > 0) {
1336                        // There are more pending requests in queue.
1337                        // Just post MCS_BOUND message to trigger processing
1338                        // of next pending install.
1339                        mHandler.sendEmptyMessage(MCS_BOUND);
1340                    }
1341
1342                    break;
1343                }
1344                case MCS_GIVE_UP: {
1345                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1346                    HandlerParams params = mPendingInstalls.remove(0);
1347                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1348                            System.identityHashCode(params));
1349                    break;
1350                }
1351                case SEND_PENDING_BROADCAST: {
1352                    String packages[];
1353                    ArrayList<String> components[];
1354                    int size = 0;
1355                    int uids[];
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357                    synchronized (mPackages) {
1358                        if (mPendingBroadcasts == null) {
1359                            return;
1360                        }
1361                        size = mPendingBroadcasts.size();
1362                        if (size <= 0) {
1363                            // Nothing to be done. Just return
1364                            return;
1365                        }
1366                        packages = new String[size];
1367                        components = new ArrayList[size];
1368                        uids = new int[size];
1369                        int i = 0;  // filling out the above arrays
1370
1371                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1372                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1373                            Iterator<Map.Entry<String, ArrayList<String>>> it
1374                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1375                                            .entrySet().iterator();
1376                            while (it.hasNext() && i < size) {
1377                                Map.Entry<String, ArrayList<String>> ent = it.next();
1378                                packages[i] = ent.getKey();
1379                                components[i] = ent.getValue();
1380                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1381                                uids[i] = (ps != null)
1382                                        ? UserHandle.getUid(packageUserId, ps.appId)
1383                                        : -1;
1384                                i++;
1385                            }
1386                        }
1387                        size = i;
1388                        mPendingBroadcasts.clear();
1389                    }
1390                    // Send broadcasts
1391                    for (int i = 0; i < size; i++) {
1392                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1393                    }
1394                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395                    break;
1396                }
1397                case START_CLEANING_PACKAGE: {
1398                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1399                    final String packageName = (String)msg.obj;
1400                    final int userId = msg.arg1;
1401                    final boolean andCode = msg.arg2 != 0;
1402                    synchronized (mPackages) {
1403                        if (userId == UserHandle.USER_ALL) {
1404                            int[] users = sUserManager.getUserIds();
1405                            for (int user : users) {
1406                                mSettings.addPackageToCleanLPw(
1407                                        new PackageCleanItem(user, packageName, andCode));
1408                            }
1409                        } else {
1410                            mSettings.addPackageToCleanLPw(
1411                                    new PackageCleanItem(userId, packageName, andCode));
1412                        }
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                    startCleaningPackages();
1416                } break;
1417                case POST_INSTALL: {
1418                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1419
1420                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1421                    mRunningInstalls.delete(msg.arg1);
1422
1423                    if (data != null) {
1424                        InstallArgs args = data.args;
1425                        PackageInstalledInfo parentRes = data.res;
1426
1427                        final boolean grantPermissions = (args.installFlags
1428                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1429                        final String[] grantedPermissions = args.installGrantPermissions;
1430
1431                        // Handle the parent package
1432                        handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions,
1433                                args.observer);
1434
1435                        // Handle the child packages
1436                        final int childCount = (parentRes.addedChildPackages != null)
1437                                ? parentRes.addedChildPackages.size() : 0;
1438                        for (int i = 0; i < childCount; i++) {
1439                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1440                            handlePackagePostInstall(childRes, grantPermissions, grantedPermissions,
1441                                    args.observer);
1442                        }
1443
1444                        // Log tracing if needed
1445                        if (args.traceMethod != null) {
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1447                                    args.traceCookie);
1448                        }
1449                    } else {
1450                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1451                    }
1452
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1454                } break;
1455                case UPDATED_MEDIA_STATUS: {
1456                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1457                    boolean reportStatus = msg.arg1 == 1;
1458                    boolean doGc = msg.arg2 == 1;
1459                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1460                    if (doGc) {
1461                        // Force a gc to clear up stale containers.
1462                        Runtime.getRuntime().gc();
1463                    }
1464                    if (msg.obj != null) {
1465                        @SuppressWarnings("unchecked")
1466                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1467                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1468                        // Unload containers
1469                        unloadAllContainers(args);
1470                    }
1471                    if (reportStatus) {
1472                        try {
1473                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1474                            PackageHelper.getMountService().finishMediaUpdate();
1475                        } catch (RemoteException e) {
1476                            Log.e(TAG, "MountService not running?");
1477                        }
1478                    }
1479                } break;
1480                case WRITE_SETTINGS: {
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1482                    synchronized (mPackages) {
1483                        removeMessages(WRITE_SETTINGS);
1484                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1485                        mSettings.writeLPr();
1486                        mDirtyUsers.clear();
1487                    }
1488                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1489                } break;
1490                case WRITE_PACKAGE_RESTRICTIONS: {
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1492                    synchronized (mPackages) {
1493                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1494                        for (int userId : mDirtyUsers) {
1495                            mSettings.writePackageRestrictionsLPr(userId);
1496                        }
1497                        mDirtyUsers.clear();
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                } break;
1501                case CHECK_PENDING_VERIFICATION: {
1502                    final int verificationId = msg.arg1;
1503                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1504
1505                    if ((state != null) && !state.timeoutExtended()) {
1506                        final InstallArgs args = state.getInstallArgs();
1507                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1508
1509                        Slog.i(TAG, "Verification timed out for " + originUri);
1510                        mPendingVerification.remove(verificationId);
1511
1512                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1513
1514                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1515                            Slog.i(TAG, "Continuing with installation of " + originUri);
1516                            state.setVerifierResponse(Binder.getCallingUid(),
1517                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1518                            broadcastPackageVerified(verificationId, originUri,
1519                                    PackageManager.VERIFICATION_ALLOW,
1520                                    state.getInstallArgs().getUser());
1521                            try {
1522                                ret = args.copyApk(mContainerService, true);
1523                            } catch (RemoteException e) {
1524                                Slog.e(TAG, "Could not contact the ContainerService");
1525                            }
1526                        } else {
1527                            broadcastPackageVerified(verificationId, originUri,
1528                                    PackageManager.VERIFICATION_REJECT,
1529                                    state.getInstallArgs().getUser());
1530                        }
1531
1532                        Trace.asyncTraceEnd(
1533                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1534
1535                        processPendingInstall(args, ret);
1536                        mHandler.sendEmptyMessage(MCS_UNBIND);
1537                    }
1538                    break;
1539                }
1540                case PACKAGE_VERIFIED: {
1541                    final int verificationId = msg.arg1;
1542
1543                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1544                    if (state == null) {
1545                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1546                        break;
1547                    }
1548
1549                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1550
1551                    state.setVerifierResponse(response.callerUid, response.code);
1552
1553                    if (state.isVerificationComplete()) {
1554                        mPendingVerification.remove(verificationId);
1555
1556                        final InstallArgs args = state.getInstallArgs();
1557                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1558
1559                        int ret;
1560                        if (state.isInstallAllowed()) {
1561                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1562                            broadcastPackageVerified(verificationId, originUri,
1563                                    response.code, state.getInstallArgs().getUser());
1564                            try {
1565                                ret = args.copyApk(mContainerService, true);
1566                            } catch (RemoteException e) {
1567                                Slog.e(TAG, "Could not contact the ContainerService");
1568                            }
1569                        } else {
1570                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1571                        }
1572
1573                        Trace.asyncTraceEnd(
1574                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1575
1576                        processPendingInstall(args, ret);
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579
1580                    break;
1581                }
1582                case START_INTENT_FILTER_VERIFICATIONS: {
1583                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1584                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1585                            params.replacing, params.pkg);
1586                    break;
1587                }
1588                case INTENT_FILTER_VERIFIED: {
1589                    final int verificationId = msg.arg1;
1590
1591                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1592                            verificationId);
1593                    if (state == null) {
1594                        Slog.w(TAG, "Invalid IntentFilter verification token "
1595                                + verificationId + " received");
1596                        break;
1597                    }
1598
1599                    final int userId = state.getUserId();
1600
1601                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1602                            "Processing IntentFilter verification with token:"
1603                            + verificationId + " and userId:" + userId);
1604
1605                    final IntentFilterVerificationResponse response =
1606                            (IntentFilterVerificationResponse) msg.obj;
1607
1608                    state.setVerifierResponse(response.callerUid, response.code);
1609
1610                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                            "IntentFilter verification with token:" + verificationId
1612                            + " and userId:" + userId
1613                            + " is settings verifier response with response code:"
1614                            + response.code);
1615
1616                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1617                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1618                                + response.getFailedDomainsString());
1619                    }
1620
1621                    if (state.isVerificationComplete()) {
1622                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1623                    } else {
1624                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1625                                "IntentFilter verification with token:" + verificationId
1626                                + " was not said to be complete");
1627                    }
1628
1629                    break;
1630                }
1631            }
1632        }
1633    }
1634
1635    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1636            String[] grantedPermissions, IPackageInstallObserver2 installObserver) {
1637        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1638            // Send the removed broadcasts
1639            if (res.removedInfo != null) {
1640                res.removedInfo.sendPackageRemovedBroadcasts();
1641            }
1642
1643            // Now that we successfully installed the package, grant runtime
1644            // permissions if requested before broadcasting the install.
1645            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1646                    >= Build.VERSION_CODES.M) {
1647                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1648            }
1649
1650            final boolean update = res.removedInfo != null
1651                    && res.removedInfo.removedPackage != null;
1652
1653            // If this is the first time we have child packages for a disabled privileged
1654            // app that had no children, we grant requested runtime permissions to the new
1655            // children if the parent on the system image had them already granted.
1656            if (res.pkg.parentPackage != null) {
1657                synchronized (mPackages) {
1658                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1659                }
1660            }
1661
1662            synchronized (mPackages) {
1663                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1664            }
1665
1666            final String packageName = res.pkg.applicationInfo.packageName;
1667            Bundle extras = new Bundle(1);
1668            extras.putInt(Intent.EXTRA_UID, res.uid);
1669
1670            // Determine the set of users who are adding this package for
1671            // the first time vs. those who are seeing an update.
1672            int[] firstUsers = EMPTY_INT_ARRAY;
1673            int[] updateUsers = EMPTY_INT_ARRAY;
1674            if (res.origUsers == null || res.origUsers.length == 0) {
1675                firstUsers = res.newUsers;
1676            } else {
1677                for (int newUser : res.newUsers) {
1678                    boolean isNew = true;
1679                    for (int origUser : res.origUsers) {
1680                        if (origUser == newUser) {
1681                            isNew = false;
1682                            break;
1683                        }
1684                    }
1685                    if (isNew) {
1686                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1687                    } else {
1688                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1689                    }
1690                }
1691            }
1692
1693            // Send installed broadcasts if the install/update is not ephemeral
1694            if (!isEphemeral(res.pkg)) {
1695                // Send added for users that see the package for the first time
1696                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1697                        extras, 0 /*flags*/, null /*targetPackage*/,
1698                        null /*finishedReceiver*/, firstUsers);
1699
1700                // Send added for users that don't see the package for the first time
1701                if (update) {
1702                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1703                }
1704                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1705                        extras, 0 /*flags*/, null /*targetPackage*/,
1706                        null /*finishedReceiver*/, updateUsers);
1707
1708                // Send replaced for users that don't see the package for the first time
1709                if (update) {
1710                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1711                            packageName, extras, 0 /*flags*/,
1712                            null /*targetPackage*/, null /*finishedReceiver*/,
1713                            updateUsers);
1714                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1715                            null /*package*/, null /*extras*/, 0 /*flags*/,
1716                            packageName /*targetPackage*/,
1717                            null /*finishedReceiver*/, updateUsers);
1718                }
1719
1720                // Send broadcast package appeared if forward locked/external for all users
1721                // treat asec-hosted packages like removable media on upgrade
1722                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1723                    if (DEBUG_INSTALL) {
1724                        Slog.i(TAG, "upgrading pkg " + res.pkg
1725                                + " is ASEC-hosted -> AVAILABLE");
1726                    }
1727                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1728                    ArrayList<String> pkgList = new ArrayList<>(1);
1729                    pkgList.add(packageName);
1730                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1731                }
1732            }
1733
1734            // Work that needs to happen on first install within each user
1735            if (firstUsers != null && firstUsers.length > 0) {
1736                synchronized (mPackages) {
1737                    for (int userId : firstUsers) {
1738                        // If this app is a browser and it's newly-installed for some
1739                        // users, clear any default-browser state in those users. The
1740                        // app's nature doesn't depend on the user, so we can just check
1741                        // its browser nature in any user and generalize.
1742                        if (packageIsBrowser(packageName, userId)) {
1743                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1744                        }
1745
1746                        // We may also need to apply pending (restored) runtime
1747                        // permission grants within these users.
1748                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1749                    }
1750                }
1751            }
1752
1753            // Log current value of "unknown sources" setting
1754            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1755                    getUnknownSourcesSettings());
1756
1757            // Force a gc to clear up things
1758            Runtime.getRuntime().gc();
1759
1760            // Remove the replaced package's older resources safely now
1761            // We delete after a gc for applications  on sdcard.
1762            if (res.removedInfo != null && res.removedInfo.args != null) {
1763                synchronized (mInstallLock) {
1764                    res.removedInfo.args.doPostDeleteLI(true);
1765                }
1766            }
1767        }
1768
1769        // If someone is watching installs - notify them
1770        if (installObserver != null) {
1771            try {
1772                Bundle extras = extrasForInstallResult(res);
1773                installObserver.onPackageInstalled(res.name, res.returnCode,
1774                        res.returnMsg, extras);
1775            } catch (RemoteException e) {
1776                Slog.i(TAG, "Observer no longer exists.");
1777            }
1778        }
1779    }
1780
1781    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1782            PackageParser.Package pkg) {
1783        if (pkg.parentPackage == null) {
1784            return;
1785        }
1786        if (pkg.requestedPermissions == null) {
1787            return;
1788        }
1789        final PackageSetting disabledSysParentPs = mSettings
1790                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1791        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1792                || !disabledSysParentPs.isPrivileged()
1793                || (disabledSysParentPs.childPackageNames != null
1794                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1795            return;
1796        }
1797        final int[] allUserIds = sUserManager.getUserIds();
1798        final int permCount = pkg.requestedPermissions.size();
1799        for (int i = 0; i < permCount; i++) {
1800            String permission = pkg.requestedPermissions.get(i);
1801            BasePermission bp = mSettings.mPermissions.get(permission);
1802            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1803                continue;
1804            }
1805            for (int userId : allUserIds) {
1806                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1807                        permission, userId)) {
1808                    grantRuntimePermission(pkg.packageName, permission, userId);
1809                }
1810            }
1811        }
1812    }
1813
1814    private StorageEventListener mStorageListener = new StorageEventListener() {
1815        @Override
1816        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1817            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1818                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1819                    final String volumeUuid = vol.getFsUuid();
1820
1821                    // Clean up any users or apps that were removed or recreated
1822                    // while this volume was missing
1823                    reconcileUsers(volumeUuid);
1824                    reconcileApps(volumeUuid);
1825
1826                    // Clean up any install sessions that expired or were
1827                    // cancelled while this volume was missing
1828                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1829
1830                    loadPrivatePackages(vol);
1831
1832                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1833                    unloadPrivatePackages(vol);
1834                }
1835            }
1836
1837            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1838                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1839                    updateExternalMediaStatus(true, false);
1840                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1841                    updateExternalMediaStatus(false, false);
1842                }
1843            }
1844        }
1845
1846        @Override
1847        public void onVolumeForgotten(String fsUuid) {
1848            if (TextUtils.isEmpty(fsUuid)) {
1849                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1850                return;
1851            }
1852
1853            // Remove any apps installed on the forgotten volume
1854            synchronized (mPackages) {
1855                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1856                for (PackageSetting ps : packages) {
1857                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1858                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1859                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1860                }
1861
1862                mSettings.onVolumeForgotten(fsUuid);
1863                mSettings.writeLPr();
1864            }
1865        }
1866    };
1867
1868    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1869            String[] grantedPermissions) {
1870        for (int userId : userIds) {
1871            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1872        }
1873
1874        // We could have touched GID membership, so flush out packages.list
1875        synchronized (mPackages) {
1876            mSettings.writePackageListLPr();
1877        }
1878    }
1879
1880    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1881            String[] grantedPermissions) {
1882        SettingBase sb = (SettingBase) pkg.mExtras;
1883        if (sb == null) {
1884            return;
1885        }
1886
1887        PermissionsState permissionsState = sb.getPermissionsState();
1888
1889        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1890                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1891
1892        synchronized (mPackages) {
1893            for (String permission : pkg.requestedPermissions) {
1894                BasePermission bp = mSettings.mPermissions.get(permission);
1895                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1896                        && (grantedPermissions == null
1897                               || ArrayUtils.contains(grantedPermissions, permission))) {
1898                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1899                    // Installer cannot change immutable permissions.
1900                    if ((flags & immutableFlags) == 0) {
1901                        grantRuntimePermission(pkg.packageName, permission, userId);
1902                    }
1903                }
1904            }
1905        }
1906    }
1907
1908    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1909        Bundle extras = null;
1910        switch (res.returnCode) {
1911            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1912                extras = new Bundle();
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1914                        res.origPermission);
1915                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1916                        res.origPackage);
1917                break;
1918            }
1919            case PackageManager.INSTALL_SUCCEEDED: {
1920                extras = new Bundle();
1921                extras.putBoolean(Intent.EXTRA_REPLACING,
1922                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1923                break;
1924            }
1925        }
1926        return extras;
1927    }
1928
1929    void scheduleWriteSettingsLocked() {
1930        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1931            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1932        }
1933    }
1934
1935    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1936        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1937        scheduleWritePackageRestrictionsLocked(userId);
1938    }
1939
1940    void scheduleWritePackageRestrictionsLocked(int userId) {
1941        final int[] userIds = (userId == UserHandle.USER_ALL)
1942                ? sUserManager.getUserIds() : new int[]{userId};
1943        for (int nextUserId : userIds) {
1944            if (!sUserManager.exists(nextUserId)) return;
1945            mDirtyUsers.add(nextUserId);
1946            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1947                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1948            }
1949        }
1950    }
1951
1952    public static PackageManagerService main(Context context, Installer installer,
1953            boolean factoryTest, boolean onlyCore) {
1954        PackageManagerService m = new PackageManagerService(context, installer,
1955                factoryTest, onlyCore);
1956        m.enableSystemUserPackages();
1957        ServiceManager.addService("package", m);
1958        return m;
1959    }
1960
1961    private void enableSystemUserPackages() {
1962        if (!UserManager.isSplitSystemUser()) {
1963            return;
1964        }
1965        // For system user, enable apps based on the following conditions:
1966        // - app is whitelisted or belong to one of these groups:
1967        //   -- system app which has no launcher icons
1968        //   -- system app which has INTERACT_ACROSS_USERS permission
1969        //   -- system IME app
1970        // - app is not in the blacklist
1971        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1972        Set<String> enableApps = new ArraySet<>();
1973        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1974                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1975                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1976        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1977        enableApps.addAll(wlApps);
1978        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1979                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1980        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1981        enableApps.removeAll(blApps);
1982        Log.i(TAG, "Applications installed for system user: " + enableApps);
1983        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1984                UserHandle.SYSTEM);
1985        final int allAppsSize = allAps.size();
1986        synchronized (mPackages) {
1987            for (int i = 0; i < allAppsSize; i++) {
1988                String pName = allAps.get(i);
1989                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1990                // Should not happen, but we shouldn't be failing if it does
1991                if (pkgSetting == null) {
1992                    continue;
1993                }
1994                boolean install = enableApps.contains(pName);
1995                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1996                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1997                            + " for system user");
1998                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1999                }
2000            }
2001        }
2002    }
2003
2004    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2005        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2006                Context.DISPLAY_SERVICE);
2007        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2008    }
2009
2010    public PackageManagerService(Context context, Installer installer,
2011            boolean factoryTest, boolean onlyCore) {
2012        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2013                SystemClock.uptimeMillis());
2014
2015        if (mSdkVersion <= 0) {
2016            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2017        }
2018
2019        mContext = context;
2020        mFactoryTest = factoryTest;
2021        mOnlyCore = onlyCore;
2022        mMetrics = new DisplayMetrics();
2023        mSettings = new Settings(mPackages);
2024        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2025                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2026        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2027                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2028        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2029                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2030        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2031                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2032        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2033                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2034        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2035                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2036
2037        String separateProcesses = SystemProperties.get("debug.separate_processes");
2038        if (separateProcesses != null && separateProcesses.length() > 0) {
2039            if ("*".equals(separateProcesses)) {
2040                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2041                mSeparateProcesses = null;
2042                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2043            } else {
2044                mDefParseFlags = 0;
2045                mSeparateProcesses = separateProcesses.split(",");
2046                Slog.w(TAG, "Running with debug.separate_processes: "
2047                        + separateProcesses);
2048            }
2049        } else {
2050            mDefParseFlags = 0;
2051            mSeparateProcesses = null;
2052        }
2053
2054        mInstaller = installer;
2055        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2056                "*dexopt*");
2057        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2058
2059        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2060                FgThread.get().getLooper());
2061
2062        getDefaultDisplayMetrics(context, mMetrics);
2063
2064        SystemConfig systemConfig = SystemConfig.getInstance();
2065        mGlobalGids = systemConfig.getGlobalGids();
2066        mSystemPermissions = systemConfig.getSystemPermissions();
2067        mAvailableFeatures = systemConfig.getAvailableFeatures();
2068
2069        synchronized (mInstallLock) {
2070        // writer
2071        synchronized (mPackages) {
2072            mHandlerThread = new ServiceThread(TAG,
2073                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2074            mHandlerThread.start();
2075            mHandler = new PackageHandler(mHandlerThread.getLooper());
2076            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2077
2078            File dataDir = Environment.getDataDirectory();
2079            mAppInstallDir = new File(dataDir, "app");
2080            mAppLib32InstallDir = new File(dataDir, "app-lib");
2081            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2082            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2083            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2084
2085            sUserManager = new UserManagerService(context, this, mPackages);
2086
2087            // Propagate permission configuration in to package manager.
2088            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2089                    = systemConfig.getPermissions();
2090            for (int i=0; i<permConfig.size(); i++) {
2091                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2092                BasePermission bp = mSettings.mPermissions.get(perm.name);
2093                if (bp == null) {
2094                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2095                    mSettings.mPermissions.put(perm.name, bp);
2096                }
2097                if (perm.gids != null) {
2098                    bp.setGids(perm.gids, perm.perUser);
2099                }
2100            }
2101
2102            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2103            for (int i=0; i<libConfig.size(); i++) {
2104                mSharedLibraries.put(libConfig.keyAt(i),
2105                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2106            }
2107
2108            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2109
2110            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2111
2112            String customResolverActivity = Resources.getSystem().getString(
2113                    R.string.config_customResolverActivity);
2114            if (TextUtils.isEmpty(customResolverActivity)) {
2115                customResolverActivity = null;
2116            } else {
2117                mCustomResolverComponentName = ComponentName.unflattenFromString(
2118                        customResolverActivity);
2119            }
2120
2121            long startTime = SystemClock.uptimeMillis();
2122
2123            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2124                    startTime);
2125
2126            // Set flag to monitor and not change apk file paths when
2127            // scanning install directories.
2128            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2129
2130            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2131            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2132
2133            if (bootClassPath == null) {
2134                Slog.w(TAG, "No BOOTCLASSPATH found!");
2135            }
2136
2137            if (systemServerClassPath == null) {
2138                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2139            }
2140
2141            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2142            final String[] dexCodeInstructionSets =
2143                    getDexCodeInstructionSets(
2144                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2145
2146            /**
2147             * Ensure all external libraries have had dexopt run on them.
2148             */
2149            if (mSharedLibraries.size() > 0) {
2150                // NOTE: For now, we're compiling these system "shared libraries"
2151                // (and framework jars) into all available architectures. It's possible
2152                // to compile them only when we come across an app that uses them (there's
2153                // already logic for that in scanPackageLI) but that adds some complexity.
2154                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2155                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2156                        final String lib = libEntry.path;
2157                        if (lib == null) {
2158                            continue;
2159                        }
2160
2161                        try {
2162                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2163                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2164                                // Shared libraries do not have profiles so we perform a full
2165                                // AOT compilation.
2166                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2167                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2168                                        StorageManager.UUID_PRIVATE_INTERNAL,
2169                                        false /*useProfiles*/);
2170                            }
2171                        } catch (FileNotFoundException e) {
2172                            Slog.w(TAG, "Library not found: " + lib);
2173                        } catch (IOException | InstallerException e) {
2174                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2175                                    + e.getMessage());
2176                        }
2177                    }
2178                }
2179            }
2180
2181            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2182
2183            final VersionInfo ver = mSettings.getInternalVersion();
2184            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2185            // when upgrading from pre-M, promote system app permissions from install to runtime
2186            mPromoteSystemApps =
2187                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2188
2189            // save off the names of pre-existing system packages prior to scanning; we don't
2190            // want to automatically grant runtime permissions for new system apps
2191            if (mPromoteSystemApps) {
2192                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2193                while (pkgSettingIter.hasNext()) {
2194                    PackageSetting ps = pkgSettingIter.next();
2195                    if (isSystemApp(ps)) {
2196                        mExistingSystemPackages.add(ps.name);
2197                    }
2198                }
2199            }
2200
2201            // Collect vendor overlay packages.
2202            // (Do this before scanning any apps.)
2203            // For security and version matching reason, only consider
2204            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2205            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2206            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2207                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2208
2209            // Find base frameworks (resource packages without code).
2210            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2211                    | PackageParser.PARSE_IS_SYSTEM_DIR
2212                    | PackageParser.PARSE_IS_PRIVILEGED,
2213                    scanFlags | SCAN_NO_DEX, 0);
2214
2215            // Collected privileged system packages.
2216            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2217            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2218                    | PackageParser.PARSE_IS_SYSTEM_DIR
2219                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2220
2221            // Collect ordinary system packages.
2222            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2223            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2224                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2225
2226            // Collect all vendor packages.
2227            File vendorAppDir = new File("/vendor/app");
2228            try {
2229                vendorAppDir = vendorAppDir.getCanonicalFile();
2230            } catch (IOException e) {
2231                // failed to look up canonical path, continue with original one
2232            }
2233            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2234                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2235
2236            // Collect all OEM packages.
2237            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2238            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2239                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2240
2241            // Prune any system packages that no longer exist.
2242            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2243            if (!mOnlyCore) {
2244                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2245                while (psit.hasNext()) {
2246                    PackageSetting ps = psit.next();
2247
2248                    /*
2249                     * If this is not a system app, it can't be a
2250                     * disable system app.
2251                     */
2252                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2253                        continue;
2254                    }
2255
2256                    /*
2257                     * If the package is scanned, it's not erased.
2258                     */
2259                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2260                    if (scannedPkg != null) {
2261                        /*
2262                         * If the system app is both scanned and in the
2263                         * disabled packages list, then it must have been
2264                         * added via OTA. Remove it from the currently
2265                         * scanned package so the previously user-installed
2266                         * application can be scanned.
2267                         */
2268                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2269                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2270                                    + ps.name + "; removing system app.  Last known codePath="
2271                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2272                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2273                                    + scannedPkg.mVersionCode);
2274                            removePackageLI(scannedPkg, true);
2275                            mExpectingBetter.put(ps.name, ps.codePath);
2276                        }
2277
2278                        continue;
2279                    }
2280
2281                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2282                        psit.remove();
2283                        logCriticalInfo(Log.WARN, "System package " + ps.name
2284                                + " no longer exists; wiping its data");
2285                        removeDataDirsLI(null, ps.name);
2286                    } else {
2287                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2288                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2289                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2290                        }
2291                    }
2292                }
2293            }
2294
2295            //look for any incomplete package installations
2296            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2297            //clean up list
2298            for(int i = 0; i < deletePkgsList.size(); i++) {
2299                //clean up here
2300                cleanupInstallFailedPackage(deletePkgsList.get(i));
2301            }
2302            //delete tmp files
2303            deleteTempPackageFiles();
2304
2305            // Remove any shared userIDs that have no associated packages
2306            mSettings.pruneSharedUsersLPw();
2307
2308            if (!mOnlyCore) {
2309                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2310                        SystemClock.uptimeMillis());
2311                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2312
2313                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2314                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2315
2316                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2317                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2318
2319                /**
2320                 * Remove disable package settings for any updated system
2321                 * apps that were removed via an OTA. If they're not a
2322                 * previously-updated app, remove them completely.
2323                 * Otherwise, just revoke their system-level permissions.
2324                 */
2325                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2326                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2327                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2328
2329                    String msg;
2330                    if (deletedPkg == null) {
2331                        msg = "Updated system package " + deletedAppName
2332                                + " no longer exists; wiping its data";
2333                        removeDataDirsLI(null, deletedAppName);
2334                    } else {
2335                        msg = "Updated system app + " + deletedAppName
2336                                + " no longer present; removing system privileges for "
2337                                + deletedAppName;
2338
2339                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2340
2341                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2342                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2343                    }
2344                    logCriticalInfo(Log.WARN, msg);
2345                }
2346
2347                /**
2348                 * Make sure all system apps that we expected to appear on
2349                 * the userdata partition actually showed up. If they never
2350                 * appeared, crawl back and revive the system version.
2351                 */
2352                for (int i = 0; i < mExpectingBetter.size(); i++) {
2353                    final String packageName = mExpectingBetter.keyAt(i);
2354                    if (!mPackages.containsKey(packageName)) {
2355                        final File scanFile = mExpectingBetter.valueAt(i);
2356
2357                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2358                                + " but never showed up; reverting to system");
2359
2360                        final int reparseFlags;
2361                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2362                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2363                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2364                                    | PackageParser.PARSE_IS_PRIVILEGED;
2365                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2366                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2367                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2368                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2369                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2370                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2371                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2372                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2373                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2374                        } else {
2375                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2376                            continue;
2377                        }
2378
2379                        mSettings.enableSystemPackageLPw(packageName);
2380
2381                        try {
2382                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2383                        } catch (PackageManagerException e) {
2384                            Slog.e(TAG, "Failed to parse original system package: "
2385                                    + e.getMessage());
2386                        }
2387                    }
2388                }
2389            }
2390            mExpectingBetter.clear();
2391
2392            // Now that we know all of the shared libraries, update all clients to have
2393            // the correct library paths.
2394            updateAllSharedLibrariesLPw();
2395
2396            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2397                // NOTE: We ignore potential failures here during a system scan (like
2398                // the rest of the commands above) because there's precious little we
2399                // can do about it. A settings error is reported, though.
2400                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2401                        false /* boot complete */);
2402            }
2403
2404            // Now that we know all the packages we are keeping,
2405            // read and update their last usage times.
2406            mPackageUsage.readLP();
2407
2408            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2409                    SystemClock.uptimeMillis());
2410            Slog.i(TAG, "Time to scan packages: "
2411                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2412                    + " seconds");
2413
2414            // If the platform SDK has changed since the last time we booted,
2415            // we need to re-grant app permission to catch any new ones that
2416            // appear.  This is really a hack, and means that apps can in some
2417            // cases get permissions that the user didn't initially explicitly
2418            // allow...  it would be nice to have some better way to handle
2419            // this situation.
2420            int updateFlags = UPDATE_PERMISSIONS_ALL;
2421            if (ver.sdkVersion != mSdkVersion) {
2422                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2423                        + mSdkVersion + "; regranting permissions for internal storage");
2424                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2425            }
2426            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2427            ver.sdkVersion = mSdkVersion;
2428
2429            // If this is the first boot or an update from pre-M, and it is a normal
2430            // boot, then we need to initialize the default preferred apps across
2431            // all defined users.
2432            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2433                for (UserInfo user : sUserManager.getUsers(true)) {
2434                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2435                    applyFactoryDefaultBrowserLPw(user.id);
2436                    primeDomainVerificationsLPw(user.id);
2437                }
2438            }
2439
2440            // Prepare storage for system user really early during boot,
2441            // since core system apps like SettingsProvider and SystemUI
2442            // can't wait for user to start
2443            final int storageFlags;
2444            if (StorageManager.isFileBasedEncryptionEnabled()) {
2445                storageFlags = StorageManager.FLAG_STORAGE_DE;
2446            } else {
2447                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2448            }
2449            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2450                    storageFlags);
2451
2452            if (!StorageManager.isFileBasedEncryptionEnabled()
2453                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2454                // When upgrading a non-FBE device, we might need to shuffle
2455                // around the default storage location of system apps
2456                final List<UserInfo> users = sUserManager.getUsers(true);
2457                for (PackageSetting ps : mSettings.mPackages.values()) {
2458                    if (ps.pkg == null || !ps.isSystem()) continue;
2459                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2460                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2461                    for (UserInfo user : users) {
2462                        if (ps.getInstalled(user.id)) {
2463                            try {
2464                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2465                                        ps.name, user.id, storageTarget);
2466                            } catch (InstallerException e) {
2467                                logCriticalInfo(Log.WARN,
2468                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2469                            }
2470                            // We may have just shuffled around app data
2471                            // directories, so prepare it one more time
2472                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2473                                    storageFlags, ps.pkg, false);
2474                        }
2475                    }
2476                }
2477            }
2478
2479            // If this is first boot after an OTA, and a normal boot, then
2480            // we need to clear code cache directories.
2481            if (mIsUpgrade && !onlyCore) {
2482                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2483                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2484                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2485                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2486                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2487                    }
2488                }
2489                ver.fingerprint = Build.FINGERPRINT;
2490            }
2491
2492            checkDefaultBrowser();
2493
2494            // clear only after permissions and other defaults have been updated
2495            mExistingSystemPackages.clear();
2496            mPromoteSystemApps = false;
2497
2498            // All the changes are done during package scanning.
2499            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2500
2501            // can downgrade to reader
2502            mSettings.writeLPr();
2503
2504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2505                    SystemClock.uptimeMillis());
2506
2507            if (!mOnlyCore) {
2508                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2509                mRequiredInstallerPackage = getRequiredInstallerLPr();
2510                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2511                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2512                        mIntentFilterVerifierComponent);
2513            } else {
2514                mRequiredVerifierPackage = null;
2515                mRequiredInstallerPackage = null;
2516                mIntentFilterVerifierComponent = null;
2517                mIntentFilterVerifier = null;
2518            }
2519
2520            mInstallerService = new PackageInstallerService(context, this);
2521
2522            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2523            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2524            // both the installer and resolver must be present to enable ephemeral
2525            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2526                if (DEBUG_EPHEMERAL) {
2527                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2528                            + " installer:" + ephemeralInstallerComponent);
2529                }
2530                mEphemeralResolverComponent = ephemeralResolverComponent;
2531                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2532                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2533                mEphemeralResolverConnection =
2534                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2535            } else {
2536                if (DEBUG_EPHEMERAL) {
2537                    final String missingComponent =
2538                            (ephemeralResolverComponent == null)
2539                            ? (ephemeralInstallerComponent == null)
2540                                    ? "resolver and installer"
2541                                    : "resolver"
2542                            : "installer";
2543                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2544                }
2545                mEphemeralResolverComponent = null;
2546                mEphemeralInstallerComponent = null;
2547                mEphemeralResolverConnection = null;
2548            }
2549
2550            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2551        } // synchronized (mPackages)
2552        } // synchronized (mInstallLock)
2553
2554        // Now after opening every single application zip, make sure they
2555        // are all flushed.  Not really needed, but keeps things nice and
2556        // tidy.
2557        Runtime.getRuntime().gc();
2558
2559        // The initial scanning above does many calls into installd while
2560        // holding the mPackages lock, but we're mostly interested in yelling
2561        // once we have a booted system.
2562        mInstaller.setWarnIfHeld(mPackages);
2563
2564        // Expose private service for system components to use.
2565        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2566    }
2567
2568    @Override
2569    public boolean isFirstBoot() {
2570        return !mRestoredSettings;
2571    }
2572
2573    @Override
2574    public boolean isOnlyCoreApps() {
2575        return mOnlyCore;
2576    }
2577
2578    @Override
2579    public boolean isUpgrade() {
2580        return mIsUpgrade;
2581    }
2582
2583    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2584        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2585
2586        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2587                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2588        if (matches.size() == 1) {
2589            return matches.get(0).getComponentInfo().packageName;
2590        } else {
2591            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2592            return null;
2593        }
2594    }
2595
2596    private @NonNull String getRequiredInstallerLPr() {
2597        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2598        intent.addCategory(Intent.CATEGORY_DEFAULT);
2599        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2600
2601        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2602                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2603        if (matches.size() == 1) {
2604            return matches.get(0).getComponentInfo().packageName;
2605        } else {
2606            throw new RuntimeException("There must be exactly one installer; found " + matches);
2607        }
2608    }
2609
2610    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2611        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2612
2613        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2614                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2615        ResolveInfo best = null;
2616        final int N = matches.size();
2617        for (int i = 0; i < N; i++) {
2618            final ResolveInfo cur = matches.get(i);
2619            final String packageName = cur.getComponentInfo().packageName;
2620            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2621                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2622                continue;
2623            }
2624
2625            if (best == null || cur.priority > best.priority) {
2626                best = cur;
2627            }
2628        }
2629
2630        if (best != null) {
2631            return best.getComponentInfo().getComponentName();
2632        } else {
2633            throw new RuntimeException("There must be at least one intent filter verifier");
2634        }
2635    }
2636
2637    private @Nullable ComponentName getEphemeralResolverLPr() {
2638        final String[] packageArray =
2639                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2640        if (packageArray.length == 0) {
2641            if (DEBUG_EPHEMERAL) {
2642                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2643            }
2644            return null;
2645        }
2646
2647        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2648        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2649                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2650
2651        final int N = resolvers.size();
2652        if (N == 0) {
2653            if (DEBUG_EPHEMERAL) {
2654                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2655            }
2656            return null;
2657        }
2658
2659        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2660        for (int i = 0; i < N; i++) {
2661            final ResolveInfo info = resolvers.get(i);
2662
2663            if (info.serviceInfo == null) {
2664                continue;
2665            }
2666
2667            final String packageName = info.serviceInfo.packageName;
2668            if (!possiblePackages.contains(packageName)) {
2669                if (DEBUG_EPHEMERAL) {
2670                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2671                            + " pkg: " + packageName + ", info:" + info);
2672                }
2673                continue;
2674            }
2675
2676            if (DEBUG_EPHEMERAL) {
2677                Slog.v(TAG, "Ephemeral resolver found;"
2678                        + " pkg: " + packageName + ", info:" + info);
2679            }
2680            return new ComponentName(packageName, info.serviceInfo.name);
2681        }
2682        if (DEBUG_EPHEMERAL) {
2683            Slog.v(TAG, "Ephemeral resolver NOT found");
2684        }
2685        return null;
2686    }
2687
2688    private @Nullable ComponentName getEphemeralInstallerLPr() {
2689        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2690        intent.addCategory(Intent.CATEGORY_DEFAULT);
2691        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2692
2693        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2694                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2695        if (matches.size() == 0) {
2696            return null;
2697        } else if (matches.size() == 1) {
2698            return matches.get(0).getComponentInfo().getComponentName();
2699        } else {
2700            throw new RuntimeException(
2701                    "There must be at most one ephemeral installer; found " + matches);
2702        }
2703    }
2704
2705    private void primeDomainVerificationsLPw(int userId) {
2706        if (DEBUG_DOMAIN_VERIFICATION) {
2707            Slog.d(TAG, "Priming domain verifications in user " + userId);
2708        }
2709
2710        SystemConfig systemConfig = SystemConfig.getInstance();
2711        ArraySet<String> packages = systemConfig.getLinkedApps();
2712        ArraySet<String> domains = new ArraySet<String>();
2713
2714        for (String packageName : packages) {
2715            PackageParser.Package pkg = mPackages.get(packageName);
2716            if (pkg != null) {
2717                if (!pkg.isSystemApp()) {
2718                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2719                    continue;
2720                }
2721
2722                domains.clear();
2723                for (PackageParser.Activity a : pkg.activities) {
2724                    for (ActivityIntentInfo filter : a.intents) {
2725                        if (hasValidDomains(filter)) {
2726                            domains.addAll(filter.getHostsList());
2727                        }
2728                    }
2729                }
2730
2731                if (domains.size() > 0) {
2732                    if (DEBUG_DOMAIN_VERIFICATION) {
2733                        Slog.v(TAG, "      + " + packageName);
2734                    }
2735                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2736                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2737                    // and then 'always' in the per-user state actually used for intent resolution.
2738                    final IntentFilterVerificationInfo ivi;
2739                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2740                            new ArrayList<String>(domains));
2741                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2742                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2743                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2744                } else {
2745                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2746                            + "' does not handle web links");
2747                }
2748            } else {
2749                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2750            }
2751        }
2752
2753        scheduleWritePackageRestrictionsLocked(userId);
2754        scheduleWriteSettingsLocked();
2755    }
2756
2757    private void applyFactoryDefaultBrowserLPw(int userId) {
2758        // The default browser app's package name is stored in a string resource,
2759        // with a product-specific overlay used for vendor customization.
2760        String browserPkg = mContext.getResources().getString(
2761                com.android.internal.R.string.default_browser);
2762        if (!TextUtils.isEmpty(browserPkg)) {
2763            // non-empty string => required to be a known package
2764            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2765            if (ps == null) {
2766                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2767                browserPkg = null;
2768            } else {
2769                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2770            }
2771        }
2772
2773        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2774        // default.  If there's more than one, just leave everything alone.
2775        if (browserPkg == null) {
2776            calculateDefaultBrowserLPw(userId);
2777        }
2778    }
2779
2780    private void calculateDefaultBrowserLPw(int userId) {
2781        List<String> allBrowsers = resolveAllBrowserApps(userId);
2782        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2783        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2784    }
2785
2786    private List<String> resolveAllBrowserApps(int userId) {
2787        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2788        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2789                PackageManager.MATCH_ALL, userId);
2790
2791        final int count = list.size();
2792        List<String> result = new ArrayList<String>(count);
2793        for (int i=0; i<count; i++) {
2794            ResolveInfo info = list.get(i);
2795            if (info.activityInfo == null
2796                    || !info.handleAllWebDataURI
2797                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2798                    || result.contains(info.activityInfo.packageName)) {
2799                continue;
2800            }
2801            result.add(info.activityInfo.packageName);
2802        }
2803
2804        return result;
2805    }
2806
2807    private boolean packageIsBrowser(String packageName, int userId) {
2808        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2809                PackageManager.MATCH_ALL, userId);
2810        final int N = list.size();
2811        for (int i = 0; i < N; i++) {
2812            ResolveInfo info = list.get(i);
2813            if (packageName.equals(info.activityInfo.packageName)) {
2814                return true;
2815            }
2816        }
2817        return false;
2818    }
2819
2820    private void checkDefaultBrowser() {
2821        final int myUserId = UserHandle.myUserId();
2822        final String packageName = getDefaultBrowserPackageName(myUserId);
2823        if (packageName != null) {
2824            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2825            if (info == null) {
2826                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2827                synchronized (mPackages) {
2828                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2829                }
2830            }
2831        }
2832    }
2833
2834    @Override
2835    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2836            throws RemoteException {
2837        try {
2838            return super.onTransact(code, data, reply, flags);
2839        } catch (RuntimeException e) {
2840            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2841                Slog.wtf(TAG, "Package Manager Crash", e);
2842            }
2843            throw e;
2844        }
2845    }
2846
2847    void cleanupInstallFailedPackage(PackageSetting ps) {
2848        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2849
2850        removeDataDirsLI(ps.volumeUuid, ps.name);
2851        if (ps.codePath != null) {
2852            removeCodePathLI(ps.codePath);
2853        }
2854        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2855            if (ps.resourcePath.isDirectory()) {
2856                FileUtils.deleteContents(ps.resourcePath);
2857            }
2858            ps.resourcePath.delete();
2859        }
2860        mSettings.removePackageLPw(ps.name);
2861    }
2862
2863    static int[] appendInts(int[] cur, int[] add) {
2864        if (add == null) return cur;
2865        if (cur == null) return add;
2866        final int N = add.length;
2867        for (int i=0; i<N; i++) {
2868            cur = appendInt(cur, add[i]);
2869        }
2870        return cur;
2871    }
2872
2873    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2874        if (!sUserManager.exists(userId)) return null;
2875        final PackageSetting ps = (PackageSetting) p.mExtras;
2876        if (ps == null) {
2877            return null;
2878        }
2879
2880        final PermissionsState permissionsState = ps.getPermissionsState();
2881
2882        final int[] gids = permissionsState.computeGids(userId);
2883        final Set<String> permissions = permissionsState.getPermissions(userId);
2884        final PackageUserState state = ps.readUserState(userId);
2885
2886        return PackageParser.generatePackageInfo(p, gids, flags,
2887                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2888    }
2889
2890    @Override
2891    public void checkPackageStartable(String packageName, int userId) {
2892        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2893
2894        synchronized (mPackages) {
2895            final PackageSetting ps = mSettings.mPackages.get(packageName);
2896            if (ps == null) {
2897                throw new SecurityException("Package " + packageName + " was not found!");
2898            }
2899
2900            if (mSafeMode && !ps.isSystem()) {
2901                throw new SecurityException("Package " + packageName + " not a system app!");
2902            }
2903
2904            if (ps.frozen) {
2905                throw new SecurityException("Package " + packageName + " is currently frozen!");
2906            }
2907
2908            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2909                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2910                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2911            }
2912        }
2913    }
2914
2915    @Override
2916    public boolean isPackageAvailable(String packageName, int userId) {
2917        if (!sUserManager.exists(userId)) return false;
2918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2919        synchronized (mPackages) {
2920            PackageParser.Package p = mPackages.get(packageName);
2921            if (p != null) {
2922                final PackageSetting ps = (PackageSetting) p.mExtras;
2923                if (ps != null) {
2924                    final PackageUserState state = ps.readUserState(userId);
2925                    if (state != null) {
2926                        return PackageParser.isAvailable(state);
2927                    }
2928                }
2929            }
2930        }
2931        return false;
2932    }
2933
2934    @Override
2935    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2936        if (!sUserManager.exists(userId)) return null;
2937        flags = updateFlagsForPackage(flags, userId, packageName);
2938        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2939        // reader
2940        synchronized (mPackages) {
2941            PackageParser.Package p = mPackages.get(packageName);
2942            if (DEBUG_PACKAGE_INFO)
2943                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2944            if (p != null) {
2945                return generatePackageInfo(p, flags, userId);
2946            }
2947            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2948                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2949            }
2950        }
2951        return null;
2952    }
2953
2954    @Override
2955    public String[] currentToCanonicalPackageNames(String[] names) {
2956        String[] out = new String[names.length];
2957        // reader
2958        synchronized (mPackages) {
2959            for (int i=names.length-1; i>=0; i--) {
2960                PackageSetting ps = mSettings.mPackages.get(names[i]);
2961                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2962            }
2963        }
2964        return out;
2965    }
2966
2967    @Override
2968    public String[] canonicalToCurrentPackageNames(String[] names) {
2969        String[] out = new String[names.length];
2970        // reader
2971        synchronized (mPackages) {
2972            for (int i=names.length-1; i>=0; i--) {
2973                String cur = mSettings.mRenamedPackages.get(names[i]);
2974                out[i] = cur != null ? cur : names[i];
2975            }
2976        }
2977        return out;
2978    }
2979
2980    @Override
2981    public int getPackageUid(String packageName, int flags, int userId) {
2982        if (!sUserManager.exists(userId)) return -1;
2983        flags = updateFlagsForPackage(flags, userId, packageName);
2984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2985
2986        // reader
2987        synchronized (mPackages) {
2988            final PackageParser.Package p = mPackages.get(packageName);
2989            if (p != null && p.isMatch(flags)) {
2990                return UserHandle.getUid(userId, p.applicationInfo.uid);
2991            }
2992            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2993                final PackageSetting ps = mSettings.mPackages.get(packageName);
2994                if (ps != null && ps.isMatch(flags)) {
2995                    return UserHandle.getUid(userId, ps.appId);
2996                }
2997            }
2998        }
2999
3000        return -1;
3001    }
3002
3003    @Override
3004    public int[] getPackageGids(String packageName, int flags, int userId) {
3005        if (!sUserManager.exists(userId)) return null;
3006        flags = updateFlagsForPackage(flags, userId, packageName);
3007        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3008                "getPackageGids");
3009
3010        // reader
3011        synchronized (mPackages) {
3012            final PackageParser.Package p = mPackages.get(packageName);
3013            if (p != null && p.isMatch(flags)) {
3014                PackageSetting ps = (PackageSetting) p.mExtras;
3015                return ps.getPermissionsState().computeGids(userId);
3016            }
3017            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3018                final PackageSetting ps = mSettings.mPackages.get(packageName);
3019                if (ps != null && ps.isMatch(flags)) {
3020                    return ps.getPermissionsState().computeGids(userId);
3021                }
3022            }
3023        }
3024
3025        return null;
3026    }
3027
3028    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3029        if (bp.perm != null) {
3030            return PackageParser.generatePermissionInfo(bp.perm, flags);
3031        }
3032        PermissionInfo pi = new PermissionInfo();
3033        pi.name = bp.name;
3034        pi.packageName = bp.sourcePackage;
3035        pi.nonLocalizedLabel = bp.name;
3036        pi.protectionLevel = bp.protectionLevel;
3037        return pi;
3038    }
3039
3040    @Override
3041    public PermissionInfo getPermissionInfo(String name, int flags) {
3042        // reader
3043        synchronized (mPackages) {
3044            final BasePermission p = mSettings.mPermissions.get(name);
3045            if (p != null) {
3046                return generatePermissionInfo(p, flags);
3047            }
3048            return null;
3049        }
3050    }
3051
3052    @Override
3053    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3054        // reader
3055        synchronized (mPackages) {
3056            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3057            for (BasePermission p : mSettings.mPermissions.values()) {
3058                if (group == null) {
3059                    if (p.perm == null || p.perm.info.group == null) {
3060                        out.add(generatePermissionInfo(p, flags));
3061                    }
3062                } else {
3063                    if (p.perm != null && group.equals(p.perm.info.group)) {
3064                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3065                    }
3066                }
3067            }
3068
3069            if (out.size() > 0) {
3070                return out;
3071            }
3072            return mPermissionGroups.containsKey(group) ? out : null;
3073        }
3074    }
3075
3076    @Override
3077    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3078        // reader
3079        synchronized (mPackages) {
3080            return PackageParser.generatePermissionGroupInfo(
3081                    mPermissionGroups.get(name), flags);
3082        }
3083    }
3084
3085    @Override
3086    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3087        // reader
3088        synchronized (mPackages) {
3089            final int N = mPermissionGroups.size();
3090            ArrayList<PermissionGroupInfo> out
3091                    = new ArrayList<PermissionGroupInfo>(N);
3092            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3093                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3094            }
3095            return out;
3096        }
3097    }
3098
3099    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3100            int userId) {
3101        if (!sUserManager.exists(userId)) return null;
3102        PackageSetting ps = mSettings.mPackages.get(packageName);
3103        if (ps != null) {
3104            if (ps.pkg == null) {
3105                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3106                        flags, userId);
3107                if (pInfo != null) {
3108                    return pInfo.applicationInfo;
3109                }
3110                return null;
3111            }
3112            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3113                    ps.readUserState(userId), userId);
3114        }
3115        return null;
3116    }
3117
3118    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3119            int userId) {
3120        if (!sUserManager.exists(userId)) return null;
3121        PackageSetting ps = mSettings.mPackages.get(packageName);
3122        if (ps != null) {
3123            PackageParser.Package pkg = ps.pkg;
3124            if (pkg == null) {
3125                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3126                    return null;
3127                }
3128                // Only data remains, so we aren't worried about code paths
3129                pkg = new PackageParser.Package(packageName);
3130                pkg.applicationInfo.packageName = packageName;
3131                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3132                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3133                pkg.applicationInfo.uid = ps.appId;
3134                pkg.applicationInfo.initForUser(userId);
3135                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3136                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3137            }
3138            return generatePackageInfo(pkg, flags, userId);
3139        }
3140        return null;
3141    }
3142
3143    @Override
3144    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3145        if (!sUserManager.exists(userId)) return null;
3146        flags = updateFlagsForApplication(flags, userId, packageName);
3147        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3148        // writer
3149        synchronized (mPackages) {
3150            PackageParser.Package p = mPackages.get(packageName);
3151            if (DEBUG_PACKAGE_INFO) Log.v(
3152                    TAG, "getApplicationInfo " + packageName
3153                    + ": " + p);
3154            if (p != null) {
3155                PackageSetting ps = mSettings.mPackages.get(packageName);
3156                if (ps == null) return null;
3157                // Note: isEnabledLP() does not apply here - always return info
3158                return PackageParser.generateApplicationInfo(
3159                        p, flags, ps.readUserState(userId), userId);
3160            }
3161            if ("android".equals(packageName)||"system".equals(packageName)) {
3162                return mAndroidApplication;
3163            }
3164            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3165                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3166            }
3167        }
3168        return null;
3169    }
3170
3171    @Override
3172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3173            final IPackageDataObserver observer) {
3174        mContext.enforceCallingOrSelfPermission(
3175                android.Manifest.permission.CLEAR_APP_CACHE, null);
3176        // Queue up an async operation since clearing cache may take a little while.
3177        mHandler.post(new Runnable() {
3178            public void run() {
3179                mHandler.removeCallbacks(this);
3180                boolean success = true;
3181                synchronized (mInstallLock) {
3182                    try {
3183                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3184                    } catch (InstallerException e) {
3185                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3186                        success = false;
3187                    }
3188                }
3189                if (observer != null) {
3190                    try {
3191                        observer.onRemoveCompleted(null, success);
3192                    } catch (RemoteException e) {
3193                        Slog.w(TAG, "RemoveException when invoking call back");
3194                    }
3195                }
3196            }
3197        });
3198    }
3199
3200    @Override
3201    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3202            final IntentSender pi) {
3203        mContext.enforceCallingOrSelfPermission(
3204                android.Manifest.permission.CLEAR_APP_CACHE, null);
3205        // Queue up an async operation since clearing cache may take a little while.
3206        mHandler.post(new Runnable() {
3207            public void run() {
3208                mHandler.removeCallbacks(this);
3209                boolean success = true;
3210                synchronized (mInstallLock) {
3211                    try {
3212                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3213                    } catch (InstallerException e) {
3214                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3215                        success = false;
3216                    }
3217                }
3218                if(pi != null) {
3219                    try {
3220                        // Callback via pending intent
3221                        int code = success ? 1 : 0;
3222                        pi.sendIntent(null, code, null,
3223                                null, null);
3224                    } catch (SendIntentException e1) {
3225                        Slog.i(TAG, "Failed to send pending intent");
3226                    }
3227                }
3228            }
3229        });
3230    }
3231
3232    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3233        synchronized (mInstallLock) {
3234            try {
3235                mInstaller.freeCache(volumeUuid, freeStorageSize);
3236            } catch (InstallerException e) {
3237                throw new IOException("Failed to free enough space", e);
3238            }
3239        }
3240    }
3241
3242    /**
3243     * Return if the user key is currently unlocked.
3244     */
3245    private boolean isUserKeyUnlocked(int userId) {
3246        if (StorageManager.isFileBasedEncryptionEnabled()) {
3247            final IMountService mount = IMountService.Stub
3248                    .asInterface(ServiceManager.getService("mount"));
3249            if (mount == null) {
3250                Slog.w(TAG, "Early during boot, assuming locked");
3251                return false;
3252            }
3253            final long token = Binder.clearCallingIdentity();
3254            try {
3255                return mount.isUserKeyUnlocked(userId);
3256            } catch (RemoteException e) {
3257                throw e.rethrowAsRuntimeException();
3258            } finally {
3259                Binder.restoreCallingIdentity(token);
3260            }
3261        } else {
3262            return true;
3263        }
3264    }
3265
3266    /**
3267     * Update given flags based on encryption status of current user.
3268     */
3269    private int updateFlags(int flags, int userId) {
3270        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3271                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3272            // Caller expressed an explicit opinion about what encryption
3273            // aware/unaware components they want to see, so fall through and
3274            // give them what they want
3275        } else {
3276            // Caller expressed no opinion, so match based on user state
3277            if (isUserKeyUnlocked(userId)) {
3278                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3279            } else {
3280                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3281            }
3282        }
3283        return flags;
3284    }
3285
3286    /**
3287     * Update given flags when being used to request {@link PackageInfo}.
3288     */
3289    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3290        boolean triaged = true;
3291        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3292                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3293            // Caller is asking for component details, so they'd better be
3294            // asking for specific encryption matching behavior, or be triaged
3295            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3296                    | PackageManager.MATCH_ENCRYPTION_AWARE
3297                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3298                triaged = false;
3299            }
3300        }
3301        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3302                | PackageManager.MATCH_SYSTEM_ONLY
3303                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3304            triaged = false;
3305        }
3306        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3307            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3308                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3309        }
3310        return updateFlags(flags, userId);
3311    }
3312
3313    /**
3314     * Update given flags when being used to request {@link ApplicationInfo}.
3315     */
3316    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3317        return updateFlagsForPackage(flags, userId, cookie);
3318    }
3319
3320    /**
3321     * Update given flags when being used to request {@link ComponentInfo}.
3322     */
3323    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3324        if (cookie instanceof Intent) {
3325            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3326                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3327            }
3328        }
3329
3330        boolean triaged = true;
3331        // Caller is asking for component details, so they'd better be
3332        // asking for specific encryption matching behavior, or be triaged
3333        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3334                | PackageManager.MATCH_ENCRYPTION_AWARE
3335                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3336            triaged = false;
3337        }
3338        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3339            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3340                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3341        }
3342
3343        return updateFlags(flags, userId);
3344    }
3345
3346    /**
3347     * Update given flags when being used to request {@link ResolveInfo}.
3348     */
3349    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3350        // Safe mode means we shouldn't match any third-party components
3351        if (mSafeMode) {
3352            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3353        }
3354
3355        return updateFlagsForComponent(flags, userId, cookie);
3356    }
3357
3358    @Override
3359    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3360        if (!sUserManager.exists(userId)) return null;
3361        flags = updateFlagsForComponent(flags, userId, component);
3362        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3363        synchronized (mPackages) {
3364            PackageParser.Activity a = mActivities.mActivities.get(component);
3365
3366            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3367            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3368                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3369                if (ps == null) return null;
3370                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3371                        userId);
3372            }
3373            if (mResolveComponentName.equals(component)) {
3374                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3375                        new PackageUserState(), userId);
3376            }
3377        }
3378        return null;
3379    }
3380
3381    @Override
3382    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3383            String resolvedType) {
3384        synchronized (mPackages) {
3385            if (component.equals(mResolveComponentName)) {
3386                // The resolver supports EVERYTHING!
3387                return true;
3388            }
3389            PackageParser.Activity a = mActivities.mActivities.get(component);
3390            if (a == null) {
3391                return false;
3392            }
3393            for (int i=0; i<a.intents.size(); i++) {
3394                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3395                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3396                    return true;
3397                }
3398            }
3399            return false;
3400        }
3401    }
3402
3403    @Override
3404    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3405        if (!sUserManager.exists(userId)) return null;
3406        flags = updateFlagsForComponent(flags, userId, component);
3407        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3408        synchronized (mPackages) {
3409            PackageParser.Activity a = mReceivers.mActivities.get(component);
3410            if (DEBUG_PACKAGE_INFO) Log.v(
3411                TAG, "getReceiverInfo " + component + ": " + a);
3412            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3413                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3414                if (ps == null) return null;
3415                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3416                        userId);
3417            }
3418        }
3419        return null;
3420    }
3421
3422    @Override
3423    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3424        if (!sUserManager.exists(userId)) return null;
3425        flags = updateFlagsForComponent(flags, userId, component);
3426        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3427        synchronized (mPackages) {
3428            PackageParser.Service s = mServices.mServices.get(component);
3429            if (DEBUG_PACKAGE_INFO) Log.v(
3430                TAG, "getServiceInfo " + component + ": " + s);
3431            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3432                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3433                if (ps == null) return null;
3434                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3435                        userId);
3436            }
3437        }
3438        return null;
3439    }
3440
3441    @Override
3442    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3443        if (!sUserManager.exists(userId)) return null;
3444        flags = updateFlagsForComponent(flags, userId, component);
3445        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3446        synchronized (mPackages) {
3447            PackageParser.Provider p = mProviders.mProviders.get(component);
3448            if (DEBUG_PACKAGE_INFO) Log.v(
3449                TAG, "getProviderInfo " + component + ": " + p);
3450            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3451                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3452                if (ps == null) return null;
3453                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3454                        userId);
3455            }
3456        }
3457        return null;
3458    }
3459
3460    @Override
3461    public String[] getSystemSharedLibraryNames() {
3462        Set<String> libSet;
3463        synchronized (mPackages) {
3464            libSet = mSharedLibraries.keySet();
3465            int size = libSet.size();
3466            if (size > 0) {
3467                String[] libs = new String[size];
3468                libSet.toArray(libs);
3469                return libs;
3470            }
3471        }
3472        return null;
3473    }
3474
3475    @Override
3476    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3477        synchronized (mPackages) {
3478            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3479                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3480            if (libraryEntry != null) {
3481                return libraryEntry.apk;
3482            }
3483        }
3484        return null;
3485    }
3486
3487    @Override
3488    public FeatureInfo[] getSystemAvailableFeatures() {
3489        Collection<FeatureInfo> featSet;
3490        synchronized (mPackages) {
3491            featSet = mAvailableFeatures.values();
3492            int size = featSet.size();
3493            if (size > 0) {
3494                FeatureInfo[] features = new FeatureInfo[size+1];
3495                featSet.toArray(features);
3496                FeatureInfo fi = new FeatureInfo();
3497                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3498                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3499                features[size] = fi;
3500                return features;
3501            }
3502        }
3503        return null;
3504    }
3505
3506    @Override
3507    public boolean hasSystemFeature(String name, int version) {
3508        synchronized (mPackages) {
3509            final FeatureInfo feat = mAvailableFeatures.get(name);
3510            if (feat == null) {
3511                return false;
3512            } else {
3513                return feat.version >= version;
3514            }
3515        }
3516    }
3517
3518    @Override
3519    public int checkPermission(String permName, String pkgName, int userId) {
3520        if (!sUserManager.exists(userId)) {
3521            return PackageManager.PERMISSION_DENIED;
3522        }
3523
3524        synchronized (mPackages) {
3525            final PackageParser.Package p = mPackages.get(pkgName);
3526            if (p != null && p.mExtras != null) {
3527                final PackageSetting ps = (PackageSetting) p.mExtras;
3528                final PermissionsState permissionsState = ps.getPermissionsState();
3529                if (permissionsState.hasPermission(permName, userId)) {
3530                    return PackageManager.PERMISSION_GRANTED;
3531                }
3532                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3533                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3534                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3535                    return PackageManager.PERMISSION_GRANTED;
3536                }
3537            }
3538        }
3539
3540        return PackageManager.PERMISSION_DENIED;
3541    }
3542
3543    @Override
3544    public int checkUidPermission(String permName, int uid) {
3545        final int userId = UserHandle.getUserId(uid);
3546
3547        if (!sUserManager.exists(userId)) {
3548            return PackageManager.PERMISSION_DENIED;
3549        }
3550
3551        synchronized (mPackages) {
3552            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3553            if (obj != null) {
3554                final SettingBase ps = (SettingBase) obj;
3555                final PermissionsState permissionsState = ps.getPermissionsState();
3556                if (permissionsState.hasPermission(permName, userId)) {
3557                    return PackageManager.PERMISSION_GRANTED;
3558                }
3559                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3560                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3561                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3562                    return PackageManager.PERMISSION_GRANTED;
3563                }
3564            } else {
3565                ArraySet<String> perms = mSystemPermissions.get(uid);
3566                if (perms != null) {
3567                    if (perms.contains(permName)) {
3568                        return PackageManager.PERMISSION_GRANTED;
3569                    }
3570                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3571                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3572                        return PackageManager.PERMISSION_GRANTED;
3573                    }
3574                }
3575            }
3576        }
3577
3578        return PackageManager.PERMISSION_DENIED;
3579    }
3580
3581    @Override
3582    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3583        if (UserHandle.getCallingUserId() != userId) {
3584            mContext.enforceCallingPermission(
3585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3586                    "isPermissionRevokedByPolicy for user " + userId);
3587        }
3588
3589        if (checkPermission(permission, packageName, userId)
3590                == PackageManager.PERMISSION_GRANTED) {
3591            return false;
3592        }
3593
3594        final long identity = Binder.clearCallingIdentity();
3595        try {
3596            final int flags = getPermissionFlags(permission, packageName, userId);
3597            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3598        } finally {
3599            Binder.restoreCallingIdentity(identity);
3600        }
3601    }
3602
3603    @Override
3604    public String getPermissionControllerPackageName() {
3605        synchronized (mPackages) {
3606            return mRequiredInstallerPackage;
3607        }
3608    }
3609
3610    /**
3611     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3612     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3613     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3614     * @param message the message to log on security exception
3615     */
3616    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3617            boolean checkShell, String message) {
3618        if (userId < 0) {
3619            throw new IllegalArgumentException("Invalid userId " + userId);
3620        }
3621        if (checkShell) {
3622            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3623        }
3624        if (userId == UserHandle.getUserId(callingUid)) return;
3625        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3626            if (requireFullPermission) {
3627                mContext.enforceCallingOrSelfPermission(
3628                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3629            } else {
3630                try {
3631                    mContext.enforceCallingOrSelfPermission(
3632                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3633                } catch (SecurityException se) {
3634                    mContext.enforceCallingOrSelfPermission(
3635                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3636                }
3637            }
3638        }
3639    }
3640
3641    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3642        if (callingUid == Process.SHELL_UID) {
3643            if (userHandle >= 0
3644                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3645                throw new SecurityException("Shell does not have permission to access user "
3646                        + userHandle);
3647            } else if (userHandle < 0) {
3648                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3649                        + Debug.getCallers(3));
3650            }
3651        }
3652    }
3653
3654    private BasePermission findPermissionTreeLP(String permName) {
3655        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3656            if (permName.startsWith(bp.name) &&
3657                    permName.length() > bp.name.length() &&
3658                    permName.charAt(bp.name.length()) == '.') {
3659                return bp;
3660            }
3661        }
3662        return null;
3663    }
3664
3665    private BasePermission checkPermissionTreeLP(String permName) {
3666        if (permName != null) {
3667            BasePermission bp = findPermissionTreeLP(permName);
3668            if (bp != null) {
3669                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3670                    return bp;
3671                }
3672                throw new SecurityException("Calling uid "
3673                        + Binder.getCallingUid()
3674                        + " is not allowed to add to permission tree "
3675                        + bp.name + " owned by uid " + bp.uid);
3676            }
3677        }
3678        throw new SecurityException("No permission tree found for " + permName);
3679    }
3680
3681    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3682        if (s1 == null) {
3683            return s2 == null;
3684        }
3685        if (s2 == null) {
3686            return false;
3687        }
3688        if (s1.getClass() != s2.getClass()) {
3689            return false;
3690        }
3691        return s1.equals(s2);
3692    }
3693
3694    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3695        if (pi1.icon != pi2.icon) return false;
3696        if (pi1.logo != pi2.logo) return false;
3697        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3698        if (!compareStrings(pi1.name, pi2.name)) return false;
3699        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3700        // We'll take care of setting this one.
3701        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3702        // These are not currently stored in settings.
3703        //if (!compareStrings(pi1.group, pi2.group)) return false;
3704        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3705        //if (pi1.labelRes != pi2.labelRes) return false;
3706        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3707        return true;
3708    }
3709
3710    int permissionInfoFootprint(PermissionInfo info) {
3711        int size = info.name.length();
3712        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3713        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3714        return size;
3715    }
3716
3717    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3718        int size = 0;
3719        for (BasePermission perm : mSettings.mPermissions.values()) {
3720            if (perm.uid == tree.uid) {
3721                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3722            }
3723        }
3724        return size;
3725    }
3726
3727    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3728        // We calculate the max size of permissions defined by this uid and throw
3729        // if that plus the size of 'info' would exceed our stated maximum.
3730        if (tree.uid != Process.SYSTEM_UID) {
3731            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3732            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3733                throw new SecurityException("Permission tree size cap exceeded");
3734            }
3735        }
3736    }
3737
3738    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3739        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3740            throw new SecurityException("Label must be specified in permission");
3741        }
3742        BasePermission tree = checkPermissionTreeLP(info.name);
3743        BasePermission bp = mSettings.mPermissions.get(info.name);
3744        boolean added = bp == null;
3745        boolean changed = true;
3746        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3747        if (added) {
3748            enforcePermissionCapLocked(info, tree);
3749            bp = new BasePermission(info.name, tree.sourcePackage,
3750                    BasePermission.TYPE_DYNAMIC);
3751        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3752            throw new SecurityException(
3753                    "Not allowed to modify non-dynamic permission "
3754                    + info.name);
3755        } else {
3756            if (bp.protectionLevel == fixedLevel
3757                    && bp.perm.owner.equals(tree.perm.owner)
3758                    && bp.uid == tree.uid
3759                    && comparePermissionInfos(bp.perm.info, info)) {
3760                changed = false;
3761            }
3762        }
3763        bp.protectionLevel = fixedLevel;
3764        info = new PermissionInfo(info);
3765        info.protectionLevel = fixedLevel;
3766        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3767        bp.perm.info.packageName = tree.perm.info.packageName;
3768        bp.uid = tree.uid;
3769        if (added) {
3770            mSettings.mPermissions.put(info.name, bp);
3771        }
3772        if (changed) {
3773            if (!async) {
3774                mSettings.writeLPr();
3775            } else {
3776                scheduleWriteSettingsLocked();
3777            }
3778        }
3779        return added;
3780    }
3781
3782    @Override
3783    public boolean addPermission(PermissionInfo info) {
3784        synchronized (mPackages) {
3785            return addPermissionLocked(info, false);
3786        }
3787    }
3788
3789    @Override
3790    public boolean addPermissionAsync(PermissionInfo info) {
3791        synchronized (mPackages) {
3792            return addPermissionLocked(info, true);
3793        }
3794    }
3795
3796    @Override
3797    public void removePermission(String name) {
3798        synchronized (mPackages) {
3799            checkPermissionTreeLP(name);
3800            BasePermission bp = mSettings.mPermissions.get(name);
3801            if (bp != null) {
3802                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3803                    throw new SecurityException(
3804                            "Not allowed to modify non-dynamic permission "
3805                            + name);
3806                }
3807                mSettings.mPermissions.remove(name);
3808                mSettings.writeLPr();
3809            }
3810        }
3811    }
3812
3813    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3814            BasePermission bp) {
3815        int index = pkg.requestedPermissions.indexOf(bp.name);
3816        if (index == -1) {
3817            throw new SecurityException("Package " + pkg.packageName
3818                    + " has not requested permission " + bp.name);
3819        }
3820        if (!bp.isRuntime() && !bp.isDevelopment()) {
3821            throw new SecurityException("Permission " + bp.name
3822                    + " is not a changeable permission type");
3823        }
3824    }
3825
3826    @Override
3827    public void grantRuntimePermission(String packageName, String name, final int userId) {
3828        if (!sUserManager.exists(userId)) {
3829            Log.e(TAG, "No such user:" + userId);
3830            return;
3831        }
3832
3833        mContext.enforceCallingOrSelfPermission(
3834                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3835                "grantRuntimePermission");
3836
3837        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3838                "grantRuntimePermission");
3839
3840        final int uid;
3841        final SettingBase sb;
3842
3843        synchronized (mPackages) {
3844            final PackageParser.Package pkg = mPackages.get(packageName);
3845            if (pkg == null) {
3846                throw new IllegalArgumentException("Unknown package: " + packageName);
3847            }
3848
3849            final BasePermission bp = mSettings.mPermissions.get(name);
3850            if (bp == null) {
3851                throw new IllegalArgumentException("Unknown permission: " + name);
3852            }
3853
3854            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3855
3856            // If a permission review is required for legacy apps we represent
3857            // their permissions as always granted runtime ones since we need
3858            // to keep the review required permission flag per user while an
3859            // install permission's state is shared across all users.
3860            if (Build.PERMISSIONS_REVIEW_REQUIRED
3861                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3862                    && bp.isRuntime()) {
3863                return;
3864            }
3865
3866            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3867            sb = (SettingBase) pkg.mExtras;
3868            if (sb == null) {
3869                throw new IllegalArgumentException("Unknown package: " + packageName);
3870            }
3871
3872            final PermissionsState permissionsState = sb.getPermissionsState();
3873
3874            final int flags = permissionsState.getPermissionFlags(name, userId);
3875            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3876                throw new SecurityException("Cannot grant system fixed permission "
3877                        + name + " for package " + packageName);
3878            }
3879
3880            if (bp.isDevelopment()) {
3881                // Development permissions must be handled specially, since they are not
3882                // normal runtime permissions.  For now they apply to all users.
3883                if (permissionsState.grantInstallPermission(bp) !=
3884                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3885                    scheduleWriteSettingsLocked();
3886                }
3887                return;
3888            }
3889
3890            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3891                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3892                return;
3893            }
3894
3895            final int result = permissionsState.grantRuntimePermission(bp, userId);
3896            switch (result) {
3897                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3898                    return;
3899                }
3900
3901                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3902                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3903                    mHandler.post(new Runnable() {
3904                        @Override
3905                        public void run() {
3906                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3907                        }
3908                    });
3909                }
3910                break;
3911            }
3912
3913            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3914
3915            // Not critical if that is lost - app has to request again.
3916            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3917        }
3918
3919        // Only need to do this if user is initialized. Otherwise it's a new user
3920        // and there are no processes running as the user yet and there's no need
3921        // to make an expensive call to remount processes for the changed permissions.
3922        if (READ_EXTERNAL_STORAGE.equals(name)
3923                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3924            final long token = Binder.clearCallingIdentity();
3925            try {
3926                if (sUserManager.isInitialized(userId)) {
3927                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3928                            MountServiceInternal.class);
3929                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3930                }
3931            } finally {
3932                Binder.restoreCallingIdentity(token);
3933            }
3934        }
3935    }
3936
3937    @Override
3938    public void revokeRuntimePermission(String packageName, String name, int userId) {
3939        if (!sUserManager.exists(userId)) {
3940            Log.e(TAG, "No such user:" + userId);
3941            return;
3942        }
3943
3944        mContext.enforceCallingOrSelfPermission(
3945                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3946                "revokeRuntimePermission");
3947
3948        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3949                "revokeRuntimePermission");
3950
3951        final int appId;
3952
3953        synchronized (mPackages) {
3954            final PackageParser.Package pkg = mPackages.get(packageName);
3955            if (pkg == null) {
3956                throw new IllegalArgumentException("Unknown package: " + packageName);
3957            }
3958
3959            final BasePermission bp = mSettings.mPermissions.get(name);
3960            if (bp == null) {
3961                throw new IllegalArgumentException("Unknown permission: " + name);
3962            }
3963
3964            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3965
3966            // If a permission review is required for legacy apps we represent
3967            // their permissions as always granted runtime ones since we need
3968            // to keep the review required permission flag per user while an
3969            // install permission's state is shared across all users.
3970            if (Build.PERMISSIONS_REVIEW_REQUIRED
3971                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3972                    && bp.isRuntime()) {
3973                return;
3974            }
3975
3976            SettingBase sb = (SettingBase) pkg.mExtras;
3977            if (sb == null) {
3978                throw new IllegalArgumentException("Unknown package: " + packageName);
3979            }
3980
3981            final PermissionsState permissionsState = sb.getPermissionsState();
3982
3983            final int flags = permissionsState.getPermissionFlags(name, userId);
3984            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3985                throw new SecurityException("Cannot revoke system fixed permission "
3986                        + name + " for package " + packageName);
3987            }
3988
3989            if (bp.isDevelopment()) {
3990                // Development permissions must be handled specially, since they are not
3991                // normal runtime permissions.  For now they apply to all users.
3992                if (permissionsState.revokeInstallPermission(bp) !=
3993                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3994                    scheduleWriteSettingsLocked();
3995                }
3996                return;
3997            }
3998
3999            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4000                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4001                return;
4002            }
4003
4004            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4005
4006            // Critical, after this call app should never have the permission.
4007            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4008
4009            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4010        }
4011
4012        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4013    }
4014
4015    @Override
4016    public void resetRuntimePermissions() {
4017        mContext.enforceCallingOrSelfPermission(
4018                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4019                "revokeRuntimePermission");
4020
4021        int callingUid = Binder.getCallingUid();
4022        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4023            mContext.enforceCallingOrSelfPermission(
4024                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4025                    "resetRuntimePermissions");
4026        }
4027
4028        synchronized (mPackages) {
4029            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4030            for (int userId : UserManagerService.getInstance().getUserIds()) {
4031                final int packageCount = mPackages.size();
4032                for (int i = 0; i < packageCount; i++) {
4033                    PackageParser.Package pkg = mPackages.valueAt(i);
4034                    if (!(pkg.mExtras instanceof PackageSetting)) {
4035                        continue;
4036                    }
4037                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4038                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4039                }
4040            }
4041        }
4042    }
4043
4044    @Override
4045    public int getPermissionFlags(String name, String packageName, int userId) {
4046        if (!sUserManager.exists(userId)) {
4047            return 0;
4048        }
4049
4050        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4051
4052        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4053                "getPermissionFlags");
4054
4055        synchronized (mPackages) {
4056            final PackageParser.Package pkg = mPackages.get(packageName);
4057            if (pkg == null) {
4058                throw new IllegalArgumentException("Unknown package: " + packageName);
4059            }
4060
4061            final BasePermission bp = mSettings.mPermissions.get(name);
4062            if (bp == null) {
4063                throw new IllegalArgumentException("Unknown permission: " + name);
4064            }
4065
4066            SettingBase sb = (SettingBase) pkg.mExtras;
4067            if (sb == null) {
4068                throw new IllegalArgumentException("Unknown package: " + packageName);
4069            }
4070
4071            PermissionsState permissionsState = sb.getPermissionsState();
4072            return permissionsState.getPermissionFlags(name, userId);
4073        }
4074    }
4075
4076    @Override
4077    public void updatePermissionFlags(String name, String packageName, int flagMask,
4078            int flagValues, int userId) {
4079        if (!sUserManager.exists(userId)) {
4080            return;
4081        }
4082
4083        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4084
4085        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4086                "updatePermissionFlags");
4087
4088        // Only the system can change these flags and nothing else.
4089        if (getCallingUid() != Process.SYSTEM_UID) {
4090            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4091            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4092            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4093            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4094            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4095        }
4096
4097        synchronized (mPackages) {
4098            final PackageParser.Package pkg = mPackages.get(packageName);
4099            if (pkg == null) {
4100                throw new IllegalArgumentException("Unknown package: " + packageName);
4101            }
4102
4103            final BasePermission bp = mSettings.mPermissions.get(name);
4104            if (bp == null) {
4105                throw new IllegalArgumentException("Unknown permission: " + name);
4106            }
4107
4108            SettingBase sb = (SettingBase) pkg.mExtras;
4109            if (sb == null) {
4110                throw new IllegalArgumentException("Unknown package: " + packageName);
4111            }
4112
4113            PermissionsState permissionsState = sb.getPermissionsState();
4114
4115            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4116
4117            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4118                // Install and runtime permissions are stored in different places,
4119                // so figure out what permission changed and persist the change.
4120                if (permissionsState.getInstallPermissionState(name) != null) {
4121                    scheduleWriteSettingsLocked();
4122                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4123                        || hadState) {
4124                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4125                }
4126            }
4127        }
4128    }
4129
4130    /**
4131     * Update the permission flags for all packages and runtime permissions of a user in order
4132     * to allow device or profile owner to remove POLICY_FIXED.
4133     */
4134    @Override
4135    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4136        if (!sUserManager.exists(userId)) {
4137            return;
4138        }
4139
4140        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4141
4142        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4143                "updatePermissionFlagsForAllApps");
4144
4145        // Only the system can change system fixed flags.
4146        if (getCallingUid() != Process.SYSTEM_UID) {
4147            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4148            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4149        }
4150
4151        synchronized (mPackages) {
4152            boolean changed = false;
4153            final int packageCount = mPackages.size();
4154            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4155                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4156                SettingBase sb = (SettingBase) pkg.mExtras;
4157                if (sb == null) {
4158                    continue;
4159                }
4160                PermissionsState permissionsState = sb.getPermissionsState();
4161                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4162                        userId, flagMask, flagValues);
4163            }
4164            if (changed) {
4165                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4166            }
4167        }
4168    }
4169
4170    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4171        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4172                != PackageManager.PERMISSION_GRANTED
4173            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4174                != PackageManager.PERMISSION_GRANTED) {
4175            throw new SecurityException(message + " requires "
4176                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4177                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4178        }
4179    }
4180
4181    @Override
4182    public boolean shouldShowRequestPermissionRationale(String permissionName,
4183            String packageName, int userId) {
4184        if (UserHandle.getCallingUserId() != userId) {
4185            mContext.enforceCallingPermission(
4186                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4187                    "canShowRequestPermissionRationale for user " + userId);
4188        }
4189
4190        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4191        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4192            return false;
4193        }
4194
4195        if (checkPermission(permissionName, packageName, userId)
4196                == PackageManager.PERMISSION_GRANTED) {
4197            return false;
4198        }
4199
4200        final int flags;
4201
4202        final long identity = Binder.clearCallingIdentity();
4203        try {
4204            flags = getPermissionFlags(permissionName,
4205                    packageName, userId);
4206        } finally {
4207            Binder.restoreCallingIdentity(identity);
4208        }
4209
4210        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4211                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4212                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4213
4214        if ((flags & fixedFlags) != 0) {
4215            return false;
4216        }
4217
4218        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4219    }
4220
4221    @Override
4222    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4223        mContext.enforceCallingOrSelfPermission(
4224                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4225                "addOnPermissionsChangeListener");
4226
4227        synchronized (mPackages) {
4228            mOnPermissionChangeListeners.addListenerLocked(listener);
4229        }
4230    }
4231
4232    @Override
4233    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4234        synchronized (mPackages) {
4235            mOnPermissionChangeListeners.removeListenerLocked(listener);
4236        }
4237    }
4238
4239    @Override
4240    public boolean isProtectedBroadcast(String actionName) {
4241        synchronized (mPackages) {
4242            if (mProtectedBroadcasts.contains(actionName)) {
4243                return true;
4244            } else if (actionName != null) {
4245                // TODO: remove these terrible hacks
4246                if (actionName.startsWith("android.net.netmon.lingerExpired")
4247                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4248                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")) {
4249                    return true;
4250                }
4251            }
4252        }
4253        return false;
4254    }
4255
4256    @Override
4257    public int checkSignatures(String pkg1, String pkg2) {
4258        synchronized (mPackages) {
4259            final PackageParser.Package p1 = mPackages.get(pkg1);
4260            final PackageParser.Package p2 = mPackages.get(pkg2);
4261            if (p1 == null || p1.mExtras == null
4262                    || p2 == null || p2.mExtras == null) {
4263                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4264            }
4265            return compareSignatures(p1.mSignatures, p2.mSignatures);
4266        }
4267    }
4268
4269    @Override
4270    public int checkUidSignatures(int uid1, int uid2) {
4271        // Map to base uids.
4272        uid1 = UserHandle.getAppId(uid1);
4273        uid2 = UserHandle.getAppId(uid2);
4274        // reader
4275        synchronized (mPackages) {
4276            Signature[] s1;
4277            Signature[] s2;
4278            Object obj = mSettings.getUserIdLPr(uid1);
4279            if (obj != null) {
4280                if (obj instanceof SharedUserSetting) {
4281                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4282                } else if (obj instanceof PackageSetting) {
4283                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4284                } else {
4285                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4286                }
4287            } else {
4288                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4289            }
4290            obj = mSettings.getUserIdLPr(uid2);
4291            if (obj != null) {
4292                if (obj instanceof SharedUserSetting) {
4293                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4294                } else if (obj instanceof PackageSetting) {
4295                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4296                } else {
4297                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4298                }
4299            } else {
4300                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4301            }
4302            return compareSignatures(s1, s2);
4303        }
4304    }
4305
4306    private void killUid(int appId, int userId, String reason) {
4307        final long identity = Binder.clearCallingIdentity();
4308        try {
4309            IActivityManager am = ActivityManagerNative.getDefault();
4310            if (am != null) {
4311                try {
4312                    am.killUid(appId, userId, reason);
4313                } catch (RemoteException e) {
4314                    /* ignore - same process */
4315                }
4316            }
4317        } finally {
4318            Binder.restoreCallingIdentity(identity);
4319        }
4320    }
4321
4322    /**
4323     * Compares two sets of signatures. Returns:
4324     * <br />
4325     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4326     * <br />
4327     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4328     * <br />
4329     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4330     * <br />
4331     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4332     * <br />
4333     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4334     */
4335    static int compareSignatures(Signature[] s1, Signature[] s2) {
4336        if (s1 == null) {
4337            return s2 == null
4338                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4339                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4340        }
4341
4342        if (s2 == null) {
4343            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4344        }
4345
4346        if (s1.length != s2.length) {
4347            return PackageManager.SIGNATURE_NO_MATCH;
4348        }
4349
4350        // Since both signature sets are of size 1, we can compare without HashSets.
4351        if (s1.length == 1) {
4352            return s1[0].equals(s2[0]) ?
4353                    PackageManager.SIGNATURE_MATCH :
4354                    PackageManager.SIGNATURE_NO_MATCH;
4355        }
4356
4357        ArraySet<Signature> set1 = new ArraySet<Signature>();
4358        for (Signature sig : s1) {
4359            set1.add(sig);
4360        }
4361        ArraySet<Signature> set2 = new ArraySet<Signature>();
4362        for (Signature sig : s2) {
4363            set2.add(sig);
4364        }
4365        // Make sure s2 contains all signatures in s1.
4366        if (set1.equals(set2)) {
4367            return PackageManager.SIGNATURE_MATCH;
4368        }
4369        return PackageManager.SIGNATURE_NO_MATCH;
4370    }
4371
4372    /**
4373     * If the database version for this type of package (internal storage or
4374     * external storage) is less than the version where package signatures
4375     * were updated, return true.
4376     */
4377    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4378        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4379        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4380    }
4381
4382    /**
4383     * Used for backward compatibility to make sure any packages with
4384     * certificate chains get upgraded to the new style. {@code existingSigs}
4385     * will be in the old format (since they were stored on disk from before the
4386     * system upgrade) and {@code scannedSigs} will be in the newer format.
4387     */
4388    private int compareSignaturesCompat(PackageSignatures existingSigs,
4389            PackageParser.Package scannedPkg) {
4390        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4391            return PackageManager.SIGNATURE_NO_MATCH;
4392        }
4393
4394        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4395        for (Signature sig : existingSigs.mSignatures) {
4396            existingSet.add(sig);
4397        }
4398        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4399        for (Signature sig : scannedPkg.mSignatures) {
4400            try {
4401                Signature[] chainSignatures = sig.getChainSignatures();
4402                for (Signature chainSig : chainSignatures) {
4403                    scannedCompatSet.add(chainSig);
4404                }
4405            } catch (CertificateEncodingException e) {
4406                scannedCompatSet.add(sig);
4407            }
4408        }
4409        /*
4410         * Make sure the expanded scanned set contains all signatures in the
4411         * existing one.
4412         */
4413        if (scannedCompatSet.equals(existingSet)) {
4414            // Migrate the old signatures to the new scheme.
4415            existingSigs.assignSignatures(scannedPkg.mSignatures);
4416            // The new KeySets will be re-added later in the scanning process.
4417            synchronized (mPackages) {
4418                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4419            }
4420            return PackageManager.SIGNATURE_MATCH;
4421        }
4422        return PackageManager.SIGNATURE_NO_MATCH;
4423    }
4424
4425    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4426        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4427        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4428    }
4429
4430    private int compareSignaturesRecover(PackageSignatures existingSigs,
4431            PackageParser.Package scannedPkg) {
4432        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4433            return PackageManager.SIGNATURE_NO_MATCH;
4434        }
4435
4436        String msg = null;
4437        try {
4438            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4439                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4440                        + scannedPkg.packageName);
4441                return PackageManager.SIGNATURE_MATCH;
4442            }
4443        } catch (CertificateException e) {
4444            msg = e.getMessage();
4445        }
4446
4447        logCriticalInfo(Log.INFO,
4448                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4449        return PackageManager.SIGNATURE_NO_MATCH;
4450    }
4451
4452    @Override
4453    public String[] getPackagesForUid(int uid) {
4454        uid = UserHandle.getAppId(uid);
4455        // reader
4456        synchronized (mPackages) {
4457            Object obj = mSettings.getUserIdLPr(uid);
4458            if (obj instanceof SharedUserSetting) {
4459                final SharedUserSetting sus = (SharedUserSetting) obj;
4460                final int N = sus.packages.size();
4461                final String[] res = new String[N];
4462                final Iterator<PackageSetting> it = sus.packages.iterator();
4463                int i = 0;
4464                while (it.hasNext()) {
4465                    res[i++] = it.next().name;
4466                }
4467                return res;
4468            } else if (obj instanceof PackageSetting) {
4469                final PackageSetting ps = (PackageSetting) obj;
4470                return new String[] { ps.name };
4471            }
4472        }
4473        return null;
4474    }
4475
4476    @Override
4477    public String getNameForUid(int uid) {
4478        // reader
4479        synchronized (mPackages) {
4480            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4481            if (obj instanceof SharedUserSetting) {
4482                final SharedUserSetting sus = (SharedUserSetting) obj;
4483                return sus.name + ":" + sus.userId;
4484            } else if (obj instanceof PackageSetting) {
4485                final PackageSetting ps = (PackageSetting) obj;
4486                return ps.name;
4487            }
4488        }
4489        return null;
4490    }
4491
4492    @Override
4493    public int getUidForSharedUser(String sharedUserName) {
4494        if(sharedUserName == null) {
4495            return -1;
4496        }
4497        // reader
4498        synchronized (mPackages) {
4499            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4500            if (suid == null) {
4501                return -1;
4502            }
4503            return suid.userId;
4504        }
4505    }
4506
4507    @Override
4508    public int getFlagsForUid(int uid) {
4509        synchronized (mPackages) {
4510            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4511            if (obj instanceof SharedUserSetting) {
4512                final SharedUserSetting sus = (SharedUserSetting) obj;
4513                return sus.pkgFlags;
4514            } else if (obj instanceof PackageSetting) {
4515                final PackageSetting ps = (PackageSetting) obj;
4516                return ps.pkgFlags;
4517            }
4518        }
4519        return 0;
4520    }
4521
4522    @Override
4523    public int getPrivateFlagsForUid(int uid) {
4524        synchronized (mPackages) {
4525            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4526            if (obj instanceof SharedUserSetting) {
4527                final SharedUserSetting sus = (SharedUserSetting) obj;
4528                return sus.pkgPrivateFlags;
4529            } else if (obj instanceof PackageSetting) {
4530                final PackageSetting ps = (PackageSetting) obj;
4531                return ps.pkgPrivateFlags;
4532            }
4533        }
4534        return 0;
4535    }
4536
4537    @Override
4538    public boolean isUidPrivileged(int uid) {
4539        uid = UserHandle.getAppId(uid);
4540        // reader
4541        synchronized (mPackages) {
4542            Object obj = mSettings.getUserIdLPr(uid);
4543            if (obj instanceof SharedUserSetting) {
4544                final SharedUserSetting sus = (SharedUserSetting) obj;
4545                final Iterator<PackageSetting> it = sus.packages.iterator();
4546                while (it.hasNext()) {
4547                    if (it.next().isPrivileged()) {
4548                        return true;
4549                    }
4550                }
4551            } else if (obj instanceof PackageSetting) {
4552                final PackageSetting ps = (PackageSetting) obj;
4553                return ps.isPrivileged();
4554            }
4555        }
4556        return false;
4557    }
4558
4559    @Override
4560    public String[] getAppOpPermissionPackages(String permissionName) {
4561        synchronized (mPackages) {
4562            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4563            if (pkgs == null) {
4564                return null;
4565            }
4566            return pkgs.toArray(new String[pkgs.size()]);
4567        }
4568    }
4569
4570    @Override
4571    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4572            int flags, int userId) {
4573        if (!sUserManager.exists(userId)) return null;
4574        flags = updateFlagsForResolve(flags, userId, intent);
4575        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4576        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4577        final ResolveInfo bestChoice =
4578                chooseBestActivity(intent, resolvedType, flags, query, userId);
4579
4580        if (isEphemeralAllowed(intent, query, userId)) {
4581            final EphemeralResolveInfo ai =
4582                    getEphemeralResolveInfo(intent, resolvedType, userId);
4583            if (ai != null) {
4584                if (DEBUG_EPHEMERAL) {
4585                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4586                }
4587                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4588                bestChoice.ephemeralResolveInfo = ai;
4589            }
4590        }
4591        return bestChoice;
4592    }
4593
4594    @Override
4595    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4596            IntentFilter filter, int match, ComponentName activity) {
4597        final int userId = UserHandle.getCallingUserId();
4598        if (DEBUG_PREFERRED) {
4599            Log.v(TAG, "setLastChosenActivity intent=" + intent
4600                + " resolvedType=" + resolvedType
4601                + " flags=" + flags
4602                + " filter=" + filter
4603                + " match=" + match
4604                + " activity=" + activity);
4605            filter.dump(new PrintStreamPrinter(System.out), "    ");
4606        }
4607        intent.setComponent(null);
4608        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4609        // Find any earlier preferred or last chosen entries and nuke them
4610        findPreferredActivity(intent, resolvedType,
4611                flags, query, 0, false, true, false, userId);
4612        // Add the new activity as the last chosen for this filter
4613        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4614                "Setting last chosen");
4615    }
4616
4617    @Override
4618    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4619        final int userId = UserHandle.getCallingUserId();
4620        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4621        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4622        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4623                false, false, false, userId);
4624    }
4625
4626
4627    private boolean isEphemeralAllowed(
4628            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4629        // Short circuit and return early if possible.
4630        if (DISABLE_EPHEMERAL_APPS) {
4631            return false;
4632        }
4633        final int callingUser = UserHandle.getCallingUserId();
4634        if (callingUser != UserHandle.USER_SYSTEM) {
4635            return false;
4636        }
4637        if (mEphemeralResolverConnection == null) {
4638            return false;
4639        }
4640        if (intent.getComponent() != null) {
4641            return false;
4642        }
4643        if (intent.getPackage() != null) {
4644            return false;
4645        }
4646        final boolean isWebUri = hasWebURI(intent);
4647        if (!isWebUri) {
4648            return false;
4649        }
4650        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4651        synchronized (mPackages) {
4652            final int count = resolvedActivites.size();
4653            for (int n = 0; n < count; n++) {
4654                ResolveInfo info = resolvedActivites.get(n);
4655                String packageName = info.activityInfo.packageName;
4656                PackageSetting ps = mSettings.mPackages.get(packageName);
4657                if (ps != null) {
4658                    // Try to get the status from User settings first
4659                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4660                    int status = (int) (packedStatus >> 32);
4661                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4662                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4663                        if (DEBUG_EPHEMERAL) {
4664                            Slog.v(TAG, "DENY ephemeral apps;"
4665                                + " pkg: " + packageName + ", status: " + status);
4666                        }
4667                        return false;
4668                    }
4669                }
4670            }
4671        }
4672        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4673        return true;
4674    }
4675
4676    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4677            int userId) {
4678        MessageDigest digest = null;
4679        try {
4680            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4681        } catch (NoSuchAlgorithmException e) {
4682            // If we can't create a digest, ignore ephemeral apps.
4683            return null;
4684        }
4685
4686        final byte[] hostBytes = intent.getData().getHost().getBytes();
4687        final byte[] digestBytes = digest.digest(hostBytes);
4688        int shaPrefix =
4689                digestBytes[0] << 24
4690                | digestBytes[1] << 16
4691                | digestBytes[2] << 8
4692                | digestBytes[3] << 0;
4693        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4694                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4695        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4696            // No hash prefix match; there are no ephemeral apps for this domain.
4697            return null;
4698        }
4699        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4700            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4701            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4702                continue;
4703            }
4704            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4705            // No filters; this should never happen.
4706            if (filters.isEmpty()) {
4707                continue;
4708            }
4709            // We have a domain match; resolve the filters to see if anything matches.
4710            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4711            for (int j = filters.size() - 1; j >= 0; --j) {
4712                final EphemeralResolveIntentInfo intentInfo =
4713                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4714                ephemeralResolver.addFilter(intentInfo);
4715            }
4716            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4717                    intent, resolvedType, false /*defaultOnly*/, userId);
4718            if (!matchedResolveInfoList.isEmpty()) {
4719                return matchedResolveInfoList.get(0);
4720            }
4721        }
4722        // Hash or filter mis-match; no ephemeral apps for this domain.
4723        return null;
4724    }
4725
4726    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4727            int flags, List<ResolveInfo> query, int userId) {
4728        if (query != null) {
4729            final int N = query.size();
4730            if (N == 1) {
4731                return query.get(0);
4732            } else if (N > 1) {
4733                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4734                // If there is more than one activity with the same priority,
4735                // then let the user decide between them.
4736                ResolveInfo r0 = query.get(0);
4737                ResolveInfo r1 = query.get(1);
4738                if (DEBUG_INTENT_MATCHING || debug) {
4739                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4740                            + r1.activityInfo.name + "=" + r1.priority);
4741                }
4742                // If the first activity has a higher priority, or a different
4743                // default, then it is always desirable to pick it.
4744                if (r0.priority != r1.priority
4745                        || r0.preferredOrder != r1.preferredOrder
4746                        || r0.isDefault != r1.isDefault) {
4747                    return query.get(0);
4748                }
4749                // If we have saved a preference for a preferred activity for
4750                // this Intent, use that.
4751                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4752                        flags, query, r0.priority, true, false, debug, userId);
4753                if (ri != null) {
4754                    return ri;
4755                }
4756                ri = new ResolveInfo(mResolveInfo);
4757                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4758                ri.activityInfo.applicationInfo = new ApplicationInfo(
4759                        ri.activityInfo.applicationInfo);
4760                if (userId != 0) {
4761                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4762                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4763                }
4764                // Make sure that the resolver is displayable in car mode
4765                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4766                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4767                return ri;
4768            }
4769        }
4770        return null;
4771    }
4772
4773    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4774            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4775        final int N = query.size();
4776        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4777                .get(userId);
4778        // Get the list of persistent preferred activities that handle the intent
4779        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4780        List<PersistentPreferredActivity> pprefs = ppir != null
4781                ? ppir.queryIntent(intent, resolvedType,
4782                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4783                : null;
4784        if (pprefs != null && pprefs.size() > 0) {
4785            final int M = pprefs.size();
4786            for (int i=0; i<M; i++) {
4787                final PersistentPreferredActivity ppa = pprefs.get(i);
4788                if (DEBUG_PREFERRED || debug) {
4789                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4790                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4791                            + "\n  component=" + ppa.mComponent);
4792                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4793                }
4794                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4795                        flags | MATCH_DISABLED_COMPONENTS, userId);
4796                if (DEBUG_PREFERRED || debug) {
4797                    Slog.v(TAG, "Found persistent preferred activity:");
4798                    if (ai != null) {
4799                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4800                    } else {
4801                        Slog.v(TAG, "  null");
4802                    }
4803                }
4804                if (ai == null) {
4805                    // This previously registered persistent preferred activity
4806                    // component is no longer known. Ignore it and do NOT remove it.
4807                    continue;
4808                }
4809                for (int j=0; j<N; j++) {
4810                    final ResolveInfo ri = query.get(j);
4811                    if (!ri.activityInfo.applicationInfo.packageName
4812                            .equals(ai.applicationInfo.packageName)) {
4813                        continue;
4814                    }
4815                    if (!ri.activityInfo.name.equals(ai.name)) {
4816                        continue;
4817                    }
4818                    //  Found a persistent preference that can handle the intent.
4819                    if (DEBUG_PREFERRED || debug) {
4820                        Slog.v(TAG, "Returning persistent preferred activity: " +
4821                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4822                    }
4823                    return ri;
4824                }
4825            }
4826        }
4827        return null;
4828    }
4829
4830    // TODO: handle preferred activities missing while user has amnesia
4831    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4832            List<ResolveInfo> query, int priority, boolean always,
4833            boolean removeMatches, boolean debug, int userId) {
4834        if (!sUserManager.exists(userId)) return null;
4835        flags = updateFlagsForResolve(flags, userId, intent);
4836        // writer
4837        synchronized (mPackages) {
4838            if (intent.getSelector() != null) {
4839                intent = intent.getSelector();
4840            }
4841            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4842
4843            // Try to find a matching persistent preferred activity.
4844            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4845                    debug, userId);
4846
4847            // If a persistent preferred activity matched, use it.
4848            if (pri != null) {
4849                return pri;
4850            }
4851
4852            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4853            // Get the list of preferred activities that handle the intent
4854            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4855            List<PreferredActivity> prefs = pir != null
4856                    ? pir.queryIntent(intent, resolvedType,
4857                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4858                    : null;
4859            if (prefs != null && prefs.size() > 0) {
4860                boolean changed = false;
4861                try {
4862                    // First figure out how good the original match set is.
4863                    // We will only allow preferred activities that came
4864                    // from the same match quality.
4865                    int match = 0;
4866
4867                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4868
4869                    final int N = query.size();
4870                    for (int j=0; j<N; j++) {
4871                        final ResolveInfo ri = query.get(j);
4872                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4873                                + ": 0x" + Integer.toHexString(match));
4874                        if (ri.match > match) {
4875                            match = ri.match;
4876                        }
4877                    }
4878
4879                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4880                            + Integer.toHexString(match));
4881
4882                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4883                    final int M = prefs.size();
4884                    for (int i=0; i<M; i++) {
4885                        final PreferredActivity pa = prefs.get(i);
4886                        if (DEBUG_PREFERRED || debug) {
4887                            Slog.v(TAG, "Checking PreferredActivity ds="
4888                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4889                                    + "\n  component=" + pa.mPref.mComponent);
4890                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4891                        }
4892                        if (pa.mPref.mMatch != match) {
4893                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4894                                    + Integer.toHexString(pa.mPref.mMatch));
4895                            continue;
4896                        }
4897                        // If it's not an "always" type preferred activity and that's what we're
4898                        // looking for, skip it.
4899                        if (always && !pa.mPref.mAlways) {
4900                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4901                            continue;
4902                        }
4903                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4904                                flags | MATCH_DISABLED_COMPONENTS, userId);
4905                        if (DEBUG_PREFERRED || debug) {
4906                            Slog.v(TAG, "Found preferred activity:");
4907                            if (ai != null) {
4908                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4909                            } else {
4910                                Slog.v(TAG, "  null");
4911                            }
4912                        }
4913                        if (ai == null) {
4914                            // This previously registered preferred activity
4915                            // component is no longer known.  Most likely an update
4916                            // to the app was installed and in the new version this
4917                            // component no longer exists.  Clean it up by removing
4918                            // it from the preferred activities list, and skip it.
4919                            Slog.w(TAG, "Removing dangling preferred activity: "
4920                                    + pa.mPref.mComponent);
4921                            pir.removeFilter(pa);
4922                            changed = true;
4923                            continue;
4924                        }
4925                        for (int j=0; j<N; j++) {
4926                            final ResolveInfo ri = query.get(j);
4927                            if (!ri.activityInfo.applicationInfo.packageName
4928                                    .equals(ai.applicationInfo.packageName)) {
4929                                continue;
4930                            }
4931                            if (!ri.activityInfo.name.equals(ai.name)) {
4932                                continue;
4933                            }
4934
4935                            if (removeMatches) {
4936                                pir.removeFilter(pa);
4937                                changed = true;
4938                                if (DEBUG_PREFERRED) {
4939                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4940                                }
4941                                break;
4942                            }
4943
4944                            // Okay we found a previously set preferred or last chosen app.
4945                            // If the result set is different from when this
4946                            // was created, we need to clear it and re-ask the
4947                            // user their preference, if we're looking for an "always" type entry.
4948                            if (always && !pa.mPref.sameSet(query)) {
4949                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4950                                        + intent + " type " + resolvedType);
4951                                if (DEBUG_PREFERRED) {
4952                                    Slog.v(TAG, "Removing preferred activity since set changed "
4953                                            + pa.mPref.mComponent);
4954                                }
4955                                pir.removeFilter(pa);
4956                                // Re-add the filter as a "last chosen" entry (!always)
4957                                PreferredActivity lastChosen = new PreferredActivity(
4958                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4959                                pir.addFilter(lastChosen);
4960                                changed = true;
4961                                return null;
4962                            }
4963
4964                            // Yay! Either the set matched or we're looking for the last chosen
4965                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4966                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4967                            return ri;
4968                        }
4969                    }
4970                } finally {
4971                    if (changed) {
4972                        if (DEBUG_PREFERRED) {
4973                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4974                        }
4975                        scheduleWritePackageRestrictionsLocked(userId);
4976                    }
4977                }
4978            }
4979        }
4980        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4981        return null;
4982    }
4983
4984    /*
4985     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4986     */
4987    @Override
4988    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4989            int targetUserId) {
4990        mContext.enforceCallingOrSelfPermission(
4991                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4992        List<CrossProfileIntentFilter> matches =
4993                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4994        if (matches != null) {
4995            int size = matches.size();
4996            for (int i = 0; i < size; i++) {
4997                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4998            }
4999        }
5000        if (hasWebURI(intent)) {
5001            // cross-profile app linking works only towards the parent.
5002            final UserInfo parent = getProfileParent(sourceUserId);
5003            synchronized(mPackages) {
5004                int flags = updateFlagsForResolve(0, parent.id, intent);
5005                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5006                        intent, resolvedType, flags, sourceUserId, parent.id);
5007                return xpDomainInfo != null;
5008            }
5009        }
5010        return false;
5011    }
5012
5013    private UserInfo getProfileParent(int userId) {
5014        final long identity = Binder.clearCallingIdentity();
5015        try {
5016            return sUserManager.getProfileParent(userId);
5017        } finally {
5018            Binder.restoreCallingIdentity(identity);
5019        }
5020    }
5021
5022    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5023            String resolvedType, int userId) {
5024        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5025        if (resolver != null) {
5026            return resolver.queryIntent(intent, resolvedType, false, userId);
5027        }
5028        return null;
5029    }
5030
5031    @Override
5032    public List<ResolveInfo> queryIntentActivities(Intent intent,
5033            String resolvedType, int flags, int userId) {
5034        if (!sUserManager.exists(userId)) return Collections.emptyList();
5035        flags = updateFlagsForResolve(flags, userId, intent);
5036        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
5037        ComponentName comp = intent.getComponent();
5038        if (comp == null) {
5039            if (intent.getSelector() != null) {
5040                intent = intent.getSelector();
5041                comp = intent.getComponent();
5042            }
5043        }
5044
5045        if (comp != null) {
5046            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5047            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5048            if (ai != null) {
5049                final ResolveInfo ri = new ResolveInfo();
5050                ri.activityInfo = ai;
5051                list.add(ri);
5052            }
5053            return list;
5054        }
5055
5056        // reader
5057        synchronized (mPackages) {
5058            final String pkgName = intent.getPackage();
5059            if (pkgName == null) {
5060                List<CrossProfileIntentFilter> matchingFilters =
5061                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5062                // Check for results that need to skip the current profile.
5063                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5064                        resolvedType, flags, userId);
5065                if (xpResolveInfo != null) {
5066                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5067                    result.add(xpResolveInfo);
5068                    return filterIfNotSystemUser(result, userId);
5069                }
5070
5071                // Check for results in the current profile.
5072                List<ResolveInfo> result = mActivities.queryIntent(
5073                        intent, resolvedType, flags, userId);
5074                result = filterIfNotSystemUser(result, userId);
5075
5076                // Check for cross profile results.
5077                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5078                xpResolveInfo = queryCrossProfileIntents(
5079                        matchingFilters, intent, resolvedType, flags, userId,
5080                        hasNonNegativePriorityResult);
5081                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5082                    boolean isVisibleToUser = filterIfNotSystemUser(
5083                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5084                    if (isVisibleToUser) {
5085                        result.add(xpResolveInfo);
5086                        Collections.sort(result, mResolvePrioritySorter);
5087                    }
5088                }
5089                if (hasWebURI(intent)) {
5090                    CrossProfileDomainInfo xpDomainInfo = null;
5091                    final UserInfo parent = getProfileParent(userId);
5092                    if (parent != null) {
5093                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5094                                flags, userId, parent.id);
5095                    }
5096                    if (xpDomainInfo != null) {
5097                        if (xpResolveInfo != null) {
5098                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5099                            // in the result.
5100                            result.remove(xpResolveInfo);
5101                        }
5102                        if (result.size() == 0) {
5103                            result.add(xpDomainInfo.resolveInfo);
5104                            return result;
5105                        }
5106                    } else if (result.size() <= 1) {
5107                        return result;
5108                    }
5109                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5110                            xpDomainInfo, userId);
5111                    Collections.sort(result, mResolvePrioritySorter);
5112                }
5113                return result;
5114            }
5115            final PackageParser.Package pkg = mPackages.get(pkgName);
5116            if (pkg != null) {
5117                return filterIfNotSystemUser(
5118                        mActivities.queryIntentForPackage(
5119                                intent, resolvedType, flags, pkg.activities, userId),
5120                        userId);
5121            }
5122            return new ArrayList<ResolveInfo>();
5123        }
5124    }
5125
5126    private static class CrossProfileDomainInfo {
5127        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5128        ResolveInfo resolveInfo;
5129        /* Best domain verification status of the activities found in the other profile */
5130        int bestDomainVerificationStatus;
5131    }
5132
5133    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5134            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5135        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5136                sourceUserId)) {
5137            return null;
5138        }
5139        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5140                resolvedType, flags, parentUserId);
5141
5142        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5143            return null;
5144        }
5145        CrossProfileDomainInfo result = null;
5146        int size = resultTargetUser.size();
5147        for (int i = 0; i < size; i++) {
5148            ResolveInfo riTargetUser = resultTargetUser.get(i);
5149            // Intent filter verification is only for filters that specify a host. So don't return
5150            // those that handle all web uris.
5151            if (riTargetUser.handleAllWebDataURI) {
5152                continue;
5153            }
5154            String packageName = riTargetUser.activityInfo.packageName;
5155            PackageSetting ps = mSettings.mPackages.get(packageName);
5156            if (ps == null) {
5157                continue;
5158            }
5159            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5160            int status = (int)(verificationState >> 32);
5161            if (result == null) {
5162                result = new CrossProfileDomainInfo();
5163                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5164                        sourceUserId, parentUserId);
5165                result.bestDomainVerificationStatus = status;
5166            } else {
5167                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5168                        result.bestDomainVerificationStatus);
5169            }
5170        }
5171        // Don't consider matches with status NEVER across profiles.
5172        if (result != null && result.bestDomainVerificationStatus
5173                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5174            return null;
5175        }
5176        return result;
5177    }
5178
5179    /**
5180     * Verification statuses are ordered from the worse to the best, except for
5181     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5182     */
5183    private int bestDomainVerificationStatus(int status1, int status2) {
5184        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5185            return status2;
5186        }
5187        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5188            return status1;
5189        }
5190        return (int) MathUtils.max(status1, status2);
5191    }
5192
5193    private boolean isUserEnabled(int userId) {
5194        long callingId = Binder.clearCallingIdentity();
5195        try {
5196            UserInfo userInfo = sUserManager.getUserInfo(userId);
5197            return userInfo != null && userInfo.isEnabled();
5198        } finally {
5199            Binder.restoreCallingIdentity(callingId);
5200        }
5201    }
5202
5203    /**
5204     * Filter out activities with systemUserOnly flag set, when current user is not System.
5205     *
5206     * @return filtered list
5207     */
5208    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5209        if (userId == UserHandle.USER_SYSTEM) {
5210            return resolveInfos;
5211        }
5212        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5213            ResolveInfo info = resolveInfos.get(i);
5214            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5215                resolveInfos.remove(i);
5216            }
5217        }
5218        return resolveInfos;
5219    }
5220
5221    /**
5222     * @param resolveInfos list of resolve infos in descending priority order
5223     * @return if the list contains a resolve info with non-negative priority
5224     */
5225    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5226        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5227    }
5228
5229    private static boolean hasWebURI(Intent intent) {
5230        if (intent.getData() == null) {
5231            return false;
5232        }
5233        final String scheme = intent.getScheme();
5234        if (TextUtils.isEmpty(scheme)) {
5235            return false;
5236        }
5237        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5238    }
5239
5240    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5241            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5242            int userId) {
5243        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5244
5245        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5246            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5247                    candidates.size());
5248        }
5249
5250        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5251        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5252        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5253        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5254        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5255        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5256
5257        synchronized (mPackages) {
5258            final int count = candidates.size();
5259            // First, try to use linked apps. Partition the candidates into four lists:
5260            // one for the final results, one for the "do not use ever", one for "undefined status"
5261            // and finally one for "browser app type".
5262            for (int n=0; n<count; n++) {
5263                ResolveInfo info = candidates.get(n);
5264                String packageName = info.activityInfo.packageName;
5265                PackageSetting ps = mSettings.mPackages.get(packageName);
5266                if (ps != null) {
5267                    // Add to the special match all list (Browser use case)
5268                    if (info.handleAllWebDataURI) {
5269                        matchAllList.add(info);
5270                        continue;
5271                    }
5272                    // Try to get the status from User settings first
5273                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5274                    int status = (int)(packedStatus >> 32);
5275                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5276                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5277                        if (DEBUG_DOMAIN_VERIFICATION) {
5278                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5279                                    + " : linkgen=" + linkGeneration);
5280                        }
5281                        // Use link-enabled generation as preferredOrder, i.e.
5282                        // prefer newly-enabled over earlier-enabled.
5283                        info.preferredOrder = linkGeneration;
5284                        alwaysList.add(info);
5285                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5286                        if (DEBUG_DOMAIN_VERIFICATION) {
5287                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5288                        }
5289                        neverList.add(info);
5290                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5291                        if (DEBUG_DOMAIN_VERIFICATION) {
5292                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5293                        }
5294                        alwaysAskList.add(info);
5295                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5296                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5297                        if (DEBUG_DOMAIN_VERIFICATION) {
5298                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5299                        }
5300                        undefinedList.add(info);
5301                    }
5302                }
5303            }
5304
5305            // We'll want to include browser possibilities in a few cases
5306            boolean includeBrowser = false;
5307
5308            // First try to add the "always" resolution(s) for the current user, if any
5309            if (alwaysList.size() > 0) {
5310                result.addAll(alwaysList);
5311            } else {
5312                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5313                result.addAll(undefinedList);
5314                // Maybe add one for the other profile.
5315                if (xpDomainInfo != null && (
5316                        xpDomainInfo.bestDomainVerificationStatus
5317                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5318                    result.add(xpDomainInfo.resolveInfo);
5319                }
5320                includeBrowser = true;
5321            }
5322
5323            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5324            // If there were 'always' entries their preferred order has been set, so we also
5325            // back that off to make the alternatives equivalent
5326            if (alwaysAskList.size() > 0) {
5327                for (ResolveInfo i : result) {
5328                    i.preferredOrder = 0;
5329                }
5330                result.addAll(alwaysAskList);
5331                includeBrowser = true;
5332            }
5333
5334            if (includeBrowser) {
5335                // Also add browsers (all of them or only the default one)
5336                if (DEBUG_DOMAIN_VERIFICATION) {
5337                    Slog.v(TAG, "   ...including browsers in candidate set");
5338                }
5339                if ((matchFlags & MATCH_ALL) != 0) {
5340                    result.addAll(matchAllList);
5341                } else {
5342                    // Browser/generic handling case.  If there's a default browser, go straight
5343                    // to that (but only if there is no other higher-priority match).
5344                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5345                    int maxMatchPrio = 0;
5346                    ResolveInfo defaultBrowserMatch = null;
5347                    final int numCandidates = matchAllList.size();
5348                    for (int n = 0; n < numCandidates; n++) {
5349                        ResolveInfo info = matchAllList.get(n);
5350                        // track the highest overall match priority...
5351                        if (info.priority > maxMatchPrio) {
5352                            maxMatchPrio = info.priority;
5353                        }
5354                        // ...and the highest-priority default browser match
5355                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5356                            if (defaultBrowserMatch == null
5357                                    || (defaultBrowserMatch.priority < info.priority)) {
5358                                if (debug) {
5359                                    Slog.v(TAG, "Considering default browser match " + info);
5360                                }
5361                                defaultBrowserMatch = info;
5362                            }
5363                        }
5364                    }
5365                    if (defaultBrowserMatch != null
5366                            && defaultBrowserMatch.priority >= maxMatchPrio
5367                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5368                    {
5369                        if (debug) {
5370                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5371                        }
5372                        result.add(defaultBrowserMatch);
5373                    } else {
5374                        result.addAll(matchAllList);
5375                    }
5376                }
5377
5378                // If there is nothing selected, add all candidates and remove the ones that the user
5379                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5380                if (result.size() == 0) {
5381                    result.addAll(candidates);
5382                    result.removeAll(neverList);
5383                }
5384            }
5385        }
5386        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5387            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5388                    result.size());
5389            for (ResolveInfo info : result) {
5390                Slog.v(TAG, "  + " + info.activityInfo);
5391            }
5392        }
5393        return result;
5394    }
5395
5396    // Returns a packed value as a long:
5397    //
5398    // high 'int'-sized word: link status: undefined/ask/never/always.
5399    // low 'int'-sized word: relative priority among 'always' results.
5400    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5401        long result = ps.getDomainVerificationStatusForUser(userId);
5402        // if none available, get the master status
5403        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5404            if (ps.getIntentFilterVerificationInfo() != null) {
5405                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5406            }
5407        }
5408        return result;
5409    }
5410
5411    private ResolveInfo querySkipCurrentProfileIntents(
5412            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5413            int flags, int sourceUserId) {
5414        if (matchingFilters != null) {
5415            int size = matchingFilters.size();
5416            for (int i = 0; i < size; i ++) {
5417                CrossProfileIntentFilter filter = matchingFilters.get(i);
5418                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5419                    // Checking if there are activities in the target user that can handle the
5420                    // intent.
5421                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5422                            resolvedType, flags, sourceUserId);
5423                    if (resolveInfo != null) {
5424                        return resolveInfo;
5425                    }
5426                }
5427            }
5428        }
5429        return null;
5430    }
5431
5432    // Return matching ResolveInfo in target user if any.
5433    private ResolveInfo queryCrossProfileIntents(
5434            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5435            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5436        if (matchingFilters != null) {
5437            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5438            // match the same intent. For performance reasons, it is better not to
5439            // run queryIntent twice for the same userId
5440            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5441            int size = matchingFilters.size();
5442            for (int i = 0; i < size; i++) {
5443                CrossProfileIntentFilter filter = matchingFilters.get(i);
5444                int targetUserId = filter.getTargetUserId();
5445                boolean skipCurrentProfile =
5446                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5447                boolean skipCurrentProfileIfNoMatchFound =
5448                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5449                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5450                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5451                    // Checking if there are activities in the target user that can handle the
5452                    // intent.
5453                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5454                            resolvedType, flags, sourceUserId);
5455                    if (resolveInfo != null) return resolveInfo;
5456                    alreadyTriedUserIds.put(targetUserId, true);
5457                }
5458            }
5459        }
5460        return null;
5461    }
5462
5463    /**
5464     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5465     * will forward the intent to the filter's target user.
5466     * Otherwise, returns null.
5467     */
5468    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5469            String resolvedType, int flags, int sourceUserId) {
5470        int targetUserId = filter.getTargetUserId();
5471        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5472                resolvedType, flags, targetUserId);
5473        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5474            // If all the matches in the target profile are suspended, return null.
5475            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5476                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5477                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5478                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5479                            targetUserId);
5480                }
5481            }
5482        }
5483        return null;
5484    }
5485
5486    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5487            int sourceUserId, int targetUserId) {
5488        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5489        long ident = Binder.clearCallingIdentity();
5490        boolean targetIsProfile;
5491        try {
5492            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5493        } finally {
5494            Binder.restoreCallingIdentity(ident);
5495        }
5496        String className;
5497        if (targetIsProfile) {
5498            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5499        } else {
5500            className = FORWARD_INTENT_TO_PARENT;
5501        }
5502        ComponentName forwardingActivityComponentName = new ComponentName(
5503                mAndroidApplication.packageName, className);
5504        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5505                sourceUserId);
5506        if (!targetIsProfile) {
5507            forwardingActivityInfo.showUserIcon = targetUserId;
5508            forwardingResolveInfo.noResourceId = true;
5509        }
5510        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5511        forwardingResolveInfo.priority = 0;
5512        forwardingResolveInfo.preferredOrder = 0;
5513        forwardingResolveInfo.match = 0;
5514        forwardingResolveInfo.isDefault = true;
5515        forwardingResolveInfo.filter = filter;
5516        forwardingResolveInfo.targetUserId = targetUserId;
5517        return forwardingResolveInfo;
5518    }
5519
5520    @Override
5521    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5522            Intent[] specifics, String[] specificTypes, Intent intent,
5523            String resolvedType, int flags, int userId) {
5524        if (!sUserManager.exists(userId)) return Collections.emptyList();
5525        flags = updateFlagsForResolve(flags, userId, intent);
5526        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5527                false, "query intent activity options");
5528        final String resultsAction = intent.getAction();
5529
5530        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5531                | PackageManager.GET_RESOLVED_FILTER, userId);
5532
5533        if (DEBUG_INTENT_MATCHING) {
5534            Log.v(TAG, "Query " + intent + ": " + results);
5535        }
5536
5537        int specificsPos = 0;
5538        int N;
5539
5540        // todo: note that the algorithm used here is O(N^2).  This
5541        // isn't a problem in our current environment, but if we start running
5542        // into situations where we have more than 5 or 10 matches then this
5543        // should probably be changed to something smarter...
5544
5545        // First we go through and resolve each of the specific items
5546        // that were supplied, taking care of removing any corresponding
5547        // duplicate items in the generic resolve list.
5548        if (specifics != null) {
5549            for (int i=0; i<specifics.length; i++) {
5550                final Intent sintent = specifics[i];
5551                if (sintent == null) {
5552                    continue;
5553                }
5554
5555                if (DEBUG_INTENT_MATCHING) {
5556                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5557                }
5558
5559                String action = sintent.getAction();
5560                if (resultsAction != null && resultsAction.equals(action)) {
5561                    // If this action was explicitly requested, then don't
5562                    // remove things that have it.
5563                    action = null;
5564                }
5565
5566                ResolveInfo ri = null;
5567                ActivityInfo ai = null;
5568
5569                ComponentName comp = sintent.getComponent();
5570                if (comp == null) {
5571                    ri = resolveIntent(
5572                        sintent,
5573                        specificTypes != null ? specificTypes[i] : null,
5574                            flags, userId);
5575                    if (ri == null) {
5576                        continue;
5577                    }
5578                    if (ri == mResolveInfo) {
5579                        // ACK!  Must do something better with this.
5580                    }
5581                    ai = ri.activityInfo;
5582                    comp = new ComponentName(ai.applicationInfo.packageName,
5583                            ai.name);
5584                } else {
5585                    ai = getActivityInfo(comp, flags, userId);
5586                    if (ai == null) {
5587                        continue;
5588                    }
5589                }
5590
5591                // Look for any generic query activities that are duplicates
5592                // of this specific one, and remove them from the results.
5593                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5594                N = results.size();
5595                int j;
5596                for (j=specificsPos; j<N; j++) {
5597                    ResolveInfo sri = results.get(j);
5598                    if ((sri.activityInfo.name.equals(comp.getClassName())
5599                            && sri.activityInfo.applicationInfo.packageName.equals(
5600                                    comp.getPackageName()))
5601                        || (action != null && sri.filter.matchAction(action))) {
5602                        results.remove(j);
5603                        if (DEBUG_INTENT_MATCHING) Log.v(
5604                            TAG, "Removing duplicate item from " + j
5605                            + " due to specific " + specificsPos);
5606                        if (ri == null) {
5607                            ri = sri;
5608                        }
5609                        j--;
5610                        N--;
5611                    }
5612                }
5613
5614                // Add this specific item to its proper place.
5615                if (ri == null) {
5616                    ri = new ResolveInfo();
5617                    ri.activityInfo = ai;
5618                }
5619                results.add(specificsPos, ri);
5620                ri.specificIndex = i;
5621                specificsPos++;
5622            }
5623        }
5624
5625        // Now we go through the remaining generic results and remove any
5626        // duplicate actions that are found here.
5627        N = results.size();
5628        for (int i=specificsPos; i<N-1; i++) {
5629            final ResolveInfo rii = results.get(i);
5630            if (rii.filter == null) {
5631                continue;
5632            }
5633
5634            // Iterate over all of the actions of this result's intent
5635            // filter...  typically this should be just one.
5636            final Iterator<String> it = rii.filter.actionsIterator();
5637            if (it == null) {
5638                continue;
5639            }
5640            while (it.hasNext()) {
5641                final String action = it.next();
5642                if (resultsAction != null && resultsAction.equals(action)) {
5643                    // If this action was explicitly requested, then don't
5644                    // remove things that have it.
5645                    continue;
5646                }
5647                for (int j=i+1; j<N; j++) {
5648                    final ResolveInfo rij = results.get(j);
5649                    if (rij.filter != null && rij.filter.hasAction(action)) {
5650                        results.remove(j);
5651                        if (DEBUG_INTENT_MATCHING) Log.v(
5652                            TAG, "Removing duplicate item from " + j
5653                            + " due to action " + action + " at " + i);
5654                        j--;
5655                        N--;
5656                    }
5657                }
5658            }
5659
5660            // If the caller didn't request filter information, drop it now
5661            // so we don't have to marshall/unmarshall it.
5662            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5663                rii.filter = null;
5664            }
5665        }
5666
5667        // Filter out the caller activity if so requested.
5668        if (caller != null) {
5669            N = results.size();
5670            for (int i=0; i<N; i++) {
5671                ActivityInfo ainfo = results.get(i).activityInfo;
5672                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5673                        && caller.getClassName().equals(ainfo.name)) {
5674                    results.remove(i);
5675                    break;
5676                }
5677            }
5678        }
5679
5680        // If the caller didn't request filter information,
5681        // drop them now so we don't have to
5682        // marshall/unmarshall it.
5683        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5684            N = results.size();
5685            for (int i=0; i<N; i++) {
5686                results.get(i).filter = null;
5687            }
5688        }
5689
5690        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5691        return results;
5692    }
5693
5694    @Override
5695    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5696            int userId) {
5697        if (!sUserManager.exists(userId)) return Collections.emptyList();
5698        flags = updateFlagsForResolve(flags, userId, intent);
5699        ComponentName comp = intent.getComponent();
5700        if (comp == null) {
5701            if (intent.getSelector() != null) {
5702                intent = intent.getSelector();
5703                comp = intent.getComponent();
5704            }
5705        }
5706        if (comp != null) {
5707            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5708            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5709            if (ai != null) {
5710                ResolveInfo ri = new ResolveInfo();
5711                ri.activityInfo = ai;
5712                list.add(ri);
5713            }
5714            return list;
5715        }
5716
5717        // reader
5718        synchronized (mPackages) {
5719            String pkgName = intent.getPackage();
5720            if (pkgName == null) {
5721                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5722            }
5723            final PackageParser.Package pkg = mPackages.get(pkgName);
5724            if (pkg != null) {
5725                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5726                        userId);
5727            }
5728            return null;
5729        }
5730    }
5731
5732    @Override
5733    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5734        if (!sUserManager.exists(userId)) return null;
5735        flags = updateFlagsForResolve(flags, userId, intent);
5736        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5737        if (query != null) {
5738            if (query.size() >= 1) {
5739                // If there is more than one service with the same priority,
5740                // just arbitrarily pick the first one.
5741                return query.get(0);
5742            }
5743        }
5744        return null;
5745    }
5746
5747    @Override
5748    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5749            int userId) {
5750        if (!sUserManager.exists(userId)) return Collections.emptyList();
5751        flags = updateFlagsForResolve(flags, userId, intent);
5752        ComponentName comp = intent.getComponent();
5753        if (comp == null) {
5754            if (intent.getSelector() != null) {
5755                intent = intent.getSelector();
5756                comp = intent.getComponent();
5757            }
5758        }
5759        if (comp != null) {
5760            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5761            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5762            if (si != null) {
5763                final ResolveInfo ri = new ResolveInfo();
5764                ri.serviceInfo = si;
5765                list.add(ri);
5766            }
5767            return list;
5768        }
5769
5770        // reader
5771        synchronized (mPackages) {
5772            String pkgName = intent.getPackage();
5773            if (pkgName == null) {
5774                return mServices.queryIntent(intent, resolvedType, flags, userId);
5775            }
5776            final PackageParser.Package pkg = mPackages.get(pkgName);
5777            if (pkg != null) {
5778                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5779                        userId);
5780            }
5781            return null;
5782        }
5783    }
5784
5785    @Override
5786    public List<ResolveInfo> queryIntentContentProviders(
5787            Intent intent, String resolvedType, int flags, int userId) {
5788        if (!sUserManager.exists(userId)) return Collections.emptyList();
5789        flags = updateFlagsForResolve(flags, userId, intent);
5790        ComponentName comp = intent.getComponent();
5791        if (comp == null) {
5792            if (intent.getSelector() != null) {
5793                intent = intent.getSelector();
5794                comp = intent.getComponent();
5795            }
5796        }
5797        if (comp != null) {
5798            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5799            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5800            if (pi != null) {
5801                final ResolveInfo ri = new ResolveInfo();
5802                ri.providerInfo = pi;
5803                list.add(ri);
5804            }
5805            return list;
5806        }
5807
5808        // reader
5809        synchronized (mPackages) {
5810            String pkgName = intent.getPackage();
5811            if (pkgName == null) {
5812                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5813            }
5814            final PackageParser.Package pkg = mPackages.get(pkgName);
5815            if (pkg != null) {
5816                return mProviders.queryIntentForPackage(
5817                        intent, resolvedType, flags, pkg.providers, userId);
5818            }
5819            return null;
5820        }
5821    }
5822
5823    @Override
5824    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5825        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5826        flags = updateFlagsForPackage(flags, userId, null);
5827        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5828        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5829
5830        // writer
5831        synchronized (mPackages) {
5832            ArrayList<PackageInfo> list;
5833            if (listUninstalled) {
5834                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5835                for (PackageSetting ps : mSettings.mPackages.values()) {
5836                    PackageInfo pi;
5837                    if (ps.pkg != null) {
5838                        pi = generatePackageInfo(ps.pkg, flags, userId);
5839                    } else {
5840                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5841                    }
5842                    if (pi != null) {
5843                        list.add(pi);
5844                    }
5845                }
5846            } else {
5847                list = new ArrayList<PackageInfo>(mPackages.size());
5848                for (PackageParser.Package p : mPackages.values()) {
5849                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5850                    if (pi != null) {
5851                        list.add(pi);
5852                    }
5853                }
5854            }
5855
5856            return new ParceledListSlice<PackageInfo>(list);
5857        }
5858    }
5859
5860    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5861            String[] permissions, boolean[] tmp, int flags, int userId) {
5862        int numMatch = 0;
5863        final PermissionsState permissionsState = ps.getPermissionsState();
5864        for (int i=0; i<permissions.length; i++) {
5865            final String permission = permissions[i];
5866            if (permissionsState.hasPermission(permission, userId)) {
5867                tmp[i] = true;
5868                numMatch++;
5869            } else {
5870                tmp[i] = false;
5871            }
5872        }
5873        if (numMatch == 0) {
5874            return;
5875        }
5876        PackageInfo pi;
5877        if (ps.pkg != null) {
5878            pi = generatePackageInfo(ps.pkg, flags, userId);
5879        } else {
5880            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5881        }
5882        // The above might return null in cases of uninstalled apps or install-state
5883        // skew across users/profiles.
5884        if (pi != null) {
5885            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5886                if (numMatch == permissions.length) {
5887                    pi.requestedPermissions = permissions;
5888                } else {
5889                    pi.requestedPermissions = new String[numMatch];
5890                    numMatch = 0;
5891                    for (int i=0; i<permissions.length; i++) {
5892                        if (tmp[i]) {
5893                            pi.requestedPermissions[numMatch] = permissions[i];
5894                            numMatch++;
5895                        }
5896                    }
5897                }
5898            }
5899            list.add(pi);
5900        }
5901    }
5902
5903    @Override
5904    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5905            String[] permissions, int flags, int userId) {
5906        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5907        flags = updateFlagsForPackage(flags, userId, permissions);
5908        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5909
5910        // writer
5911        synchronized (mPackages) {
5912            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5913            boolean[] tmpBools = new boolean[permissions.length];
5914            if (listUninstalled) {
5915                for (PackageSetting ps : mSettings.mPackages.values()) {
5916                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5917                }
5918            } else {
5919                for (PackageParser.Package pkg : mPackages.values()) {
5920                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5921                    if (ps != null) {
5922                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5923                                userId);
5924                    }
5925                }
5926            }
5927
5928            return new ParceledListSlice<PackageInfo>(list);
5929        }
5930    }
5931
5932    @Override
5933    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5934        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5935        flags = updateFlagsForApplication(flags, userId, null);
5936        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5937
5938        // writer
5939        synchronized (mPackages) {
5940            ArrayList<ApplicationInfo> list;
5941            if (listUninstalled) {
5942                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5943                for (PackageSetting ps : mSettings.mPackages.values()) {
5944                    ApplicationInfo ai;
5945                    if (ps.pkg != null) {
5946                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5947                                ps.readUserState(userId), userId);
5948                    } else {
5949                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5950                    }
5951                    if (ai != null) {
5952                        list.add(ai);
5953                    }
5954                }
5955            } else {
5956                list = new ArrayList<ApplicationInfo>(mPackages.size());
5957                for (PackageParser.Package p : mPackages.values()) {
5958                    if (p.mExtras != null) {
5959                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5960                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5961                        if (ai != null) {
5962                            list.add(ai);
5963                        }
5964                    }
5965                }
5966            }
5967
5968            return new ParceledListSlice<ApplicationInfo>(list);
5969        }
5970    }
5971
5972    @Override
5973    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5974        if (DISABLE_EPHEMERAL_APPS) {
5975            return null;
5976        }
5977
5978        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5979                "getEphemeralApplications");
5980        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5981                "getEphemeralApplications");
5982        synchronized (mPackages) {
5983            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5984                    .getEphemeralApplicationsLPw(userId);
5985            if (ephemeralApps != null) {
5986                return new ParceledListSlice<>(ephemeralApps);
5987            }
5988        }
5989        return null;
5990    }
5991
5992    @Override
5993    public boolean isEphemeralApplication(String packageName, int userId) {
5994        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5995                "isEphemeral");
5996        if (DISABLE_EPHEMERAL_APPS) {
5997            return false;
5998        }
5999
6000        if (!isCallerSameApp(packageName)) {
6001            return false;
6002        }
6003        synchronized (mPackages) {
6004            PackageParser.Package pkg = mPackages.get(packageName);
6005            if (pkg != null) {
6006                return pkg.applicationInfo.isEphemeralApp();
6007            }
6008        }
6009        return false;
6010    }
6011
6012    @Override
6013    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6014        if (DISABLE_EPHEMERAL_APPS) {
6015            return null;
6016        }
6017
6018        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6019                "getCookie");
6020        if (!isCallerSameApp(packageName)) {
6021            return null;
6022        }
6023        synchronized (mPackages) {
6024            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6025                    packageName, userId);
6026        }
6027    }
6028
6029    @Override
6030    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6031        if (DISABLE_EPHEMERAL_APPS) {
6032            return true;
6033        }
6034
6035        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6036                "setCookie");
6037        if (!isCallerSameApp(packageName)) {
6038            return false;
6039        }
6040        synchronized (mPackages) {
6041            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6042                    packageName, cookie, userId);
6043        }
6044    }
6045
6046    @Override
6047    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6048        if (DISABLE_EPHEMERAL_APPS) {
6049            return null;
6050        }
6051
6052        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6053                "getEphemeralApplicationIcon");
6054        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6055                "getEphemeralApplicationIcon");
6056        synchronized (mPackages) {
6057            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6058                    packageName, userId);
6059        }
6060    }
6061
6062    private boolean isCallerSameApp(String packageName) {
6063        PackageParser.Package pkg = mPackages.get(packageName);
6064        return pkg != null
6065                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6066    }
6067
6068    public List<ApplicationInfo> getPersistentApplications(int flags) {
6069        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6070
6071        // reader
6072        synchronized (mPackages) {
6073            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6074            final int userId = UserHandle.getCallingUserId();
6075            while (i.hasNext()) {
6076                final PackageParser.Package p = i.next();
6077                if (p.applicationInfo != null
6078                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6079                        && (!mSafeMode || isSystemApp(p))) {
6080                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6081                    if (ps != null) {
6082                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6083                                ps.readUserState(userId), userId);
6084                        if (ai != null) {
6085                            finalList.add(ai);
6086                        }
6087                    }
6088                }
6089            }
6090        }
6091
6092        return finalList;
6093    }
6094
6095    @Override
6096    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6097        if (!sUserManager.exists(userId)) return null;
6098        flags = updateFlagsForComponent(flags, userId, name);
6099        // reader
6100        synchronized (mPackages) {
6101            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6102            PackageSetting ps = provider != null
6103                    ? mSettings.mPackages.get(provider.owner.packageName)
6104                    : null;
6105            return ps != null
6106                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6107                    ? PackageParser.generateProviderInfo(provider, flags,
6108                            ps.readUserState(userId), userId)
6109                    : null;
6110        }
6111    }
6112
6113    /**
6114     * @deprecated
6115     */
6116    @Deprecated
6117    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6118        // reader
6119        synchronized (mPackages) {
6120            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6121                    .entrySet().iterator();
6122            final int userId = UserHandle.getCallingUserId();
6123            while (i.hasNext()) {
6124                Map.Entry<String, PackageParser.Provider> entry = i.next();
6125                PackageParser.Provider p = entry.getValue();
6126                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6127
6128                if (ps != null && p.syncable
6129                        && (!mSafeMode || (p.info.applicationInfo.flags
6130                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6131                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6132                            ps.readUserState(userId), userId);
6133                    if (info != null) {
6134                        outNames.add(entry.getKey());
6135                        outInfo.add(info);
6136                    }
6137                }
6138            }
6139        }
6140    }
6141
6142    @Override
6143    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6144            int uid, int flags) {
6145        final int userId = processName != null ? UserHandle.getUserId(uid)
6146                : UserHandle.getCallingUserId();
6147        if (!sUserManager.exists(userId)) return null;
6148        flags = updateFlagsForComponent(flags, userId, processName);
6149
6150        ArrayList<ProviderInfo> finalList = null;
6151        // reader
6152        synchronized (mPackages) {
6153            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6154            while (i.hasNext()) {
6155                final PackageParser.Provider p = i.next();
6156                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6157                if (ps != null && p.info.authority != null
6158                        && (processName == null
6159                                || (p.info.processName.equals(processName)
6160                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6161                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6162                    if (finalList == null) {
6163                        finalList = new ArrayList<ProviderInfo>(3);
6164                    }
6165                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6166                            ps.readUserState(userId), userId);
6167                    if (info != null) {
6168                        finalList.add(info);
6169                    }
6170                }
6171            }
6172        }
6173
6174        if (finalList != null) {
6175            Collections.sort(finalList, mProviderInitOrderSorter);
6176            return new ParceledListSlice<ProviderInfo>(finalList);
6177        }
6178
6179        return null;
6180    }
6181
6182    @Override
6183    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6184        // reader
6185        synchronized (mPackages) {
6186            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6187            return PackageParser.generateInstrumentationInfo(i, flags);
6188        }
6189    }
6190
6191    @Override
6192    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6193            int flags) {
6194        ArrayList<InstrumentationInfo> finalList =
6195            new ArrayList<InstrumentationInfo>();
6196
6197        // reader
6198        synchronized (mPackages) {
6199            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6200            while (i.hasNext()) {
6201                final PackageParser.Instrumentation p = i.next();
6202                if (targetPackage == null
6203                        || targetPackage.equals(p.info.targetPackage)) {
6204                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6205                            flags);
6206                    if (ii != null) {
6207                        finalList.add(ii);
6208                    }
6209                }
6210            }
6211        }
6212
6213        return finalList;
6214    }
6215
6216    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6217        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6218        if (overlays == null) {
6219            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6220            return;
6221        }
6222        for (PackageParser.Package opkg : overlays.values()) {
6223            // Not much to do if idmap fails: we already logged the error
6224            // and we certainly don't want to abort installation of pkg simply
6225            // because an overlay didn't fit properly. For these reasons,
6226            // ignore the return value of createIdmapForPackagePairLI.
6227            createIdmapForPackagePairLI(pkg, opkg);
6228        }
6229    }
6230
6231    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6232            PackageParser.Package opkg) {
6233        if (!opkg.mTrustedOverlay) {
6234            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6235                    opkg.baseCodePath + ": overlay not trusted");
6236            return false;
6237        }
6238        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6239        if (overlaySet == null) {
6240            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6241                    opkg.baseCodePath + " but target package has no known overlays");
6242            return false;
6243        }
6244        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6245        // TODO: generate idmap for split APKs
6246        try {
6247            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6248        } catch (InstallerException e) {
6249            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6250                    + opkg.baseCodePath);
6251            return false;
6252        }
6253        PackageParser.Package[] overlayArray =
6254            overlaySet.values().toArray(new PackageParser.Package[0]);
6255        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6256            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6257                return p1.mOverlayPriority - p2.mOverlayPriority;
6258            }
6259        };
6260        Arrays.sort(overlayArray, cmp);
6261
6262        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6263        int i = 0;
6264        for (PackageParser.Package p : overlayArray) {
6265            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6266        }
6267        return true;
6268    }
6269
6270    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6271        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6272        try {
6273            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6274        } finally {
6275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6276        }
6277    }
6278
6279    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6280        final File[] files = dir.listFiles();
6281        if (ArrayUtils.isEmpty(files)) {
6282            Log.d(TAG, "No files in app dir " + dir);
6283            return;
6284        }
6285
6286        if (DEBUG_PACKAGE_SCANNING) {
6287            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6288                    + " flags=0x" + Integer.toHexString(parseFlags));
6289        }
6290
6291        for (File file : files) {
6292            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6293                    && !PackageInstallerService.isStageName(file.getName());
6294            if (!isPackage) {
6295                // Ignore entries which are not packages
6296                continue;
6297            }
6298            try {
6299                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6300                        scanFlags, currentTime, null);
6301            } catch (PackageManagerException e) {
6302                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6303
6304                // Delete invalid userdata apps
6305                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6306                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6307                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6308                    removeCodePathLI(file);
6309                }
6310            }
6311        }
6312    }
6313
6314    private static File getSettingsProblemFile() {
6315        File dataDir = Environment.getDataDirectory();
6316        File systemDir = new File(dataDir, "system");
6317        File fname = new File(systemDir, "uiderrors.txt");
6318        return fname;
6319    }
6320
6321    static void reportSettingsProblem(int priority, String msg) {
6322        logCriticalInfo(priority, msg);
6323    }
6324
6325    static void logCriticalInfo(int priority, String msg) {
6326        Slog.println(priority, TAG, msg);
6327        EventLogTags.writePmCriticalInfo(msg);
6328        try {
6329            File fname = getSettingsProblemFile();
6330            FileOutputStream out = new FileOutputStream(fname, true);
6331            PrintWriter pw = new FastPrintWriter(out);
6332            SimpleDateFormat formatter = new SimpleDateFormat();
6333            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6334            pw.println(dateString + ": " + msg);
6335            pw.close();
6336            FileUtils.setPermissions(
6337                    fname.toString(),
6338                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6339                    -1, -1);
6340        } catch (java.io.IOException e) {
6341        }
6342    }
6343
6344    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6345            int parseFlags) throws PackageManagerException {
6346        if (ps != null
6347                && ps.codePath.equals(srcFile)
6348                && ps.timeStamp == srcFile.lastModified()
6349                && !isCompatSignatureUpdateNeeded(pkg)
6350                && !isRecoverSignatureUpdateNeeded(pkg)) {
6351            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6352            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6353            ArraySet<PublicKey> signingKs;
6354            synchronized (mPackages) {
6355                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6356            }
6357            if (ps.signatures.mSignatures != null
6358                    && ps.signatures.mSignatures.length != 0
6359                    && signingKs != null) {
6360                // Optimization: reuse the existing cached certificates
6361                // if the package appears to be unchanged.
6362                pkg.mSignatures = ps.signatures.mSignatures;
6363                pkg.mSigningKeys = signingKs;
6364                return;
6365            }
6366
6367            Slog.w(TAG, "PackageSetting for " + ps.name
6368                    + " is missing signatures.  Collecting certs again to recover them.");
6369        } else {
6370            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6371        }
6372
6373        try {
6374            PackageParser.collectCertificates(pkg, parseFlags);
6375        } catch (PackageParserException e) {
6376            throw PackageManagerException.from(e);
6377        }
6378    }
6379
6380    /**
6381     *  Traces a package scan.
6382     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6383     */
6384    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6385            long currentTime, UserHandle user) throws PackageManagerException {
6386        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6387        try {
6388            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6389        } finally {
6390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6391        }
6392    }
6393
6394    /**
6395     *  Scans a package and returns the newly parsed package.
6396     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6397     */
6398    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6399            long currentTime, UserHandle user) throws PackageManagerException {
6400        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6401        parseFlags |= mDefParseFlags;
6402        PackageParser pp = new PackageParser();
6403        pp.setSeparateProcesses(mSeparateProcesses);
6404        pp.setOnlyCoreApps(mOnlyCore);
6405        pp.setDisplayMetrics(mMetrics);
6406
6407        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6408            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6409        }
6410
6411        final PackageParser.Package pkg;
6412        try {
6413            pkg = pp.parsePackage(scanFile, parseFlags);
6414        } catch (PackageParserException e) {
6415            throw PackageManagerException.from(e);
6416        }
6417
6418        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6419    }
6420
6421    /**
6422     *  Scans a package and returns the newly parsed package.
6423     *  @throws PackageManagerException on a parse error.
6424     */
6425    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6426            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6427            throws PackageManagerException {
6428        // If the package has children and this is the first dive in the function
6429        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6430        // packages (parent and children) would be successfully scanned before the
6431        // actual scan since scanning mutates internal state and we want to atomically
6432        // install the package and its children.
6433        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6434            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6435                scanFlags |= SCAN_CHECK_ONLY;
6436            }
6437        } else {
6438            scanFlags &= ~SCAN_CHECK_ONLY;
6439        }
6440
6441        // Scan the parent
6442        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6443                scanFlags, currentTime, user);
6444
6445        // Scan the children
6446        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6447        for (int i = 0; i < childCount; i++) {
6448            PackageParser.Package childPackage = pkg.childPackages.get(i);
6449            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6450                    currentTime, user);
6451        }
6452
6453
6454        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6455            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6456        }
6457
6458        return scannedPkg;
6459    }
6460
6461    /**
6462     *  Scans a package and returns the newly parsed package.
6463     *  @throws PackageManagerException on a parse error.
6464     */
6465    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6466            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6467            throws PackageManagerException {
6468        PackageSetting ps = null;
6469        PackageSetting updatedPkg;
6470        // reader
6471        synchronized (mPackages) {
6472            // Look to see if we already know about this package.
6473            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6474            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6475                // This package has been renamed to its original name.  Let's
6476                // use that.
6477                ps = mSettings.peekPackageLPr(oldName);
6478            }
6479            // If there was no original package, see one for the real package name.
6480            if (ps == null) {
6481                ps = mSettings.peekPackageLPr(pkg.packageName);
6482            }
6483            // Check to see if this package could be hiding/updating a system
6484            // package.  Must look for it either under the original or real
6485            // package name depending on our state.
6486            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6487            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6488
6489            // If this is a package we don't know about on the system partition, we
6490            // may need to remove disabled child packages on the system partition
6491            // or may need to not add child packages if the parent apk is updated
6492            // on the data partition and no longer defines this child package.
6493            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6494                // If this is a parent package for an updated system app and this system
6495                // app got an OTA update which no longer defines some of the child packages
6496                // we have to prune them from the disabled system packages.
6497                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6498                if (disabledPs != null) {
6499                    final int scannedChildCount = (pkg.childPackages != null)
6500                            ? pkg.childPackages.size() : 0;
6501                    final int disabledChildCount = disabledPs.childPackageNames != null
6502                            ? disabledPs.childPackageNames.size() : 0;
6503                    for (int i = 0; i < disabledChildCount; i++) {
6504                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6505                        boolean disabledPackageAvailable = false;
6506                        for (int j = 0; j < scannedChildCount; j++) {
6507                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6508                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6509                                disabledPackageAvailable = true;
6510                                break;
6511                            }
6512                         }
6513                         if (!disabledPackageAvailable) {
6514                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6515                         }
6516                    }
6517                }
6518            }
6519        }
6520
6521        boolean updatedPkgBetter = false;
6522        // First check if this is a system package that may involve an update
6523        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6524            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6525            // it needs to drop FLAG_PRIVILEGED.
6526            if (locationIsPrivileged(scanFile)) {
6527                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6528            } else {
6529                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6530            }
6531
6532            if (ps != null && !ps.codePath.equals(scanFile)) {
6533                // The path has changed from what was last scanned...  check the
6534                // version of the new path against what we have stored to determine
6535                // what to do.
6536                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6537                if (pkg.mVersionCode <= ps.versionCode) {
6538                    // The system package has been updated and the code path does not match
6539                    // Ignore entry. Skip it.
6540                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6541                            + " ignored: updated version " + ps.versionCode
6542                            + " better than this " + pkg.mVersionCode);
6543                    if (!updatedPkg.codePath.equals(scanFile)) {
6544                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6545                                + ps.name + " changing from " + updatedPkg.codePathString
6546                                + " to " + scanFile);
6547                        updatedPkg.codePath = scanFile;
6548                        updatedPkg.codePathString = scanFile.toString();
6549                        updatedPkg.resourcePath = scanFile;
6550                        updatedPkg.resourcePathString = scanFile.toString();
6551                    }
6552                    updatedPkg.pkg = pkg;
6553                    updatedPkg.versionCode = pkg.mVersionCode;
6554
6555                    // Update the disabled system child packages to point to the package too.
6556                    final int childCount = updatedPkg.childPackageNames != null
6557                            ? updatedPkg.childPackageNames.size() : 0;
6558                    for (int i = 0; i < childCount; i++) {
6559                        String childPackageName = updatedPkg.childPackageNames.get(i);
6560                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6561                                childPackageName);
6562                        if (updatedChildPkg != null) {
6563                            updatedChildPkg.pkg = pkg;
6564                            updatedChildPkg.versionCode = pkg.mVersionCode;
6565                        }
6566                    }
6567
6568                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6569                            + scanFile + " ignored: updated version " + ps.versionCode
6570                            + " better than this " + pkg.mVersionCode);
6571                } else {
6572                    // The current app on the system partition is better than
6573                    // what we have updated to on the data partition; switch
6574                    // back to the system partition version.
6575                    // At this point, its safely assumed that package installation for
6576                    // apps in system partition will go through. If not there won't be a working
6577                    // version of the app
6578                    // writer
6579                    synchronized (mPackages) {
6580                        // Just remove the loaded entries from package lists.
6581                        mPackages.remove(ps.name);
6582                    }
6583
6584                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6585                            + " reverting from " + ps.codePathString
6586                            + ": new version " + pkg.mVersionCode
6587                            + " better than installed " + ps.versionCode);
6588
6589                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6590                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6591                    synchronized (mInstallLock) {
6592                        args.cleanUpResourcesLI();
6593                    }
6594                    synchronized (mPackages) {
6595                        mSettings.enableSystemPackageLPw(ps.name);
6596                    }
6597                    updatedPkgBetter = true;
6598                }
6599            }
6600        }
6601
6602        if (updatedPkg != null) {
6603            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6604            // initially
6605            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6606
6607            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6608            // flag set initially
6609            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6610                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6611            }
6612        }
6613
6614        // Verify certificates against what was last scanned
6615        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6616
6617        /*
6618         * A new system app appeared, but we already had a non-system one of the
6619         * same name installed earlier.
6620         */
6621        boolean shouldHideSystemApp = false;
6622        if (updatedPkg == null && ps != null
6623                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6624            /*
6625             * Check to make sure the signatures match first. If they don't,
6626             * wipe the installed application and its data.
6627             */
6628            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6629                    != PackageManager.SIGNATURE_MATCH) {
6630                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6631                        + " signatures don't match existing userdata copy; removing");
6632                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6633                ps = null;
6634            } else {
6635                /*
6636                 * If the newly-added system app is an older version than the
6637                 * already installed version, hide it. It will be scanned later
6638                 * and re-added like an update.
6639                 */
6640                if (pkg.mVersionCode <= ps.versionCode) {
6641                    shouldHideSystemApp = true;
6642                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6643                            + " but new version " + pkg.mVersionCode + " better than installed "
6644                            + ps.versionCode + "; hiding system");
6645                } else {
6646                    /*
6647                     * The newly found system app is a newer version that the
6648                     * one previously installed. Simply remove the
6649                     * already-installed application and replace it with our own
6650                     * while keeping the application data.
6651                     */
6652                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6653                            + " reverting from " + ps.codePathString + ": new version "
6654                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6655                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6656                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6657                    synchronized (mInstallLock) {
6658                        args.cleanUpResourcesLI();
6659                    }
6660                }
6661            }
6662        }
6663
6664        // The apk is forward locked (not public) if its code and resources
6665        // are kept in different files. (except for app in either system or
6666        // vendor path).
6667        // TODO grab this value from PackageSettings
6668        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6669            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6670                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6671            }
6672        }
6673
6674        // TODO: extend to support forward-locked splits
6675        String resourcePath = null;
6676        String baseResourcePath = null;
6677        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6678            if (ps != null && ps.resourcePathString != null) {
6679                resourcePath = ps.resourcePathString;
6680                baseResourcePath = ps.resourcePathString;
6681            } else {
6682                // Should not happen at all. Just log an error.
6683                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6684            }
6685        } else {
6686            resourcePath = pkg.codePath;
6687            baseResourcePath = pkg.baseCodePath;
6688        }
6689
6690        // Set application objects path explicitly.
6691        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6692        pkg.setApplicationInfoCodePath(pkg.codePath);
6693        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6694        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6695        pkg.setApplicationInfoResourcePath(resourcePath);
6696        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6697        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6698
6699        // Note that we invoke the following method only if we are about to unpack an application
6700        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6701                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6702
6703        /*
6704         * If the system app should be overridden by a previously installed
6705         * data, hide the system app now and let the /data/app scan pick it up
6706         * again.
6707         */
6708        if (shouldHideSystemApp) {
6709            synchronized (mPackages) {
6710                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6711            }
6712        }
6713
6714        return scannedPkg;
6715    }
6716
6717    private static String fixProcessName(String defProcessName,
6718            String processName, int uid) {
6719        if (processName == null) {
6720            return defProcessName;
6721        }
6722        return processName;
6723    }
6724
6725    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6726            throws PackageManagerException {
6727        if (pkgSetting.signatures.mSignatures != null) {
6728            // Already existing package. Make sure signatures match
6729            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6730                    == PackageManager.SIGNATURE_MATCH;
6731            if (!match) {
6732                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6733                        == PackageManager.SIGNATURE_MATCH;
6734            }
6735            if (!match) {
6736                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6737                        == PackageManager.SIGNATURE_MATCH;
6738            }
6739            if (!match) {
6740                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6741                        + pkg.packageName + " signatures do not match the "
6742                        + "previously installed version; ignoring!");
6743            }
6744        }
6745
6746        // Check for shared user signatures
6747        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6748            // Already existing package. Make sure signatures match
6749            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6750                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6751            if (!match) {
6752                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6753                        == PackageManager.SIGNATURE_MATCH;
6754            }
6755            if (!match) {
6756                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6757                        == PackageManager.SIGNATURE_MATCH;
6758            }
6759            if (!match) {
6760                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6761                        "Package " + pkg.packageName
6762                        + " has no signatures that match those in shared user "
6763                        + pkgSetting.sharedUser.name + "; ignoring!");
6764            }
6765        }
6766    }
6767
6768    /**
6769     * Enforces that only the system UID or root's UID can call a method exposed
6770     * via Binder.
6771     *
6772     * @param message used as message if SecurityException is thrown
6773     * @throws SecurityException if the caller is not system or root
6774     */
6775    private static final void enforceSystemOrRoot(String message) {
6776        final int uid = Binder.getCallingUid();
6777        if (uid != Process.SYSTEM_UID && uid != 0) {
6778            throw new SecurityException(message);
6779        }
6780    }
6781
6782    @Override
6783    public void performFstrimIfNeeded() {
6784        enforceSystemOrRoot("Only the system can request fstrim");
6785
6786        // Before everything else, see whether we need to fstrim.
6787        try {
6788            IMountService ms = PackageHelper.getMountService();
6789            if (ms != null) {
6790                final boolean isUpgrade = isUpgrade();
6791                boolean doTrim = isUpgrade;
6792                if (doTrim) {
6793                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6794                } else {
6795                    final long interval = android.provider.Settings.Global.getLong(
6796                            mContext.getContentResolver(),
6797                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6798                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6799                    if (interval > 0) {
6800                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6801                        if (timeSinceLast > interval) {
6802                            doTrim = true;
6803                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6804                                    + "; running immediately");
6805                        }
6806                    }
6807                }
6808                if (doTrim) {
6809                    if (!isFirstBoot()) {
6810                        try {
6811                            ActivityManagerNative.getDefault().showBootMessage(
6812                                    mContext.getResources().getString(
6813                                            R.string.android_upgrading_fstrim), true);
6814                        } catch (RemoteException e) {
6815                        }
6816                    }
6817                    ms.runMaintenance();
6818                }
6819            } else {
6820                Slog.e(TAG, "Mount service unavailable!");
6821            }
6822        } catch (RemoteException e) {
6823            // Can't happen; MountService is local
6824        }
6825    }
6826
6827    @Override
6828    public void extractPackagesIfNeeded() {
6829        enforceSystemOrRoot("Only the system can request package extraction");
6830
6831        // Extract pacakges only if profile-guided compilation is enabled because
6832        // otherwise BackgroundDexOptService will not dexopt them later.
6833        if (!mUseJitProfiles || !isUpgrade()) {
6834            return;
6835        }
6836
6837        List<PackageParser.Package> pkgs;
6838        synchronized (mPackages) {
6839            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6840        }
6841
6842        int curr = 0;
6843        int total = pkgs.size();
6844        for (PackageParser.Package pkg : pkgs) {
6845            curr++;
6846
6847            if (DEBUG_DEXOPT) {
6848                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6849            }
6850
6851            if (!isFirstBoot()) {
6852                try {
6853                    ActivityManagerNative.getDefault().showBootMessage(
6854                            mContext.getResources().getString(R.string.android_upgrading_apk,
6855                                    curr, total), true);
6856                } catch (RemoteException e) {
6857                }
6858            }
6859
6860            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6861                performDexOpt(pkg.packageName, null /* instructionSet */,
6862                         false /* useProfiles */, true /* extractOnly */, false /* force */);
6863            }
6864        }
6865    }
6866
6867    @Override
6868    public void notifyPackageUse(String packageName) {
6869        synchronized (mPackages) {
6870            PackageParser.Package p = mPackages.get(packageName);
6871            if (p == null) {
6872                return;
6873            }
6874            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6875        }
6876    }
6877
6878    // TODO: this is not used nor needed. Delete it.
6879    @Override
6880    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6881        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6882                false /* extractOnly */, false /* force */);
6883    }
6884
6885    @Override
6886    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6887            boolean extractOnly, boolean force) {
6888        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6889    }
6890
6891    private boolean performDexOptTraced(String packageName, String instructionSet,
6892                boolean useProfiles, boolean extractOnly, boolean force) {
6893        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6894        try {
6895            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6896                    force);
6897        } finally {
6898            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6899        }
6900    }
6901
6902    private boolean performDexOptInternal(String packageName, String instructionSet,
6903                boolean useProfiles, boolean extractOnly, boolean force) {
6904        PackageParser.Package p;
6905        final String targetInstructionSet;
6906        synchronized (mPackages) {
6907            p = mPackages.get(packageName);
6908            if (p == null) {
6909                return false;
6910            }
6911            mPackageUsage.write(false);
6912
6913            targetInstructionSet = instructionSet != null ? instructionSet :
6914                    getPrimaryInstructionSet(p.applicationInfo);
6915            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6916                // Skip only if we do not use profiles since they might trigger a recompilation.
6917                return false;
6918            }
6919        }
6920        long callingId = Binder.clearCallingIdentity();
6921        try {
6922            synchronized (mInstallLock) {
6923                final String[] instructionSets = new String[] { targetInstructionSet };
6924                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6925                        useProfiles, extractOnly, force);
6926                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6927            }
6928        } finally {
6929            Binder.restoreCallingIdentity(callingId);
6930        }
6931    }
6932
6933    public ArraySet<String> getOptimizablePackages() {
6934        ArraySet<String> pkgs = new ArraySet<String>();
6935        synchronized (mPackages) {
6936            for (PackageParser.Package p : mPackages.values()) {
6937                if (PackageDexOptimizer.canOptimizePackage(p)) {
6938                    pkgs.add(p.packageName);
6939                }
6940            }
6941        }
6942        return pkgs;
6943    }
6944
6945    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6946            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6947        // Select the dex optimizer based on the force parameter.
6948        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6949        //       allocate an object here.
6950        PackageDexOptimizer pdo = force
6951                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6952                : mPackageDexOptimizer;
6953
6954        // Optimize all dependencies first. Note: we ignore the return value and march on
6955        // on errors.
6956        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6957        if (!deps.isEmpty()) {
6958            for (PackageParser.Package depPackage : deps) {
6959                // TODO: Analyze and investigate if we (should) profile libraries.
6960                // Currently this will do a full compilation of the library.
6961                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6962                        false /* extractOnly */);
6963            }
6964        }
6965
6966        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6967    }
6968
6969    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6970        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6971            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6972            Set<String> collectedNames = new HashSet<>();
6973            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6974
6975            retValue.remove(p);
6976
6977            return retValue;
6978        } else {
6979            return Collections.emptyList();
6980        }
6981    }
6982
6983    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6984            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6985        if (!collectedNames.contains(p.packageName)) {
6986            collectedNames.add(p.packageName);
6987            collected.add(p);
6988
6989            if (p.usesLibraries != null) {
6990                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6991            }
6992            if (p.usesOptionalLibraries != null) {
6993                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6994                        collectedNames);
6995            }
6996        }
6997    }
6998
6999    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7000            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7001        for (String libName : libs) {
7002            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7003            if (libPkg != null) {
7004                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7005            }
7006        }
7007    }
7008
7009    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7010        synchronized (mPackages) {
7011            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7012            if (lib != null && lib.apk != null) {
7013                return mPackages.get(lib.apk);
7014            }
7015        }
7016        return null;
7017    }
7018
7019    public void shutdown() {
7020        mPackageUsage.write(true);
7021    }
7022
7023    @Override
7024    public void forceDexOpt(String packageName) {
7025        enforceSystemOrRoot("forceDexOpt");
7026
7027        PackageParser.Package pkg;
7028        synchronized (mPackages) {
7029            pkg = mPackages.get(packageName);
7030            if (pkg == null) {
7031                throw new IllegalArgumentException("Unknown package: " + packageName);
7032            }
7033        }
7034
7035        synchronized (mInstallLock) {
7036            final String[] instructionSets = new String[] {
7037                    getPrimaryInstructionSet(pkg.applicationInfo) };
7038
7039            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7040
7041            // Whoever is calling forceDexOpt wants a fully compiled package.
7042            // Don't use profiles since that may cause compilation to be skipped.
7043            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7044                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7045
7046            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7047            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7048                throw new IllegalStateException("Failed to dexopt: " + res);
7049            }
7050        }
7051    }
7052
7053    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7054        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7055            Slog.w(TAG, "Unable to update from " + oldPkg.name
7056                    + " to " + newPkg.packageName
7057                    + ": old package not in system partition");
7058            return false;
7059        } else if (mPackages.get(oldPkg.name) != null) {
7060            Slog.w(TAG, "Unable to update from " + oldPkg.name
7061                    + " to " + newPkg.packageName
7062                    + ": old package still exists");
7063            return false;
7064        }
7065        return true;
7066    }
7067
7068    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7069        // TODO: triage flags as part of 26466827
7070        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7071
7072        boolean res = true;
7073        final int[] users = sUserManager.getUserIds();
7074        for (int user : users) {
7075            try {
7076                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7077            } catch (InstallerException e) {
7078                Slog.w(TAG, "Failed to delete data directory", e);
7079                res = false;
7080            }
7081        }
7082        return res;
7083    }
7084
7085    void removeCodePathLI(File codePath) {
7086        if (codePath.isDirectory()) {
7087            try {
7088                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7089            } catch (InstallerException e) {
7090                Slog.w(TAG, "Failed to remove code path", e);
7091            }
7092        } else {
7093            codePath.delete();
7094        }
7095    }
7096
7097    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7098        try {
7099            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7100        } catch (InstallerException e) {
7101            Slog.w(TAG, "Failed to destroy app data", e);
7102        }
7103    }
7104
7105    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7106            int appId, String seinfo) {
7107        try {
7108            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7109        } catch (InstallerException e) {
7110            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7111        }
7112    }
7113
7114    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7115        final PackageParser.Package pkg;
7116        synchronized (mPackages) {
7117            pkg = mPackages.get(packageName);
7118        }
7119        if (pkg == null) {
7120            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7121            return;
7122        }
7123        deleteCodeCacheDirsLI(pkg);
7124    }
7125
7126    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7127        // TODO: triage flags as part of 26466827
7128        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7129
7130        int[] users = sUserManager.getUserIds();
7131        int res = 0;
7132        for (int user : users) {
7133            // Remove the parent code cache
7134            try {
7135                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7136                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7137            } catch (InstallerException e) {
7138                Slog.w(TAG, "Failed to delete code cache directory", e);
7139            }
7140            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7141            for (int i = 0; i < childCount; i++) {
7142                PackageParser.Package childPkg = pkg.childPackages.get(i);
7143                // Remove the child code cache
7144                try {
7145                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7146                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7147                } catch (InstallerException e) {
7148                    Slog.w(TAG, "Failed to delete code cache directory", e);
7149                }
7150            }
7151        }
7152    }
7153
7154    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7155            long lastUpdateTime) {
7156        // Set parent install/update time
7157        PackageSetting ps = (PackageSetting) pkg.mExtras;
7158        if (ps != null) {
7159            ps.firstInstallTime = firstInstallTime;
7160            ps.lastUpdateTime = lastUpdateTime;
7161        }
7162        // Set children install/update time
7163        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7164        for (int i = 0; i < childCount; i++) {
7165            PackageParser.Package childPkg = pkg.childPackages.get(i);
7166            ps = (PackageSetting) childPkg.mExtras;
7167            if (ps != null) {
7168                ps.firstInstallTime = firstInstallTime;
7169                ps.lastUpdateTime = lastUpdateTime;
7170            }
7171        }
7172    }
7173
7174    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7175            PackageParser.Package changingLib) {
7176        if (file.path != null) {
7177            usesLibraryFiles.add(file.path);
7178            return;
7179        }
7180        PackageParser.Package p = mPackages.get(file.apk);
7181        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7182            // If we are doing this while in the middle of updating a library apk,
7183            // then we need to make sure to use that new apk for determining the
7184            // dependencies here.  (We haven't yet finished committing the new apk
7185            // to the package manager state.)
7186            if (p == null || p.packageName.equals(changingLib.packageName)) {
7187                p = changingLib;
7188            }
7189        }
7190        if (p != null) {
7191            usesLibraryFiles.addAll(p.getAllCodePaths());
7192        }
7193    }
7194
7195    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7196            PackageParser.Package changingLib) throws PackageManagerException {
7197        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7198            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7199            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7200            for (int i=0; i<N; i++) {
7201                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7202                if (file == null) {
7203                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7204                            "Package " + pkg.packageName + " requires unavailable shared library "
7205                            + pkg.usesLibraries.get(i) + "; failing!");
7206                }
7207                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7208            }
7209            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7210            for (int i=0; i<N; i++) {
7211                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7212                if (file == null) {
7213                    Slog.w(TAG, "Package " + pkg.packageName
7214                            + " desires unavailable shared library "
7215                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7216                } else {
7217                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7218                }
7219            }
7220            N = usesLibraryFiles.size();
7221            if (N > 0) {
7222                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7223            } else {
7224                pkg.usesLibraryFiles = null;
7225            }
7226        }
7227    }
7228
7229    private static boolean hasString(List<String> list, List<String> which) {
7230        if (list == null) {
7231            return false;
7232        }
7233        for (int i=list.size()-1; i>=0; i--) {
7234            for (int j=which.size()-1; j>=0; j--) {
7235                if (which.get(j).equals(list.get(i))) {
7236                    return true;
7237                }
7238            }
7239        }
7240        return false;
7241    }
7242
7243    private void updateAllSharedLibrariesLPw() {
7244        for (PackageParser.Package pkg : mPackages.values()) {
7245            try {
7246                updateSharedLibrariesLPw(pkg, null);
7247            } catch (PackageManagerException e) {
7248                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7249            }
7250        }
7251    }
7252
7253    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7254            PackageParser.Package changingPkg) {
7255        ArrayList<PackageParser.Package> res = null;
7256        for (PackageParser.Package pkg : mPackages.values()) {
7257            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7258                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7259                if (res == null) {
7260                    res = new ArrayList<PackageParser.Package>();
7261                }
7262                res.add(pkg);
7263                try {
7264                    updateSharedLibrariesLPw(pkg, changingPkg);
7265                } catch (PackageManagerException e) {
7266                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7267                }
7268            }
7269        }
7270        return res;
7271    }
7272
7273    /**
7274     * Derive the value of the {@code cpuAbiOverride} based on the provided
7275     * value and an optional stored value from the package settings.
7276     */
7277    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7278        String cpuAbiOverride = null;
7279
7280        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7281            cpuAbiOverride = null;
7282        } else if (abiOverride != null) {
7283            cpuAbiOverride = abiOverride;
7284        } else if (settings != null) {
7285            cpuAbiOverride = settings.cpuAbiOverrideString;
7286        }
7287
7288        return cpuAbiOverride;
7289    }
7290
7291    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7292            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7293        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7294        // If the package has children and this is the first dive in the function
7295        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7296        // whether all packages (parent and children) would be successfully scanned
7297        // before the actual scan since scanning mutates internal state and we want
7298        // to atomically install the package and its children.
7299        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7300            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7301                scanFlags |= SCAN_CHECK_ONLY;
7302            }
7303        } else {
7304            scanFlags &= ~SCAN_CHECK_ONLY;
7305        }
7306
7307        final PackageParser.Package scannedPkg;
7308        try {
7309            // Scan the parent
7310            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7311            // Scan the children
7312            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7313            for (int i = 0; i < childCount; i++) {
7314                PackageParser.Package childPkg = pkg.childPackages.get(i);
7315                scanPackageLI(childPkg, parseFlags,
7316                        scanFlags, currentTime, user);
7317            }
7318        } finally {
7319            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7320        }
7321
7322        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7323            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7324        }
7325
7326        return scannedPkg;
7327    }
7328
7329    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7330            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7331        boolean success = false;
7332        try {
7333            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7334                    currentTime, user);
7335            success = true;
7336            return res;
7337        } finally {
7338            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7339                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7340            }
7341        }
7342    }
7343
7344    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7345            int scanFlags, long currentTime, UserHandle user)
7346            throws PackageManagerException {
7347        final File scanFile = new File(pkg.codePath);
7348        if (pkg.applicationInfo.getCodePath() == null ||
7349                pkg.applicationInfo.getResourcePath() == null) {
7350            // Bail out. The resource and code paths haven't been set.
7351            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7352                    "Code and resource paths haven't been set correctly");
7353        }
7354
7355        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7356            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7357        } else {
7358            // Only allow system apps to be flagged as core apps.
7359            pkg.coreApp = false;
7360        }
7361
7362        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7363            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7364        }
7365
7366        if (mCustomResolverComponentName != null &&
7367                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7368            setUpCustomResolverActivity(pkg);
7369        }
7370
7371        if (pkg.packageName.equals("android")) {
7372            synchronized (mPackages) {
7373                if (mAndroidApplication != null) {
7374                    Slog.w(TAG, "*************************************************");
7375                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7376                    Slog.w(TAG, " file=" + scanFile);
7377                    Slog.w(TAG, "*************************************************");
7378                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7379                            "Core android package being redefined.  Skipping.");
7380                }
7381
7382                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7383                    // Set up information for our fall-back user intent resolution activity.
7384                    mPlatformPackage = pkg;
7385                    pkg.mVersionCode = mSdkVersion;
7386                    mAndroidApplication = pkg.applicationInfo;
7387
7388                    if (!mResolverReplaced) {
7389                        mResolveActivity.applicationInfo = mAndroidApplication;
7390                        mResolveActivity.name = ResolverActivity.class.getName();
7391                        mResolveActivity.packageName = mAndroidApplication.packageName;
7392                        mResolveActivity.processName = "system:ui";
7393                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7394                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7395                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7396                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7397                        mResolveActivity.exported = true;
7398                        mResolveActivity.enabled = true;
7399                        mResolveInfo.activityInfo = mResolveActivity;
7400                        mResolveInfo.priority = 0;
7401                        mResolveInfo.preferredOrder = 0;
7402                        mResolveInfo.match = 0;
7403                        mResolveComponentName = new ComponentName(
7404                                mAndroidApplication.packageName, mResolveActivity.name);
7405                    }
7406                }
7407            }
7408        }
7409
7410        if (DEBUG_PACKAGE_SCANNING) {
7411            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7412                Log.d(TAG, "Scanning package " + pkg.packageName);
7413        }
7414
7415        synchronized (mPackages) {
7416            if (mPackages.containsKey(pkg.packageName)
7417                    || mSharedLibraries.containsKey(pkg.packageName)) {
7418                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7419                        "Application package " + pkg.packageName
7420                                + " already installed.  Skipping duplicate.");
7421            }
7422
7423            // If we're only installing presumed-existing packages, require that the
7424            // scanned APK is both already known and at the path previously established
7425            // for it.  Previously unknown packages we pick up normally, but if we have an
7426            // a priori expectation about this package's install presence, enforce it.
7427            // With a singular exception for new system packages. When an OTA contains
7428            // a new system package, we allow the codepath to change from a system location
7429            // to the user-installed location. If we don't allow this change, any newer,
7430            // user-installed version of the application will be ignored.
7431            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7432                if (mExpectingBetter.containsKey(pkg.packageName)) {
7433                    logCriticalInfo(Log.WARN,
7434                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7435                } else {
7436                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7437                    if (known != null) {
7438                        if (DEBUG_PACKAGE_SCANNING) {
7439                            Log.d(TAG, "Examining " + pkg.codePath
7440                                    + " and requiring known paths " + known.codePathString
7441                                    + " & " + known.resourcePathString);
7442                        }
7443                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7444                                || !pkg.applicationInfo.getResourcePath().equals(
7445                                known.resourcePathString)) {
7446                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7447                                    "Application package " + pkg.packageName
7448                                            + " found at " + pkg.applicationInfo.getCodePath()
7449                                            + " but expected at " + known.codePathString
7450                                            + "; ignoring.");
7451                        }
7452                    }
7453                }
7454            }
7455        }
7456
7457        // Initialize package source and resource directories
7458        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7459        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7460
7461        SharedUserSetting suid = null;
7462        PackageSetting pkgSetting = null;
7463
7464        if (!isSystemApp(pkg)) {
7465            // Only system apps can use these features.
7466            pkg.mOriginalPackages = null;
7467            pkg.mRealPackage = null;
7468            pkg.mAdoptPermissions = null;
7469        }
7470
7471        // Getting the package setting may have a side-effect, so if we
7472        // are only checking if scan would succeed, stash a copy of the
7473        // old setting to restore at the end.
7474        PackageSetting nonMutatedPs = null;
7475
7476        // writer
7477        synchronized (mPackages) {
7478            if (pkg.mSharedUserId != null) {
7479                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7480                if (suid == null) {
7481                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7482                            "Creating application package " + pkg.packageName
7483                            + " for shared user failed");
7484                }
7485                if (DEBUG_PACKAGE_SCANNING) {
7486                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7487                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7488                                + "): packages=" + suid.packages);
7489                }
7490            }
7491
7492            // Check if we are renaming from an original package name.
7493            PackageSetting origPackage = null;
7494            String realName = null;
7495            if (pkg.mOriginalPackages != null) {
7496                // This package may need to be renamed to a previously
7497                // installed name.  Let's check on that...
7498                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7499                if (pkg.mOriginalPackages.contains(renamed)) {
7500                    // This package had originally been installed as the
7501                    // original name, and we have already taken care of
7502                    // transitioning to the new one.  Just update the new
7503                    // one to continue using the old name.
7504                    realName = pkg.mRealPackage;
7505                    if (!pkg.packageName.equals(renamed)) {
7506                        // Callers into this function may have already taken
7507                        // care of renaming the package; only do it here if
7508                        // it is not already done.
7509                        pkg.setPackageName(renamed);
7510                    }
7511
7512                } else {
7513                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7514                        if ((origPackage = mSettings.peekPackageLPr(
7515                                pkg.mOriginalPackages.get(i))) != null) {
7516                            // We do have the package already installed under its
7517                            // original name...  should we use it?
7518                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7519                                // New package is not compatible with original.
7520                                origPackage = null;
7521                                continue;
7522                            } else if (origPackage.sharedUser != null) {
7523                                // Make sure uid is compatible between packages.
7524                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7525                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7526                                            + " to " + pkg.packageName + ": old uid "
7527                                            + origPackage.sharedUser.name
7528                                            + " differs from " + pkg.mSharedUserId);
7529                                    origPackage = null;
7530                                    continue;
7531                                }
7532                            } else {
7533                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7534                                        + pkg.packageName + " to old name " + origPackage.name);
7535                            }
7536                            break;
7537                        }
7538                    }
7539                }
7540            }
7541
7542            if (mTransferedPackages.contains(pkg.packageName)) {
7543                Slog.w(TAG, "Package " + pkg.packageName
7544                        + " was transferred to another, but its .apk remains");
7545            }
7546
7547            // See comments in nonMutatedPs declaration
7548            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7549                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7550                if (foundPs != null) {
7551                    nonMutatedPs = new PackageSetting(foundPs);
7552                }
7553            }
7554
7555            // Just create the setting, don't add it yet. For already existing packages
7556            // the PkgSetting exists already and doesn't have to be created.
7557            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7558                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7559                    pkg.applicationInfo.primaryCpuAbi,
7560                    pkg.applicationInfo.secondaryCpuAbi,
7561                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7562                    user, false);
7563            if (pkgSetting == null) {
7564                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7565                        "Creating application package " + pkg.packageName + " failed");
7566            }
7567
7568            if (pkgSetting.origPackage != null) {
7569                // If we are first transitioning from an original package,
7570                // fix up the new package's name now.  We need to do this after
7571                // looking up the package under its new name, so getPackageLP
7572                // can take care of fiddling things correctly.
7573                pkg.setPackageName(origPackage.name);
7574
7575                // File a report about this.
7576                String msg = "New package " + pkgSetting.realName
7577                        + " renamed to replace old package " + pkgSetting.name;
7578                reportSettingsProblem(Log.WARN, msg);
7579
7580                // Make a note of it.
7581                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7582                    mTransferedPackages.add(origPackage.name);
7583                }
7584
7585                // No longer need to retain this.
7586                pkgSetting.origPackage = null;
7587            }
7588
7589            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7590                // Make a note of it.
7591                mTransferedPackages.add(pkg.packageName);
7592            }
7593
7594            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7595                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7596            }
7597
7598            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7599                // Check all shared libraries and map to their actual file path.
7600                // We only do this here for apps not on a system dir, because those
7601                // are the only ones that can fail an install due to this.  We
7602                // will take care of the system apps by updating all of their
7603                // library paths after the scan is done.
7604                updateSharedLibrariesLPw(pkg, null);
7605            }
7606
7607            if (mFoundPolicyFile) {
7608                SELinuxMMAC.assignSeinfoValue(pkg);
7609            }
7610
7611            pkg.applicationInfo.uid = pkgSetting.appId;
7612            pkg.mExtras = pkgSetting;
7613            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7614                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7615                    // We just determined the app is signed correctly, so bring
7616                    // over the latest parsed certs.
7617                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7618                } else {
7619                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7620                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7621                                "Package " + pkg.packageName + " upgrade keys do not match the "
7622                                + "previously installed version");
7623                    } else {
7624                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7625                        String msg = "System package " + pkg.packageName
7626                            + " signature changed; retaining data.";
7627                        reportSettingsProblem(Log.WARN, msg);
7628                    }
7629                }
7630            } else {
7631                try {
7632                    verifySignaturesLP(pkgSetting, pkg);
7633                    // We just determined the app is signed correctly, so bring
7634                    // over the latest parsed certs.
7635                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7636                } catch (PackageManagerException e) {
7637                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7638                        throw e;
7639                    }
7640                    // The signature has changed, but this package is in the system
7641                    // image...  let's recover!
7642                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7643                    // However...  if this package is part of a shared user, but it
7644                    // doesn't match the signature of the shared user, let's fail.
7645                    // What this means is that you can't change the signatures
7646                    // associated with an overall shared user, which doesn't seem all
7647                    // that unreasonable.
7648                    if (pkgSetting.sharedUser != null) {
7649                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7650                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7651                            throw new PackageManagerException(
7652                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7653                                            "Signature mismatch for shared user: "
7654                                            + pkgSetting.sharedUser);
7655                        }
7656                    }
7657                    // File a report about this.
7658                    String msg = "System package " + pkg.packageName
7659                        + " signature changed; retaining data.";
7660                    reportSettingsProblem(Log.WARN, msg);
7661                }
7662            }
7663            // Verify that this new package doesn't have any content providers
7664            // that conflict with existing packages.  Only do this if the
7665            // package isn't already installed, since we don't want to break
7666            // things that are installed.
7667            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7668                final int N = pkg.providers.size();
7669                int i;
7670                for (i=0; i<N; i++) {
7671                    PackageParser.Provider p = pkg.providers.get(i);
7672                    if (p.info.authority != null) {
7673                        String names[] = p.info.authority.split(";");
7674                        for (int j = 0; j < names.length; j++) {
7675                            if (mProvidersByAuthority.containsKey(names[j])) {
7676                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7677                                final String otherPackageName =
7678                                        ((other != null && other.getComponentName() != null) ?
7679                                                other.getComponentName().getPackageName() : "?");
7680                                throw new PackageManagerException(
7681                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7682                                                "Can't install because provider name " + names[j]
7683                                                + " (in package " + pkg.applicationInfo.packageName
7684                                                + ") is already used by " + otherPackageName);
7685                            }
7686                        }
7687                    }
7688                }
7689            }
7690
7691            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7692                // This package wants to adopt ownership of permissions from
7693                // another package.
7694                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7695                    final String origName = pkg.mAdoptPermissions.get(i);
7696                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7697                    if (orig != null) {
7698                        if (verifyPackageUpdateLPr(orig, pkg)) {
7699                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7700                                    + pkg.packageName);
7701                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7702                        }
7703                    }
7704                }
7705            }
7706        }
7707
7708        final String pkgName = pkg.packageName;
7709
7710        final long scanFileTime = scanFile.lastModified();
7711        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7712        pkg.applicationInfo.processName = fixProcessName(
7713                pkg.applicationInfo.packageName,
7714                pkg.applicationInfo.processName,
7715                pkg.applicationInfo.uid);
7716
7717        if (pkg != mPlatformPackage) {
7718            // Get all of our default paths setup
7719            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7720        }
7721
7722        final String path = scanFile.getPath();
7723        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7724
7725        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7726            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7727
7728            // Some system apps still use directory structure for native libraries
7729            // in which case we might end up not detecting abi solely based on apk
7730            // structure. Try to detect abi based on directory structure.
7731            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7732                    pkg.applicationInfo.primaryCpuAbi == null) {
7733                setBundledAppAbisAndRoots(pkg, pkgSetting);
7734                setNativeLibraryPaths(pkg);
7735            }
7736
7737        } else {
7738            if ((scanFlags & SCAN_MOVE) != 0) {
7739                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7740                // but we already have this packages package info in the PackageSetting. We just
7741                // use that and derive the native library path based on the new codepath.
7742                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7743                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7744            }
7745
7746            // Set native library paths again. For moves, the path will be updated based on the
7747            // ABIs we've determined above. For non-moves, the path will be updated based on the
7748            // ABIs we determined during compilation, but the path will depend on the final
7749            // package path (after the rename away from the stage path).
7750            setNativeLibraryPaths(pkg);
7751        }
7752
7753        // This is a special case for the "system" package, where the ABI is
7754        // dictated by the zygote configuration (and init.rc). We should keep track
7755        // of this ABI so that we can deal with "normal" applications that run under
7756        // the same UID correctly.
7757        if (mPlatformPackage == pkg) {
7758            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7759                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7760        }
7761
7762        // If there's a mismatch between the abi-override in the package setting
7763        // and the abiOverride specified for the install. Warn about this because we
7764        // would've already compiled the app without taking the package setting into
7765        // account.
7766        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7767            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7768                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7769                        " for package " + pkg.packageName);
7770            }
7771        }
7772
7773        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7774        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7775        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7776
7777        // Copy the derived override back to the parsed package, so that we can
7778        // update the package settings accordingly.
7779        pkg.cpuAbiOverride = cpuAbiOverride;
7780
7781        if (DEBUG_ABI_SELECTION) {
7782            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7783                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7784                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7785        }
7786
7787        // Push the derived path down into PackageSettings so we know what to
7788        // clean up at uninstall time.
7789        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7790
7791        if (DEBUG_ABI_SELECTION) {
7792            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7793                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7794                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7795        }
7796
7797        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7798            // We don't do this here during boot because we can do it all
7799            // at once after scanning all existing packages.
7800            //
7801            // We also do this *before* we perform dexopt on this package, so that
7802            // we can avoid redundant dexopts, and also to make sure we've got the
7803            // code and package path correct.
7804            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7805                    pkg, true /* boot complete */);
7806        }
7807
7808        if (mFactoryTest && pkg.requestedPermissions.contains(
7809                android.Manifest.permission.FACTORY_TEST)) {
7810            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7811        }
7812
7813        ArrayList<PackageParser.Package> clientLibPkgs = null;
7814
7815        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7816            if (nonMutatedPs != null) {
7817                synchronized (mPackages) {
7818                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7819                }
7820            }
7821            return pkg;
7822        }
7823
7824        // Only privileged apps and updated privileged apps can add child packages.
7825        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7826            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7827                throw new PackageManagerException("Only privileged apps and updated "
7828                        + "privileged apps can add child packages. Ignoring package "
7829                        + pkg.packageName);
7830            }
7831            final int childCount = pkg.childPackages.size();
7832            for (int i = 0; i < childCount; i++) {
7833                PackageParser.Package childPkg = pkg.childPackages.get(i);
7834                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7835                        childPkg.packageName)) {
7836                    throw new PackageManagerException("Cannot override a child package of "
7837                            + "another disabled system app. Ignoring package " + pkg.packageName);
7838                }
7839            }
7840        }
7841
7842        // writer
7843        synchronized (mPackages) {
7844            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7845                // Only system apps can add new shared libraries.
7846                if (pkg.libraryNames != null) {
7847                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7848                        String name = pkg.libraryNames.get(i);
7849                        boolean allowed = false;
7850                        if (pkg.isUpdatedSystemApp()) {
7851                            // New library entries can only be added through the
7852                            // system image.  This is important to get rid of a lot
7853                            // of nasty edge cases: for example if we allowed a non-
7854                            // system update of the app to add a library, then uninstalling
7855                            // the update would make the library go away, and assumptions
7856                            // we made such as through app install filtering would now
7857                            // have allowed apps on the device which aren't compatible
7858                            // with it.  Better to just have the restriction here, be
7859                            // conservative, and create many fewer cases that can negatively
7860                            // impact the user experience.
7861                            final PackageSetting sysPs = mSettings
7862                                    .getDisabledSystemPkgLPr(pkg.packageName);
7863                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7864                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7865                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7866                                        allowed = true;
7867                                        break;
7868                                    }
7869                                }
7870                            }
7871                        } else {
7872                            allowed = true;
7873                        }
7874                        if (allowed) {
7875                            if (!mSharedLibraries.containsKey(name)) {
7876                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7877                            } else if (!name.equals(pkg.packageName)) {
7878                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7879                                        + name + " already exists; skipping");
7880                            }
7881                        } else {
7882                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7883                                    + name + " that is not declared on system image; skipping");
7884                        }
7885                    }
7886                    if ((scanFlags & SCAN_BOOTING) == 0) {
7887                        // If we are not booting, we need to update any applications
7888                        // that are clients of our shared library.  If we are booting,
7889                        // this will all be done once the scan is complete.
7890                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7891                    }
7892                }
7893            }
7894        }
7895
7896        // Request the ActivityManager to kill the process(only for existing packages)
7897        // so that we do not end up in a confused state while the user is still using the older
7898        // version of the application while the new one gets installed.
7899        if ((scanFlags & SCAN_REPLACING) != 0) {
7900            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7901
7902            killApplication(pkg.applicationInfo.packageName,
7903                        pkg.applicationInfo.uid, "replace pkg");
7904
7905            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7906        }
7907
7908        // Also need to kill any apps that are dependent on the library.
7909        if (clientLibPkgs != null) {
7910            for (int i=0; i<clientLibPkgs.size(); i++) {
7911                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7912                killApplication(clientPkg.applicationInfo.packageName,
7913                        clientPkg.applicationInfo.uid, "update lib");
7914            }
7915        }
7916
7917        // Make sure we're not adding any bogus keyset info
7918        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7919        ksms.assertScannedPackageValid(pkg);
7920
7921        // writer
7922        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7923
7924        boolean createIdmapFailed = false;
7925        synchronized (mPackages) {
7926            // We don't expect installation to fail beyond this point
7927
7928            // Add the new setting to mSettings
7929            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7930            // Add the new setting to mPackages
7931            mPackages.put(pkg.applicationInfo.packageName, pkg);
7932            // Make sure we don't accidentally delete its data.
7933            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7934            while (iter.hasNext()) {
7935                PackageCleanItem item = iter.next();
7936                if (pkgName.equals(item.packageName)) {
7937                    iter.remove();
7938                }
7939            }
7940
7941            // Take care of first install / last update times.
7942            if (currentTime != 0) {
7943                if (pkgSetting.firstInstallTime == 0) {
7944                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7945                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7946                    pkgSetting.lastUpdateTime = currentTime;
7947                }
7948            } else if (pkgSetting.firstInstallTime == 0) {
7949                // We need *something*.  Take time time stamp of the file.
7950                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7951            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7952                if (scanFileTime != pkgSetting.timeStamp) {
7953                    // A package on the system image has changed; consider this
7954                    // to be an update.
7955                    pkgSetting.lastUpdateTime = scanFileTime;
7956                }
7957            }
7958
7959            // Add the package's KeySets to the global KeySetManagerService
7960            ksms.addScannedPackageLPw(pkg);
7961
7962            int N = pkg.providers.size();
7963            StringBuilder r = null;
7964            int i;
7965            for (i=0; i<N; i++) {
7966                PackageParser.Provider p = pkg.providers.get(i);
7967                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7968                        p.info.processName, pkg.applicationInfo.uid);
7969                mProviders.addProvider(p);
7970                p.syncable = p.info.isSyncable;
7971                if (p.info.authority != null) {
7972                    String names[] = p.info.authority.split(";");
7973                    p.info.authority = null;
7974                    for (int j = 0; j < names.length; j++) {
7975                        if (j == 1 && p.syncable) {
7976                            // We only want the first authority for a provider to possibly be
7977                            // syncable, so if we already added this provider using a different
7978                            // authority clear the syncable flag. We copy the provider before
7979                            // changing it because the mProviders object contains a reference
7980                            // to a provider that we don't want to change.
7981                            // Only do this for the second authority since the resulting provider
7982                            // object can be the same for all future authorities for this provider.
7983                            p = new PackageParser.Provider(p);
7984                            p.syncable = false;
7985                        }
7986                        if (!mProvidersByAuthority.containsKey(names[j])) {
7987                            mProvidersByAuthority.put(names[j], p);
7988                            if (p.info.authority == null) {
7989                                p.info.authority = names[j];
7990                            } else {
7991                                p.info.authority = p.info.authority + ";" + names[j];
7992                            }
7993                            if (DEBUG_PACKAGE_SCANNING) {
7994                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7995                                    Log.d(TAG, "Registered content provider: " + names[j]
7996                                            + ", className = " + p.info.name + ", isSyncable = "
7997                                            + p.info.isSyncable);
7998                            }
7999                        } else {
8000                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8001                            Slog.w(TAG, "Skipping provider name " + names[j] +
8002                                    " (in package " + pkg.applicationInfo.packageName +
8003                                    "): name already used by "
8004                                    + ((other != null && other.getComponentName() != null)
8005                                            ? other.getComponentName().getPackageName() : "?"));
8006                        }
8007                    }
8008                }
8009                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8010                    if (r == null) {
8011                        r = new StringBuilder(256);
8012                    } else {
8013                        r.append(' ');
8014                    }
8015                    r.append(p.info.name);
8016                }
8017            }
8018            if (r != null) {
8019                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8020            }
8021
8022            N = pkg.services.size();
8023            r = null;
8024            for (i=0; i<N; i++) {
8025                PackageParser.Service s = pkg.services.get(i);
8026                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8027                        s.info.processName, pkg.applicationInfo.uid);
8028                mServices.addService(s);
8029                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8030                    if (r == null) {
8031                        r = new StringBuilder(256);
8032                    } else {
8033                        r.append(' ');
8034                    }
8035                    r.append(s.info.name);
8036                }
8037            }
8038            if (r != null) {
8039                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8040            }
8041
8042            N = pkg.receivers.size();
8043            r = null;
8044            for (i=0; i<N; i++) {
8045                PackageParser.Activity a = pkg.receivers.get(i);
8046                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8047                        a.info.processName, pkg.applicationInfo.uid);
8048                mReceivers.addActivity(a, "receiver");
8049                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8050                    if (r == null) {
8051                        r = new StringBuilder(256);
8052                    } else {
8053                        r.append(' ');
8054                    }
8055                    r.append(a.info.name);
8056                }
8057            }
8058            if (r != null) {
8059                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8060            }
8061
8062            N = pkg.activities.size();
8063            r = null;
8064            for (i=0; i<N; i++) {
8065                PackageParser.Activity a = pkg.activities.get(i);
8066                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8067                        a.info.processName, pkg.applicationInfo.uid);
8068                mActivities.addActivity(a, "activity");
8069                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8070                    if (r == null) {
8071                        r = new StringBuilder(256);
8072                    } else {
8073                        r.append(' ');
8074                    }
8075                    r.append(a.info.name);
8076                }
8077            }
8078            if (r != null) {
8079                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8080            }
8081
8082            N = pkg.permissionGroups.size();
8083            r = null;
8084            for (i=0; i<N; i++) {
8085                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8086                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8087                if (cur == null) {
8088                    mPermissionGroups.put(pg.info.name, pg);
8089                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8090                        if (r == null) {
8091                            r = new StringBuilder(256);
8092                        } else {
8093                            r.append(' ');
8094                        }
8095                        r.append(pg.info.name);
8096                    }
8097                } else {
8098                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8099                            + pg.info.packageName + " ignored: original from "
8100                            + cur.info.packageName);
8101                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8102                        if (r == null) {
8103                            r = new StringBuilder(256);
8104                        } else {
8105                            r.append(' ');
8106                        }
8107                        r.append("DUP:");
8108                        r.append(pg.info.name);
8109                    }
8110                }
8111            }
8112            if (r != null) {
8113                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8114            }
8115
8116            N = pkg.permissions.size();
8117            r = null;
8118            for (i=0; i<N; i++) {
8119                PackageParser.Permission p = pkg.permissions.get(i);
8120
8121                // Assume by default that we did not install this permission into the system.
8122                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8123
8124                // Now that permission groups have a special meaning, we ignore permission
8125                // groups for legacy apps to prevent unexpected behavior. In particular,
8126                // permissions for one app being granted to someone just becase they happen
8127                // to be in a group defined by another app (before this had no implications).
8128                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8129                    p.group = mPermissionGroups.get(p.info.group);
8130                    // Warn for a permission in an unknown group.
8131                    if (p.info.group != null && p.group == null) {
8132                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8133                                + p.info.packageName + " in an unknown group " + p.info.group);
8134                    }
8135                }
8136
8137                ArrayMap<String, BasePermission> permissionMap =
8138                        p.tree ? mSettings.mPermissionTrees
8139                                : mSettings.mPermissions;
8140                BasePermission bp = permissionMap.get(p.info.name);
8141
8142                // Allow system apps to redefine non-system permissions
8143                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8144                    final boolean currentOwnerIsSystem = (bp.perm != null
8145                            && isSystemApp(bp.perm.owner));
8146                    if (isSystemApp(p.owner)) {
8147                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8148                            // It's a built-in permission and no owner, take ownership now
8149                            bp.packageSetting = pkgSetting;
8150                            bp.perm = p;
8151                            bp.uid = pkg.applicationInfo.uid;
8152                            bp.sourcePackage = p.info.packageName;
8153                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8154                        } else if (!currentOwnerIsSystem) {
8155                            String msg = "New decl " + p.owner + " of permission  "
8156                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8157                            reportSettingsProblem(Log.WARN, msg);
8158                            bp = null;
8159                        }
8160                    }
8161                }
8162
8163                if (bp == null) {
8164                    bp = new BasePermission(p.info.name, p.info.packageName,
8165                            BasePermission.TYPE_NORMAL);
8166                    permissionMap.put(p.info.name, bp);
8167                }
8168
8169                if (bp.perm == null) {
8170                    if (bp.sourcePackage == null
8171                            || bp.sourcePackage.equals(p.info.packageName)) {
8172                        BasePermission tree = findPermissionTreeLP(p.info.name);
8173                        if (tree == null
8174                                || tree.sourcePackage.equals(p.info.packageName)) {
8175                            bp.packageSetting = pkgSetting;
8176                            bp.perm = p;
8177                            bp.uid = pkg.applicationInfo.uid;
8178                            bp.sourcePackage = p.info.packageName;
8179                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8180                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8181                                if (r == null) {
8182                                    r = new StringBuilder(256);
8183                                } else {
8184                                    r.append(' ');
8185                                }
8186                                r.append(p.info.name);
8187                            }
8188                        } else {
8189                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8190                                    + p.info.packageName + " ignored: base tree "
8191                                    + tree.name + " is from package "
8192                                    + tree.sourcePackage);
8193                        }
8194                    } else {
8195                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8196                                + p.info.packageName + " ignored: original from "
8197                                + bp.sourcePackage);
8198                    }
8199                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8200                    if (r == null) {
8201                        r = new StringBuilder(256);
8202                    } else {
8203                        r.append(' ');
8204                    }
8205                    r.append("DUP:");
8206                    r.append(p.info.name);
8207                }
8208                if (bp.perm == p) {
8209                    bp.protectionLevel = p.info.protectionLevel;
8210                }
8211            }
8212
8213            if (r != null) {
8214                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8215            }
8216
8217            N = pkg.instrumentation.size();
8218            r = null;
8219            for (i=0; i<N; i++) {
8220                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8221                a.info.packageName = pkg.applicationInfo.packageName;
8222                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8223                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8224                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8225                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8226                a.info.dataDir = pkg.applicationInfo.dataDir;
8227                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8228                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8229
8230                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8231                // need other information about the application, like the ABI and what not ?
8232                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8233                mInstrumentation.put(a.getComponentName(), a);
8234                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8235                    if (r == null) {
8236                        r = new StringBuilder(256);
8237                    } else {
8238                        r.append(' ');
8239                    }
8240                    r.append(a.info.name);
8241                }
8242            }
8243            if (r != null) {
8244                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8245            }
8246
8247            if (pkg.protectedBroadcasts != null) {
8248                N = pkg.protectedBroadcasts.size();
8249                for (i=0; i<N; i++) {
8250                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8251                }
8252            }
8253
8254            pkgSetting.setTimeStamp(scanFileTime);
8255
8256            // Create idmap files for pairs of (packages, overlay packages).
8257            // Note: "android", ie framework-res.apk, is handled by native layers.
8258            if (pkg.mOverlayTarget != null) {
8259                // This is an overlay package.
8260                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8261                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8262                        mOverlays.put(pkg.mOverlayTarget,
8263                                new ArrayMap<String, PackageParser.Package>());
8264                    }
8265                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8266                    map.put(pkg.packageName, pkg);
8267                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8268                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8269                        createIdmapFailed = true;
8270                    }
8271                }
8272            } else if (mOverlays.containsKey(pkg.packageName) &&
8273                    !pkg.packageName.equals("android")) {
8274                // This is a regular package, with one or more known overlay packages.
8275                createIdmapsForPackageLI(pkg);
8276            }
8277        }
8278
8279        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8280
8281        if (createIdmapFailed) {
8282            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8283                    "scanPackageLI failed to createIdmap");
8284        }
8285        return pkg;
8286    }
8287
8288    /**
8289     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8290     * is derived purely on the basis of the contents of {@code scanFile} and
8291     * {@code cpuAbiOverride}.
8292     *
8293     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8294     */
8295    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8296                                 String cpuAbiOverride, boolean extractLibs)
8297            throws PackageManagerException {
8298        // TODO: We can probably be smarter about this stuff. For installed apps,
8299        // we can calculate this information at install time once and for all. For
8300        // system apps, we can probably assume that this information doesn't change
8301        // after the first boot scan. As things stand, we do lots of unnecessary work.
8302
8303        // Give ourselves some initial paths; we'll come back for another
8304        // pass once we've determined ABI below.
8305        setNativeLibraryPaths(pkg);
8306
8307        // We would never need to extract libs for forward-locked and external packages,
8308        // since the container service will do it for us. We shouldn't attempt to
8309        // extract libs from system app when it was not updated.
8310        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8311                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8312            extractLibs = false;
8313        }
8314
8315        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8316        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8317
8318        NativeLibraryHelper.Handle handle = null;
8319        try {
8320            handle = NativeLibraryHelper.Handle.create(pkg);
8321            // TODO(multiArch): This can be null for apps that didn't go through the
8322            // usual installation process. We can calculate it again, like we
8323            // do during install time.
8324            //
8325            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8326            // unnecessary.
8327            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8328
8329            // Null out the abis so that they can be recalculated.
8330            pkg.applicationInfo.primaryCpuAbi = null;
8331            pkg.applicationInfo.secondaryCpuAbi = null;
8332            if (isMultiArch(pkg.applicationInfo)) {
8333                // Warn if we've set an abiOverride for multi-lib packages..
8334                // By definition, we need to copy both 32 and 64 bit libraries for
8335                // such packages.
8336                if (pkg.cpuAbiOverride != null
8337                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8338                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8339                }
8340
8341                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8342                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8343                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8344                    if (extractLibs) {
8345                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8346                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8347                                useIsaSpecificSubdirs);
8348                    } else {
8349                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8350                    }
8351                }
8352
8353                maybeThrowExceptionForMultiArchCopy(
8354                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8355
8356                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8357                    if (extractLibs) {
8358                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8359                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8360                                useIsaSpecificSubdirs);
8361                    } else {
8362                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8363                    }
8364                }
8365
8366                maybeThrowExceptionForMultiArchCopy(
8367                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8368
8369                if (abi64 >= 0) {
8370                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8371                }
8372
8373                if (abi32 >= 0) {
8374                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8375                    if (abi64 >= 0) {
8376                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8377                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8378                            pkg.applicationInfo.primaryCpuAbi = abi;
8379                        } else {
8380                            pkg.applicationInfo.secondaryCpuAbi = abi;
8381                        }
8382                    } else {
8383                        pkg.applicationInfo.primaryCpuAbi = abi;
8384                    }
8385                }
8386
8387            } else {
8388                String[] abiList = (cpuAbiOverride != null) ?
8389                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8390
8391                // Enable gross and lame hacks for apps that are built with old
8392                // SDK tools. We must scan their APKs for renderscript bitcode and
8393                // not launch them if it's present. Don't bother checking on devices
8394                // that don't have 64 bit support.
8395                boolean needsRenderScriptOverride = false;
8396                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8397                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8398                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8399                    needsRenderScriptOverride = true;
8400                }
8401
8402                final int copyRet;
8403                if (extractLibs) {
8404                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8405                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8406                } else {
8407                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8408                }
8409
8410                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8411                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8412                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8413                }
8414
8415                if (copyRet >= 0) {
8416                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8417                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8418                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8419                } else if (needsRenderScriptOverride) {
8420                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8421                }
8422            }
8423        } catch (IOException ioe) {
8424            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8425        } finally {
8426            IoUtils.closeQuietly(handle);
8427        }
8428
8429        // Now that we've calculated the ABIs and determined if it's an internal app,
8430        // we will go ahead and populate the nativeLibraryPath.
8431        setNativeLibraryPaths(pkg);
8432    }
8433
8434    /**
8435     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8436     * i.e, so that all packages can be run inside a single process if required.
8437     *
8438     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8439     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8440     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8441     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8442     * updating a package that belongs to a shared user.
8443     *
8444     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8445     * adds unnecessary complexity.
8446     */
8447    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8448            PackageParser.Package scannedPackage, boolean bootComplete) {
8449        String requiredInstructionSet = null;
8450        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8451            requiredInstructionSet = VMRuntime.getInstructionSet(
8452                     scannedPackage.applicationInfo.primaryCpuAbi);
8453        }
8454
8455        PackageSetting requirer = null;
8456        for (PackageSetting ps : packagesForUser) {
8457            // If packagesForUser contains scannedPackage, we skip it. This will happen
8458            // when scannedPackage is an update of an existing package. Without this check,
8459            // we will never be able to change the ABI of any package belonging to a shared
8460            // user, even if it's compatible with other packages.
8461            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8462                if (ps.primaryCpuAbiString == null) {
8463                    continue;
8464                }
8465
8466                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8467                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8468                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8469                    // this but there's not much we can do.
8470                    String errorMessage = "Instruction set mismatch, "
8471                            + ((requirer == null) ? "[caller]" : requirer)
8472                            + " requires " + requiredInstructionSet + " whereas " + ps
8473                            + " requires " + instructionSet;
8474                    Slog.w(TAG, errorMessage);
8475                }
8476
8477                if (requiredInstructionSet == null) {
8478                    requiredInstructionSet = instructionSet;
8479                    requirer = ps;
8480                }
8481            }
8482        }
8483
8484        if (requiredInstructionSet != null) {
8485            String adjustedAbi;
8486            if (requirer != null) {
8487                // requirer != null implies that either scannedPackage was null or that scannedPackage
8488                // did not require an ABI, in which case we have to adjust scannedPackage to match
8489                // the ABI of the set (which is the same as requirer's ABI)
8490                adjustedAbi = requirer.primaryCpuAbiString;
8491                if (scannedPackage != null) {
8492                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8493                }
8494            } else {
8495                // requirer == null implies that we're updating all ABIs in the set to
8496                // match scannedPackage.
8497                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8498            }
8499
8500            for (PackageSetting ps : packagesForUser) {
8501                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8502                    if (ps.primaryCpuAbiString != null) {
8503                        continue;
8504                    }
8505
8506                    ps.primaryCpuAbiString = adjustedAbi;
8507                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8508                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8509                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8510                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8511                                + " (requirer="
8512                                + (requirer == null ? "null" : requirer.pkg.packageName)
8513                                + ", scannedPackage="
8514                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8515                                + ")");
8516                        try {
8517                            mInstaller.rmdex(ps.codePathString,
8518                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8519                        } catch (InstallerException ignored) {
8520                        }
8521                    }
8522                }
8523            }
8524        }
8525    }
8526
8527    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8528        synchronized (mPackages) {
8529            mResolverReplaced = true;
8530            // Set up information for custom user intent resolution activity.
8531            mResolveActivity.applicationInfo = pkg.applicationInfo;
8532            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8533            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8534            mResolveActivity.processName = pkg.applicationInfo.packageName;
8535            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8536            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8537                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8538            mResolveActivity.theme = 0;
8539            mResolveActivity.exported = true;
8540            mResolveActivity.enabled = true;
8541            mResolveInfo.activityInfo = mResolveActivity;
8542            mResolveInfo.priority = 0;
8543            mResolveInfo.preferredOrder = 0;
8544            mResolveInfo.match = 0;
8545            mResolveComponentName = mCustomResolverComponentName;
8546            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8547                    mResolveComponentName);
8548        }
8549    }
8550
8551    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8552        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8553
8554        // Set up information for ephemeral installer activity
8555        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8556        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8557        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8558        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8559        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8560        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8561                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8562        mEphemeralInstallerActivity.theme = 0;
8563        mEphemeralInstallerActivity.exported = true;
8564        mEphemeralInstallerActivity.enabled = true;
8565        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8566        mEphemeralInstallerInfo.priority = 0;
8567        mEphemeralInstallerInfo.preferredOrder = 0;
8568        mEphemeralInstallerInfo.match = 0;
8569
8570        if (DEBUG_EPHEMERAL) {
8571            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8572        }
8573    }
8574
8575    private static String calculateBundledApkRoot(final String codePathString) {
8576        final File codePath = new File(codePathString);
8577        final File codeRoot;
8578        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8579            codeRoot = Environment.getRootDirectory();
8580        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8581            codeRoot = Environment.getOemDirectory();
8582        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8583            codeRoot = Environment.getVendorDirectory();
8584        } else {
8585            // Unrecognized code path; take its top real segment as the apk root:
8586            // e.g. /something/app/blah.apk => /something
8587            try {
8588                File f = codePath.getCanonicalFile();
8589                File parent = f.getParentFile();    // non-null because codePath is a file
8590                File tmp;
8591                while ((tmp = parent.getParentFile()) != null) {
8592                    f = parent;
8593                    parent = tmp;
8594                }
8595                codeRoot = f;
8596                Slog.w(TAG, "Unrecognized code path "
8597                        + codePath + " - using " + codeRoot);
8598            } catch (IOException e) {
8599                // Can't canonicalize the code path -- shenanigans?
8600                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8601                return Environment.getRootDirectory().getPath();
8602            }
8603        }
8604        return codeRoot.getPath();
8605    }
8606
8607    /**
8608     * Derive and set the location of native libraries for the given package,
8609     * which varies depending on where and how the package was installed.
8610     */
8611    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8612        final ApplicationInfo info = pkg.applicationInfo;
8613        final String codePath = pkg.codePath;
8614        final File codeFile = new File(codePath);
8615        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8616        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8617
8618        info.nativeLibraryRootDir = null;
8619        info.nativeLibraryRootRequiresIsa = false;
8620        info.nativeLibraryDir = null;
8621        info.secondaryNativeLibraryDir = null;
8622
8623        if (isApkFile(codeFile)) {
8624            // Monolithic install
8625            if (bundledApp) {
8626                // If "/system/lib64/apkname" exists, assume that is the per-package
8627                // native library directory to use; otherwise use "/system/lib/apkname".
8628                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8629                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8630                        getPrimaryInstructionSet(info));
8631
8632                // This is a bundled system app so choose the path based on the ABI.
8633                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8634                // is just the default path.
8635                final String apkName = deriveCodePathName(codePath);
8636                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8637                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8638                        apkName).getAbsolutePath();
8639
8640                if (info.secondaryCpuAbi != null) {
8641                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8642                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8643                            secondaryLibDir, apkName).getAbsolutePath();
8644                }
8645            } else if (asecApp) {
8646                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8647                        .getAbsolutePath();
8648            } else {
8649                final String apkName = deriveCodePathName(codePath);
8650                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8651                        .getAbsolutePath();
8652            }
8653
8654            info.nativeLibraryRootRequiresIsa = false;
8655            info.nativeLibraryDir = info.nativeLibraryRootDir;
8656        } else {
8657            // Cluster install
8658            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8659            info.nativeLibraryRootRequiresIsa = true;
8660
8661            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8662                    getPrimaryInstructionSet(info)).getAbsolutePath();
8663
8664            if (info.secondaryCpuAbi != null) {
8665                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8666                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8667            }
8668        }
8669    }
8670
8671    /**
8672     * Calculate the abis and roots for a bundled app. These can uniquely
8673     * be determined from the contents of the system partition, i.e whether
8674     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8675     * of this information, and instead assume that the system was built
8676     * sensibly.
8677     */
8678    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8679                                           PackageSetting pkgSetting) {
8680        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8681
8682        // If "/system/lib64/apkname" exists, assume that is the per-package
8683        // native library directory to use; otherwise use "/system/lib/apkname".
8684        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8685        setBundledAppAbi(pkg, apkRoot, apkName);
8686        // pkgSetting might be null during rescan following uninstall of updates
8687        // to a bundled app, so accommodate that possibility.  The settings in
8688        // that case will be established later from the parsed package.
8689        //
8690        // If the settings aren't null, sync them up with what we've just derived.
8691        // note that apkRoot isn't stored in the package settings.
8692        if (pkgSetting != null) {
8693            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8694            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8695        }
8696    }
8697
8698    /**
8699     * Deduces the ABI of a bundled app and sets the relevant fields on the
8700     * parsed pkg object.
8701     *
8702     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8703     *        under which system libraries are installed.
8704     * @param apkName the name of the installed package.
8705     */
8706    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8707        final File codeFile = new File(pkg.codePath);
8708
8709        final boolean has64BitLibs;
8710        final boolean has32BitLibs;
8711        if (isApkFile(codeFile)) {
8712            // Monolithic install
8713            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8714            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8715        } else {
8716            // Cluster install
8717            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8718            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8719                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8720                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8721                has64BitLibs = (new File(rootDir, isa)).exists();
8722            } else {
8723                has64BitLibs = false;
8724            }
8725            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8726                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8727                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8728                has32BitLibs = (new File(rootDir, isa)).exists();
8729            } else {
8730                has32BitLibs = false;
8731            }
8732        }
8733
8734        if (has64BitLibs && !has32BitLibs) {
8735            // The package has 64 bit libs, but not 32 bit libs. Its primary
8736            // ABI should be 64 bit. We can safely assume here that the bundled
8737            // native libraries correspond to the most preferred ABI in the list.
8738
8739            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8740            pkg.applicationInfo.secondaryCpuAbi = null;
8741        } else if (has32BitLibs && !has64BitLibs) {
8742            // The package has 32 bit libs but not 64 bit libs. Its primary
8743            // ABI should be 32 bit.
8744
8745            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8746            pkg.applicationInfo.secondaryCpuAbi = null;
8747        } else if (has32BitLibs && has64BitLibs) {
8748            // The application has both 64 and 32 bit bundled libraries. We check
8749            // here that the app declares multiArch support, and warn if it doesn't.
8750            //
8751            // We will be lenient here and record both ABIs. The primary will be the
8752            // ABI that's higher on the list, i.e, a device that's configured to prefer
8753            // 64 bit apps will see a 64 bit primary ABI,
8754
8755            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8756                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8757            }
8758
8759            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8760                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8761                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8762            } else {
8763                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8764                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8765            }
8766        } else {
8767            pkg.applicationInfo.primaryCpuAbi = null;
8768            pkg.applicationInfo.secondaryCpuAbi = null;
8769        }
8770    }
8771
8772    private void killPackage(PackageParser.Package pkg, String reason) {
8773        // Kill the parent package
8774        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8775        // Kill the child packages
8776        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8777        for (int i = 0; i < childCount; i++) {
8778            PackageParser.Package childPkg = pkg.childPackages.get(i);
8779            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8780        }
8781    }
8782
8783    private void killApplication(String pkgName, int appId, String reason) {
8784        // Request the ActivityManager to kill the process(only for existing packages)
8785        // so that we do not end up in a confused state while the user is still using the older
8786        // version of the application while the new one gets installed.
8787        IActivityManager am = ActivityManagerNative.getDefault();
8788        if (am != null) {
8789            try {
8790                am.killApplicationWithAppId(pkgName, appId, reason);
8791            } catch (RemoteException e) {
8792            }
8793        }
8794    }
8795
8796    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8797        // Remove the parent package setting
8798        PackageSetting ps = (PackageSetting) pkg.mExtras;
8799        if (ps != null) {
8800            removePackageLI(ps, chatty);
8801        }
8802        // Remove the child package setting
8803        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8804        for (int i = 0; i < childCount; i++) {
8805            PackageParser.Package childPkg = pkg.childPackages.get(i);
8806            ps = (PackageSetting) childPkg.mExtras;
8807            if (ps != null) {
8808                removePackageLI(ps, chatty);
8809            }
8810        }
8811    }
8812
8813    void removePackageLI(PackageSetting ps, boolean chatty) {
8814        if (DEBUG_INSTALL) {
8815            if (chatty)
8816                Log.d(TAG, "Removing package " + ps.name);
8817        }
8818
8819        // writer
8820        synchronized (mPackages) {
8821            mPackages.remove(ps.name);
8822            final PackageParser.Package pkg = ps.pkg;
8823            if (pkg != null) {
8824                cleanPackageDataStructuresLILPw(pkg, chatty);
8825            }
8826        }
8827    }
8828
8829    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8830        if (DEBUG_INSTALL) {
8831            if (chatty)
8832                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8833        }
8834
8835        // writer
8836        synchronized (mPackages) {
8837            // Remove the parent package
8838            mPackages.remove(pkg.applicationInfo.packageName);
8839            cleanPackageDataStructuresLILPw(pkg, chatty);
8840
8841            // Remove the child packages
8842            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8843            for (int i = 0; i < childCount; i++) {
8844                PackageParser.Package childPkg = pkg.childPackages.get(i);
8845                mPackages.remove(childPkg.applicationInfo.packageName);
8846                cleanPackageDataStructuresLILPw(childPkg, chatty);
8847            }
8848        }
8849    }
8850
8851    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8852        int N = pkg.providers.size();
8853        StringBuilder r = null;
8854        int i;
8855        for (i=0; i<N; i++) {
8856            PackageParser.Provider p = pkg.providers.get(i);
8857            mProviders.removeProvider(p);
8858            if (p.info.authority == null) {
8859
8860                /* There was another ContentProvider with this authority when
8861                 * this app was installed so this authority is null,
8862                 * Ignore it as we don't have to unregister the provider.
8863                 */
8864                continue;
8865            }
8866            String names[] = p.info.authority.split(";");
8867            for (int j = 0; j < names.length; j++) {
8868                if (mProvidersByAuthority.get(names[j]) == p) {
8869                    mProvidersByAuthority.remove(names[j]);
8870                    if (DEBUG_REMOVE) {
8871                        if (chatty)
8872                            Log.d(TAG, "Unregistered content provider: " + names[j]
8873                                    + ", className = " + p.info.name + ", isSyncable = "
8874                                    + p.info.isSyncable);
8875                    }
8876                }
8877            }
8878            if (DEBUG_REMOVE && chatty) {
8879                if (r == null) {
8880                    r = new StringBuilder(256);
8881                } else {
8882                    r.append(' ');
8883                }
8884                r.append(p.info.name);
8885            }
8886        }
8887        if (r != null) {
8888            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8889        }
8890
8891        N = pkg.services.size();
8892        r = null;
8893        for (i=0; i<N; i++) {
8894            PackageParser.Service s = pkg.services.get(i);
8895            mServices.removeService(s);
8896            if (chatty) {
8897                if (r == null) {
8898                    r = new StringBuilder(256);
8899                } else {
8900                    r.append(' ');
8901                }
8902                r.append(s.info.name);
8903            }
8904        }
8905        if (r != null) {
8906            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8907        }
8908
8909        N = pkg.receivers.size();
8910        r = null;
8911        for (i=0; i<N; i++) {
8912            PackageParser.Activity a = pkg.receivers.get(i);
8913            mReceivers.removeActivity(a, "receiver");
8914            if (DEBUG_REMOVE && chatty) {
8915                if (r == null) {
8916                    r = new StringBuilder(256);
8917                } else {
8918                    r.append(' ');
8919                }
8920                r.append(a.info.name);
8921            }
8922        }
8923        if (r != null) {
8924            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8925        }
8926
8927        N = pkg.activities.size();
8928        r = null;
8929        for (i=0; i<N; i++) {
8930            PackageParser.Activity a = pkg.activities.get(i);
8931            mActivities.removeActivity(a, "activity");
8932            if (DEBUG_REMOVE && chatty) {
8933                if (r == null) {
8934                    r = new StringBuilder(256);
8935                } else {
8936                    r.append(' ');
8937                }
8938                r.append(a.info.name);
8939            }
8940        }
8941        if (r != null) {
8942            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8943        }
8944
8945        N = pkg.permissions.size();
8946        r = null;
8947        for (i=0; i<N; i++) {
8948            PackageParser.Permission p = pkg.permissions.get(i);
8949            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8950            if (bp == null) {
8951                bp = mSettings.mPermissionTrees.get(p.info.name);
8952            }
8953            if (bp != null && bp.perm == p) {
8954                bp.perm = null;
8955                if (DEBUG_REMOVE && chatty) {
8956                    if (r == null) {
8957                        r = new StringBuilder(256);
8958                    } else {
8959                        r.append(' ');
8960                    }
8961                    r.append(p.info.name);
8962                }
8963            }
8964            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8965                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8966                if (appOpPkgs != null) {
8967                    appOpPkgs.remove(pkg.packageName);
8968                }
8969            }
8970        }
8971        if (r != null) {
8972            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8973        }
8974
8975        N = pkg.requestedPermissions.size();
8976        r = null;
8977        for (i=0; i<N; i++) {
8978            String perm = pkg.requestedPermissions.get(i);
8979            BasePermission bp = mSettings.mPermissions.get(perm);
8980            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8981                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8982                if (appOpPkgs != null) {
8983                    appOpPkgs.remove(pkg.packageName);
8984                    if (appOpPkgs.isEmpty()) {
8985                        mAppOpPermissionPackages.remove(perm);
8986                    }
8987                }
8988            }
8989        }
8990        if (r != null) {
8991            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8992        }
8993
8994        N = pkg.instrumentation.size();
8995        r = null;
8996        for (i=0; i<N; i++) {
8997            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8998            mInstrumentation.remove(a.getComponentName());
8999            if (DEBUG_REMOVE && chatty) {
9000                if (r == null) {
9001                    r = new StringBuilder(256);
9002                } else {
9003                    r.append(' ');
9004                }
9005                r.append(a.info.name);
9006            }
9007        }
9008        if (r != null) {
9009            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9010        }
9011
9012        r = null;
9013        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9014            // Only system apps can hold shared libraries.
9015            if (pkg.libraryNames != null) {
9016                for (i=0; i<pkg.libraryNames.size(); i++) {
9017                    String name = pkg.libraryNames.get(i);
9018                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9019                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9020                        mSharedLibraries.remove(name);
9021                        if (DEBUG_REMOVE && chatty) {
9022                            if (r == null) {
9023                                r = new StringBuilder(256);
9024                            } else {
9025                                r.append(' ');
9026                            }
9027                            r.append(name);
9028                        }
9029                    }
9030                }
9031            }
9032        }
9033        if (r != null) {
9034            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9035        }
9036    }
9037
9038    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9039        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9040            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9041                return true;
9042            }
9043        }
9044        return false;
9045    }
9046
9047    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9048    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9049    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9050
9051    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9052        // Update the parent permissions
9053        updatePermissionsLPw(pkg.packageName, pkg, flags);
9054        // Update the child permissions
9055        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9056        for (int i = 0; i < childCount; i++) {
9057            PackageParser.Package childPkg = pkg.childPackages.get(i);
9058            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9059        }
9060    }
9061
9062    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9063            int flags) {
9064        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9065        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9066    }
9067
9068    private void updatePermissionsLPw(String changingPkg,
9069            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9070        // Make sure there are no dangling permission trees.
9071        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9072        while (it.hasNext()) {
9073            final BasePermission bp = it.next();
9074            if (bp.packageSetting == null) {
9075                // We may not yet have parsed the package, so just see if
9076                // we still know about its settings.
9077                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9078            }
9079            if (bp.packageSetting == null) {
9080                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9081                        + " from package " + bp.sourcePackage);
9082                it.remove();
9083            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9084                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9085                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9086                            + " from package " + bp.sourcePackage);
9087                    flags |= UPDATE_PERMISSIONS_ALL;
9088                    it.remove();
9089                }
9090            }
9091        }
9092
9093        // Make sure all dynamic permissions have been assigned to a package,
9094        // and make sure there are no dangling permissions.
9095        it = mSettings.mPermissions.values().iterator();
9096        while (it.hasNext()) {
9097            final BasePermission bp = it.next();
9098            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9099                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9100                        + bp.name + " pkg=" + bp.sourcePackage
9101                        + " info=" + bp.pendingInfo);
9102                if (bp.packageSetting == null && bp.pendingInfo != null) {
9103                    final BasePermission tree = findPermissionTreeLP(bp.name);
9104                    if (tree != null && tree.perm != null) {
9105                        bp.packageSetting = tree.packageSetting;
9106                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9107                                new PermissionInfo(bp.pendingInfo));
9108                        bp.perm.info.packageName = tree.perm.info.packageName;
9109                        bp.perm.info.name = bp.name;
9110                        bp.uid = tree.uid;
9111                    }
9112                }
9113            }
9114            if (bp.packageSetting == null) {
9115                // We may not yet have parsed the package, so just see if
9116                // we still know about its settings.
9117                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9118            }
9119            if (bp.packageSetting == null) {
9120                Slog.w(TAG, "Removing dangling permission: " + bp.name
9121                        + " from package " + bp.sourcePackage);
9122                it.remove();
9123            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9124                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9125                    Slog.i(TAG, "Removing old permission: " + bp.name
9126                            + " from package " + bp.sourcePackage);
9127                    flags |= UPDATE_PERMISSIONS_ALL;
9128                    it.remove();
9129                }
9130            }
9131        }
9132
9133        // Now update the permissions for all packages, in particular
9134        // replace the granted permissions of the system packages.
9135        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9136            for (PackageParser.Package pkg : mPackages.values()) {
9137                if (pkg != pkgInfo) {
9138                    // Only replace for packages on requested volume
9139                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9140                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9141                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9142                    grantPermissionsLPw(pkg, replace, changingPkg);
9143                }
9144            }
9145        }
9146
9147        if (pkgInfo != null) {
9148            // Only replace for packages on requested volume
9149            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9150            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9151                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9152            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9153        }
9154    }
9155
9156    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9157            String packageOfInterest) {
9158        // IMPORTANT: There are two types of permissions: install and runtime.
9159        // Install time permissions are granted when the app is installed to
9160        // all device users and users added in the future. Runtime permissions
9161        // are granted at runtime explicitly to specific users. Normal and signature
9162        // protected permissions are install time permissions. Dangerous permissions
9163        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9164        // otherwise they are runtime permissions. This function does not manage
9165        // runtime permissions except for the case an app targeting Lollipop MR1
9166        // being upgraded to target a newer SDK, in which case dangerous permissions
9167        // are transformed from install time to runtime ones.
9168
9169        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9170        if (ps == null) {
9171            return;
9172        }
9173
9174        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9175
9176        PermissionsState permissionsState = ps.getPermissionsState();
9177        PermissionsState origPermissions = permissionsState;
9178
9179        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9180
9181        boolean runtimePermissionsRevoked = false;
9182        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9183
9184        boolean changedInstallPermission = false;
9185
9186        if (replace) {
9187            ps.installPermissionsFixed = false;
9188            if (!ps.isSharedUser()) {
9189                origPermissions = new PermissionsState(permissionsState);
9190                permissionsState.reset();
9191            } else {
9192                // We need to know only about runtime permission changes since the
9193                // calling code always writes the install permissions state but
9194                // the runtime ones are written only if changed. The only cases of
9195                // changed runtime permissions here are promotion of an install to
9196                // runtime and revocation of a runtime from a shared user.
9197                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9198                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9199                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9200                    runtimePermissionsRevoked = true;
9201                }
9202            }
9203        }
9204
9205        permissionsState.setGlobalGids(mGlobalGids);
9206
9207        final int N = pkg.requestedPermissions.size();
9208        for (int i=0; i<N; i++) {
9209            final String name = pkg.requestedPermissions.get(i);
9210            final BasePermission bp = mSettings.mPermissions.get(name);
9211
9212            if (DEBUG_INSTALL) {
9213                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9214            }
9215
9216            if (bp == null || bp.packageSetting == null) {
9217                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9218                    Slog.w(TAG, "Unknown permission " + name
9219                            + " in package " + pkg.packageName);
9220                }
9221                continue;
9222            }
9223
9224            final String perm = bp.name;
9225            boolean allowedSig = false;
9226            int grant = GRANT_DENIED;
9227
9228            // Keep track of app op permissions.
9229            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9230                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9231                if (pkgs == null) {
9232                    pkgs = new ArraySet<>();
9233                    mAppOpPermissionPackages.put(bp.name, pkgs);
9234                }
9235                pkgs.add(pkg.packageName);
9236            }
9237
9238            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9239            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9240                    >= Build.VERSION_CODES.M;
9241            switch (level) {
9242                case PermissionInfo.PROTECTION_NORMAL: {
9243                    // For all apps normal permissions are install time ones.
9244                    grant = GRANT_INSTALL;
9245                } break;
9246
9247                case PermissionInfo.PROTECTION_DANGEROUS: {
9248                    // If a permission review is required for legacy apps we represent
9249                    // their permissions as always granted runtime ones since we need
9250                    // to keep the review required permission flag per user while an
9251                    // install permission's state is shared across all users.
9252                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9253                        // For legacy apps dangerous permissions are install time ones.
9254                        grant = GRANT_INSTALL;
9255                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9256                        // For legacy apps that became modern, install becomes runtime.
9257                        grant = GRANT_UPGRADE;
9258                    } else if (mPromoteSystemApps
9259                            && isSystemApp(ps)
9260                            && mExistingSystemPackages.contains(ps.name)) {
9261                        // For legacy system apps, install becomes runtime.
9262                        // We cannot check hasInstallPermission() for system apps since those
9263                        // permissions were granted implicitly and not persisted pre-M.
9264                        grant = GRANT_UPGRADE;
9265                    } else {
9266                        // For modern apps keep runtime permissions unchanged.
9267                        grant = GRANT_RUNTIME;
9268                    }
9269                } break;
9270
9271                case PermissionInfo.PROTECTION_SIGNATURE: {
9272                    // For all apps signature permissions are install time ones.
9273                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9274                    if (allowedSig) {
9275                        grant = GRANT_INSTALL;
9276                    }
9277                } break;
9278            }
9279
9280            if (DEBUG_INSTALL) {
9281                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9282            }
9283
9284            if (grant != GRANT_DENIED) {
9285                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9286                    // If this is an existing, non-system package, then
9287                    // we can't add any new permissions to it.
9288                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9289                        // Except...  if this is a permission that was added
9290                        // to the platform (note: need to only do this when
9291                        // updating the platform).
9292                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9293                            grant = GRANT_DENIED;
9294                        }
9295                    }
9296                }
9297
9298                switch (grant) {
9299                    case GRANT_INSTALL: {
9300                        // Revoke this as runtime permission to handle the case of
9301                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9302                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9303                            if (origPermissions.getRuntimePermissionState(
9304                                    bp.name, userId) != null) {
9305                                // Revoke the runtime permission and clear the flags.
9306                                origPermissions.revokeRuntimePermission(bp, userId);
9307                                origPermissions.updatePermissionFlags(bp, userId,
9308                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9309                                // If we revoked a permission permission, we have to write.
9310                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9311                                        changedRuntimePermissionUserIds, userId);
9312                            }
9313                        }
9314                        // Grant an install permission.
9315                        if (permissionsState.grantInstallPermission(bp) !=
9316                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9317                            changedInstallPermission = true;
9318                        }
9319                    } break;
9320
9321                    case GRANT_RUNTIME: {
9322                        // Grant previously granted runtime permissions.
9323                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9324                            PermissionState permissionState = origPermissions
9325                                    .getRuntimePermissionState(bp.name, userId);
9326                            int flags = permissionState != null
9327                                    ? permissionState.getFlags() : 0;
9328                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9329                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9330                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9331                                    // If we cannot put the permission as it was, we have to write.
9332                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9333                                            changedRuntimePermissionUserIds, userId);
9334                                }
9335                                // If the app supports runtime permissions no need for a review.
9336                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9337                                        && appSupportsRuntimePermissions
9338                                        && (flags & PackageManager
9339                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9340                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9341                                    // Since we changed the flags, we have to write.
9342                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9343                                            changedRuntimePermissionUserIds, userId);
9344                                }
9345                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9346                                    && !appSupportsRuntimePermissions) {
9347                                // For legacy apps that need a permission review, every new
9348                                // runtime permission is granted but it is pending a review.
9349                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9350                                    permissionsState.grantRuntimePermission(bp, userId);
9351                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9352                                    // We changed the permission and flags, hence have to write.
9353                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9354                                            changedRuntimePermissionUserIds, userId);
9355                                }
9356                            }
9357                            // Propagate the permission flags.
9358                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9359                        }
9360                    } break;
9361
9362                    case GRANT_UPGRADE: {
9363                        // Grant runtime permissions for a previously held install permission.
9364                        PermissionState permissionState = origPermissions
9365                                .getInstallPermissionState(bp.name);
9366                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9367
9368                        if (origPermissions.revokeInstallPermission(bp)
9369                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9370                            // We will be transferring the permission flags, so clear them.
9371                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9372                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9373                            changedInstallPermission = true;
9374                        }
9375
9376                        // If the permission is not to be promoted to runtime we ignore it and
9377                        // also its other flags as they are not applicable to install permissions.
9378                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9379                            for (int userId : currentUserIds) {
9380                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9381                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9382                                    // Transfer the permission flags.
9383                                    permissionsState.updatePermissionFlags(bp, userId,
9384                                            flags, flags);
9385                                    // If we granted the permission, we have to write.
9386                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9387                                            changedRuntimePermissionUserIds, userId);
9388                                }
9389                            }
9390                        }
9391                    } break;
9392
9393                    default: {
9394                        if (packageOfInterest == null
9395                                || packageOfInterest.equals(pkg.packageName)) {
9396                            Slog.w(TAG, "Not granting permission " + perm
9397                                    + " to package " + pkg.packageName
9398                                    + " because it was previously installed without");
9399                        }
9400                    } break;
9401                }
9402            } else {
9403                if (permissionsState.revokeInstallPermission(bp) !=
9404                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9405                    // Also drop the permission flags.
9406                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9407                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9408                    changedInstallPermission = true;
9409                    Slog.i(TAG, "Un-granting permission " + perm
9410                            + " from package " + pkg.packageName
9411                            + " (protectionLevel=" + bp.protectionLevel
9412                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9413                            + ")");
9414                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9415                    // Don't print warning for app op permissions, since it is fine for them
9416                    // not to be granted, there is a UI for the user to decide.
9417                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9418                        Slog.w(TAG, "Not granting permission " + perm
9419                                + " to package " + pkg.packageName
9420                                + " (protectionLevel=" + bp.protectionLevel
9421                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9422                                + ")");
9423                    }
9424                }
9425            }
9426        }
9427
9428        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9429                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9430            // This is the first that we have heard about this package, so the
9431            // permissions we have now selected are fixed until explicitly
9432            // changed.
9433            ps.installPermissionsFixed = true;
9434        }
9435
9436        // Persist the runtime permissions state for users with changes. If permissions
9437        // were revoked because no app in the shared user declares them we have to
9438        // write synchronously to avoid losing runtime permissions state.
9439        for (int userId : changedRuntimePermissionUserIds) {
9440            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9441        }
9442
9443        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9444    }
9445
9446    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9447        boolean allowed = false;
9448        final int NP = PackageParser.NEW_PERMISSIONS.length;
9449        for (int ip=0; ip<NP; ip++) {
9450            final PackageParser.NewPermissionInfo npi
9451                    = PackageParser.NEW_PERMISSIONS[ip];
9452            if (npi.name.equals(perm)
9453                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9454                allowed = true;
9455                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9456                        + pkg.packageName);
9457                break;
9458            }
9459        }
9460        return allowed;
9461    }
9462
9463    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9464            BasePermission bp, PermissionsState origPermissions) {
9465        boolean allowed;
9466        allowed = (compareSignatures(
9467                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9468                        == PackageManager.SIGNATURE_MATCH)
9469                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9470                        == PackageManager.SIGNATURE_MATCH);
9471        if (!allowed && (bp.protectionLevel
9472                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9473            if (isSystemApp(pkg)) {
9474                // For updated system applications, a system permission
9475                // is granted only if it had been defined by the original application.
9476                if (pkg.isUpdatedSystemApp()) {
9477                    final PackageSetting sysPs = mSettings
9478                            .getDisabledSystemPkgLPr(pkg.packageName);
9479                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9480                        // If the original was granted this permission, we take
9481                        // that grant decision as read and propagate it to the
9482                        // update.
9483                        if (sysPs.isPrivileged()) {
9484                            allowed = true;
9485                        }
9486                    } else {
9487                        // The system apk may have been updated with an older
9488                        // version of the one on the data partition, but which
9489                        // granted a new system permission that it didn't have
9490                        // before.  In this case we do want to allow the app to
9491                        // now get the new permission if the ancestral apk is
9492                        // privileged to get it.
9493                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9494                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9495                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9496                                    allowed = true;
9497                                    break;
9498                                }
9499                            }
9500                        }
9501                        // Also if a privileged parent package on the system image or any of
9502                        // its children requested a privileged permission, the updated child
9503                        // packages can also get the permission.
9504                        if (pkg.parentPackage != null) {
9505                            final PackageSetting disabledSysParentPs = mSettings
9506                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9507                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9508                                    && disabledSysParentPs.isPrivileged()) {
9509                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9510                                    allowed = true;
9511                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9512                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9513                                    for (int i = 0; i < count; i++) {
9514                                        PackageParser.Package disabledSysChildPkg =
9515                                                disabledSysParentPs.pkg.childPackages.get(i);
9516                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9517                                                perm)) {
9518                                            allowed = true;
9519                                            break;
9520                                        }
9521                                    }
9522                                }
9523                            }
9524                        }
9525                    }
9526                } else {
9527                    allowed = isPrivilegedApp(pkg);
9528                }
9529            }
9530        }
9531        if (!allowed) {
9532            if (!allowed && (bp.protectionLevel
9533                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9534                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9535                // If this was a previously normal/dangerous permission that got moved
9536                // to a system permission as part of the runtime permission redesign, then
9537                // we still want to blindly grant it to old apps.
9538                allowed = true;
9539            }
9540            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9541                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9542                // If this permission is to be granted to the system installer and
9543                // this app is an installer, then it gets the permission.
9544                allowed = true;
9545            }
9546            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9547                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9548                // If this permission is to be granted to the system verifier and
9549                // this app is a verifier, then it gets the permission.
9550                allowed = true;
9551            }
9552            if (!allowed && (bp.protectionLevel
9553                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9554                    && isSystemApp(pkg)) {
9555                // Any pre-installed system app is allowed to get this permission.
9556                allowed = true;
9557            }
9558            if (!allowed && (bp.protectionLevel
9559                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9560                // For development permissions, a development permission
9561                // is granted only if it was already granted.
9562                allowed = origPermissions.hasInstallPermission(perm);
9563            }
9564        }
9565        return allowed;
9566    }
9567
9568    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9569        final int permCount = pkg.requestedPermissions.size();
9570        for (int j = 0; j < permCount; j++) {
9571            String requestedPermission = pkg.requestedPermissions.get(j);
9572            if (permission.equals(requestedPermission)) {
9573                return true;
9574            }
9575        }
9576        return false;
9577    }
9578
9579    final class ActivityIntentResolver
9580            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9581        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9582                boolean defaultOnly, int userId) {
9583            if (!sUserManager.exists(userId)) return null;
9584            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9585            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9586        }
9587
9588        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9589                int userId) {
9590            if (!sUserManager.exists(userId)) return null;
9591            mFlags = flags;
9592            return super.queryIntent(intent, resolvedType,
9593                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9594        }
9595
9596        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9597                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9598            if (!sUserManager.exists(userId)) return null;
9599            if (packageActivities == null) {
9600                return null;
9601            }
9602            mFlags = flags;
9603            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9604            final int N = packageActivities.size();
9605            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9606                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9607
9608            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9609            for (int i = 0; i < N; ++i) {
9610                intentFilters = packageActivities.get(i).intents;
9611                if (intentFilters != null && intentFilters.size() > 0) {
9612                    PackageParser.ActivityIntentInfo[] array =
9613                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9614                    intentFilters.toArray(array);
9615                    listCut.add(array);
9616                }
9617            }
9618            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9619        }
9620
9621        public final void addActivity(PackageParser.Activity a, String type) {
9622            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9623            mActivities.put(a.getComponentName(), a);
9624            if (DEBUG_SHOW_INFO)
9625                Log.v(
9626                TAG, "  " + type + " " +
9627                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9628            if (DEBUG_SHOW_INFO)
9629                Log.v(TAG, "    Class=" + a.info.name);
9630            final int NI = a.intents.size();
9631            for (int j=0; j<NI; j++) {
9632                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9633                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9634                    intent.setPriority(0);
9635                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9636                            + a.className + " with priority > 0, forcing to 0");
9637                }
9638                if (DEBUG_SHOW_INFO) {
9639                    Log.v(TAG, "    IntentFilter:");
9640                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9641                }
9642                if (!intent.debugCheck()) {
9643                    Log.w(TAG, "==> For Activity " + a.info.name);
9644                }
9645                addFilter(intent);
9646            }
9647        }
9648
9649        public final void removeActivity(PackageParser.Activity a, String type) {
9650            mActivities.remove(a.getComponentName());
9651            if (DEBUG_SHOW_INFO) {
9652                Log.v(TAG, "  " + type + " "
9653                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9654                                : a.info.name) + ":");
9655                Log.v(TAG, "    Class=" + a.info.name);
9656            }
9657            final int NI = a.intents.size();
9658            for (int j=0; j<NI; j++) {
9659                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9660                if (DEBUG_SHOW_INFO) {
9661                    Log.v(TAG, "    IntentFilter:");
9662                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9663                }
9664                removeFilter(intent);
9665            }
9666        }
9667
9668        @Override
9669        protected boolean allowFilterResult(
9670                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9671            ActivityInfo filterAi = filter.activity.info;
9672            for (int i=dest.size()-1; i>=0; i--) {
9673                ActivityInfo destAi = dest.get(i).activityInfo;
9674                if (destAi.name == filterAi.name
9675                        && destAi.packageName == filterAi.packageName) {
9676                    return false;
9677                }
9678            }
9679            return true;
9680        }
9681
9682        @Override
9683        protected ActivityIntentInfo[] newArray(int size) {
9684            return new ActivityIntentInfo[size];
9685        }
9686
9687        @Override
9688        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9689            if (!sUserManager.exists(userId)) return true;
9690            PackageParser.Package p = filter.activity.owner;
9691            if (p != null) {
9692                PackageSetting ps = (PackageSetting)p.mExtras;
9693                if (ps != null) {
9694                    // System apps are never considered stopped for purposes of
9695                    // filtering, because there may be no way for the user to
9696                    // actually re-launch them.
9697                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9698                            && ps.getStopped(userId);
9699                }
9700            }
9701            return false;
9702        }
9703
9704        @Override
9705        protected boolean isPackageForFilter(String packageName,
9706                PackageParser.ActivityIntentInfo info) {
9707            return packageName.equals(info.activity.owner.packageName);
9708        }
9709
9710        @Override
9711        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9712                int match, int userId) {
9713            if (!sUserManager.exists(userId)) return null;
9714            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9715                return null;
9716            }
9717            final PackageParser.Activity activity = info.activity;
9718            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9719            if (ps == null) {
9720                return null;
9721            }
9722            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9723                    ps.readUserState(userId), userId);
9724            if (ai == null) {
9725                return null;
9726            }
9727            final ResolveInfo res = new ResolveInfo();
9728            res.activityInfo = ai;
9729            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9730                res.filter = info;
9731            }
9732            if (info != null) {
9733                res.handleAllWebDataURI = info.handleAllWebDataURI();
9734            }
9735            res.priority = info.getPriority();
9736            res.preferredOrder = activity.owner.mPreferredOrder;
9737            //System.out.println("Result: " + res.activityInfo.className +
9738            //                   " = " + res.priority);
9739            res.match = match;
9740            res.isDefault = info.hasDefault;
9741            res.labelRes = info.labelRes;
9742            res.nonLocalizedLabel = info.nonLocalizedLabel;
9743            if (userNeedsBadging(userId)) {
9744                res.noResourceId = true;
9745            } else {
9746                res.icon = info.icon;
9747            }
9748            res.iconResourceId = info.icon;
9749            res.system = res.activityInfo.applicationInfo.isSystemApp();
9750            return res;
9751        }
9752
9753        @Override
9754        protected void sortResults(List<ResolveInfo> results) {
9755            Collections.sort(results, mResolvePrioritySorter);
9756        }
9757
9758        @Override
9759        protected void dumpFilter(PrintWriter out, String prefix,
9760                PackageParser.ActivityIntentInfo filter) {
9761            out.print(prefix); out.print(
9762                    Integer.toHexString(System.identityHashCode(filter.activity)));
9763                    out.print(' ');
9764                    filter.activity.printComponentShortName(out);
9765                    out.print(" filter ");
9766                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9767        }
9768
9769        @Override
9770        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9771            return filter.activity;
9772        }
9773
9774        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9775            PackageParser.Activity activity = (PackageParser.Activity)label;
9776            out.print(prefix); out.print(
9777                    Integer.toHexString(System.identityHashCode(activity)));
9778                    out.print(' ');
9779                    activity.printComponentShortName(out);
9780            if (count > 1) {
9781                out.print(" ("); out.print(count); out.print(" filters)");
9782            }
9783            out.println();
9784        }
9785
9786//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9787//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9788//            final List<ResolveInfo> retList = Lists.newArrayList();
9789//            while (i.hasNext()) {
9790//                final ResolveInfo resolveInfo = i.next();
9791//                if (isEnabledLP(resolveInfo.activityInfo)) {
9792//                    retList.add(resolveInfo);
9793//                }
9794//            }
9795//            return retList;
9796//        }
9797
9798        // Keys are String (activity class name), values are Activity.
9799        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9800                = new ArrayMap<ComponentName, PackageParser.Activity>();
9801        private int mFlags;
9802    }
9803
9804    private final class ServiceIntentResolver
9805            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9807                boolean defaultOnly, int userId) {
9808            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9809            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9810        }
9811
9812        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9813                int userId) {
9814            if (!sUserManager.exists(userId)) return null;
9815            mFlags = flags;
9816            return super.queryIntent(intent, resolvedType,
9817                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9818        }
9819
9820        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9821                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9822            if (!sUserManager.exists(userId)) return null;
9823            if (packageServices == null) {
9824                return null;
9825            }
9826            mFlags = flags;
9827            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9828            final int N = packageServices.size();
9829            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9830                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9831
9832            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9833            for (int i = 0; i < N; ++i) {
9834                intentFilters = packageServices.get(i).intents;
9835                if (intentFilters != null && intentFilters.size() > 0) {
9836                    PackageParser.ServiceIntentInfo[] array =
9837                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9838                    intentFilters.toArray(array);
9839                    listCut.add(array);
9840                }
9841            }
9842            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9843        }
9844
9845        public final void addService(PackageParser.Service s) {
9846            mServices.put(s.getComponentName(), s);
9847            if (DEBUG_SHOW_INFO) {
9848                Log.v(TAG, "  "
9849                        + (s.info.nonLocalizedLabel != null
9850                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9851                Log.v(TAG, "    Class=" + s.info.name);
9852            }
9853            final int NI = s.intents.size();
9854            int j;
9855            for (j=0; j<NI; j++) {
9856                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9857                if (DEBUG_SHOW_INFO) {
9858                    Log.v(TAG, "    IntentFilter:");
9859                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9860                }
9861                if (!intent.debugCheck()) {
9862                    Log.w(TAG, "==> For Service " + s.info.name);
9863                }
9864                addFilter(intent);
9865            }
9866        }
9867
9868        public final void removeService(PackageParser.Service s) {
9869            mServices.remove(s.getComponentName());
9870            if (DEBUG_SHOW_INFO) {
9871                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9872                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9873                Log.v(TAG, "    Class=" + s.info.name);
9874            }
9875            final int NI = s.intents.size();
9876            int j;
9877            for (j=0; j<NI; j++) {
9878                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9879                if (DEBUG_SHOW_INFO) {
9880                    Log.v(TAG, "    IntentFilter:");
9881                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9882                }
9883                removeFilter(intent);
9884            }
9885        }
9886
9887        @Override
9888        protected boolean allowFilterResult(
9889                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9890            ServiceInfo filterSi = filter.service.info;
9891            for (int i=dest.size()-1; i>=0; i--) {
9892                ServiceInfo destAi = dest.get(i).serviceInfo;
9893                if (destAi.name == filterSi.name
9894                        && destAi.packageName == filterSi.packageName) {
9895                    return false;
9896                }
9897            }
9898            return true;
9899        }
9900
9901        @Override
9902        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9903            return new PackageParser.ServiceIntentInfo[size];
9904        }
9905
9906        @Override
9907        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9908            if (!sUserManager.exists(userId)) return true;
9909            PackageParser.Package p = filter.service.owner;
9910            if (p != null) {
9911                PackageSetting ps = (PackageSetting)p.mExtras;
9912                if (ps != null) {
9913                    // System apps are never considered stopped for purposes of
9914                    // filtering, because there may be no way for the user to
9915                    // actually re-launch them.
9916                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9917                            && ps.getStopped(userId);
9918                }
9919            }
9920            return false;
9921        }
9922
9923        @Override
9924        protected boolean isPackageForFilter(String packageName,
9925                PackageParser.ServiceIntentInfo info) {
9926            return packageName.equals(info.service.owner.packageName);
9927        }
9928
9929        @Override
9930        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9931                int match, int userId) {
9932            if (!sUserManager.exists(userId)) return null;
9933            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9934            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9935                return null;
9936            }
9937            final PackageParser.Service service = info.service;
9938            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9939            if (ps == null) {
9940                return null;
9941            }
9942            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9943                    ps.readUserState(userId), userId);
9944            if (si == null) {
9945                return null;
9946            }
9947            final ResolveInfo res = new ResolveInfo();
9948            res.serviceInfo = si;
9949            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9950                res.filter = filter;
9951            }
9952            res.priority = info.getPriority();
9953            res.preferredOrder = service.owner.mPreferredOrder;
9954            res.match = match;
9955            res.isDefault = info.hasDefault;
9956            res.labelRes = info.labelRes;
9957            res.nonLocalizedLabel = info.nonLocalizedLabel;
9958            res.icon = info.icon;
9959            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9960            return res;
9961        }
9962
9963        @Override
9964        protected void sortResults(List<ResolveInfo> results) {
9965            Collections.sort(results, mResolvePrioritySorter);
9966        }
9967
9968        @Override
9969        protected void dumpFilter(PrintWriter out, String prefix,
9970                PackageParser.ServiceIntentInfo filter) {
9971            out.print(prefix); out.print(
9972                    Integer.toHexString(System.identityHashCode(filter.service)));
9973                    out.print(' ');
9974                    filter.service.printComponentShortName(out);
9975                    out.print(" filter ");
9976                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9977        }
9978
9979        @Override
9980        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9981            return filter.service;
9982        }
9983
9984        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9985            PackageParser.Service service = (PackageParser.Service)label;
9986            out.print(prefix); out.print(
9987                    Integer.toHexString(System.identityHashCode(service)));
9988                    out.print(' ');
9989                    service.printComponentShortName(out);
9990            if (count > 1) {
9991                out.print(" ("); out.print(count); out.print(" filters)");
9992            }
9993            out.println();
9994        }
9995
9996//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9997//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9998//            final List<ResolveInfo> retList = Lists.newArrayList();
9999//            while (i.hasNext()) {
10000//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10001//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10002//                    retList.add(resolveInfo);
10003//                }
10004//            }
10005//            return retList;
10006//        }
10007
10008        // Keys are String (activity class name), values are Activity.
10009        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10010                = new ArrayMap<ComponentName, PackageParser.Service>();
10011        private int mFlags;
10012    };
10013
10014    private final class ProviderIntentResolver
10015            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10016        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10017                boolean defaultOnly, int userId) {
10018            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10019            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10020        }
10021
10022        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10023                int userId) {
10024            if (!sUserManager.exists(userId))
10025                return null;
10026            mFlags = flags;
10027            return super.queryIntent(intent, resolvedType,
10028                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10029        }
10030
10031        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10032                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10033            if (!sUserManager.exists(userId))
10034                return null;
10035            if (packageProviders == null) {
10036                return null;
10037            }
10038            mFlags = flags;
10039            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10040            final int N = packageProviders.size();
10041            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10042                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10043
10044            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10045            for (int i = 0; i < N; ++i) {
10046                intentFilters = packageProviders.get(i).intents;
10047                if (intentFilters != null && intentFilters.size() > 0) {
10048                    PackageParser.ProviderIntentInfo[] array =
10049                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10050                    intentFilters.toArray(array);
10051                    listCut.add(array);
10052                }
10053            }
10054            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10055        }
10056
10057        public final void addProvider(PackageParser.Provider p) {
10058            if (mProviders.containsKey(p.getComponentName())) {
10059                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10060                return;
10061            }
10062
10063            mProviders.put(p.getComponentName(), p);
10064            if (DEBUG_SHOW_INFO) {
10065                Log.v(TAG, "  "
10066                        + (p.info.nonLocalizedLabel != null
10067                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10068                Log.v(TAG, "    Class=" + p.info.name);
10069            }
10070            final int NI = p.intents.size();
10071            int j;
10072            for (j = 0; j < NI; j++) {
10073                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10074                if (DEBUG_SHOW_INFO) {
10075                    Log.v(TAG, "    IntentFilter:");
10076                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10077                }
10078                if (!intent.debugCheck()) {
10079                    Log.w(TAG, "==> For Provider " + p.info.name);
10080                }
10081                addFilter(intent);
10082            }
10083        }
10084
10085        public final void removeProvider(PackageParser.Provider p) {
10086            mProviders.remove(p.getComponentName());
10087            if (DEBUG_SHOW_INFO) {
10088                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10089                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10090                Log.v(TAG, "    Class=" + p.info.name);
10091            }
10092            final int NI = p.intents.size();
10093            int j;
10094            for (j = 0; j < NI; j++) {
10095                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10096                if (DEBUG_SHOW_INFO) {
10097                    Log.v(TAG, "    IntentFilter:");
10098                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10099                }
10100                removeFilter(intent);
10101            }
10102        }
10103
10104        @Override
10105        protected boolean allowFilterResult(
10106                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10107            ProviderInfo filterPi = filter.provider.info;
10108            for (int i = dest.size() - 1; i >= 0; i--) {
10109                ProviderInfo destPi = dest.get(i).providerInfo;
10110                if (destPi.name == filterPi.name
10111                        && destPi.packageName == filterPi.packageName) {
10112                    return false;
10113                }
10114            }
10115            return true;
10116        }
10117
10118        @Override
10119        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10120            return new PackageParser.ProviderIntentInfo[size];
10121        }
10122
10123        @Override
10124        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10125            if (!sUserManager.exists(userId))
10126                return true;
10127            PackageParser.Package p = filter.provider.owner;
10128            if (p != null) {
10129                PackageSetting ps = (PackageSetting) p.mExtras;
10130                if (ps != null) {
10131                    // System apps are never considered stopped for purposes of
10132                    // filtering, because there may be no way for the user to
10133                    // actually re-launch them.
10134                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10135                            && ps.getStopped(userId);
10136                }
10137            }
10138            return false;
10139        }
10140
10141        @Override
10142        protected boolean isPackageForFilter(String packageName,
10143                PackageParser.ProviderIntentInfo info) {
10144            return packageName.equals(info.provider.owner.packageName);
10145        }
10146
10147        @Override
10148        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10149                int match, int userId) {
10150            if (!sUserManager.exists(userId))
10151                return null;
10152            final PackageParser.ProviderIntentInfo info = filter;
10153            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10154                return null;
10155            }
10156            final PackageParser.Provider provider = info.provider;
10157            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10158            if (ps == null) {
10159                return null;
10160            }
10161            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10162                    ps.readUserState(userId), userId);
10163            if (pi == null) {
10164                return null;
10165            }
10166            final ResolveInfo res = new ResolveInfo();
10167            res.providerInfo = pi;
10168            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10169                res.filter = filter;
10170            }
10171            res.priority = info.getPriority();
10172            res.preferredOrder = provider.owner.mPreferredOrder;
10173            res.match = match;
10174            res.isDefault = info.hasDefault;
10175            res.labelRes = info.labelRes;
10176            res.nonLocalizedLabel = info.nonLocalizedLabel;
10177            res.icon = info.icon;
10178            res.system = res.providerInfo.applicationInfo.isSystemApp();
10179            return res;
10180        }
10181
10182        @Override
10183        protected void sortResults(List<ResolveInfo> results) {
10184            Collections.sort(results, mResolvePrioritySorter);
10185        }
10186
10187        @Override
10188        protected void dumpFilter(PrintWriter out, String prefix,
10189                PackageParser.ProviderIntentInfo filter) {
10190            out.print(prefix);
10191            out.print(
10192                    Integer.toHexString(System.identityHashCode(filter.provider)));
10193            out.print(' ');
10194            filter.provider.printComponentShortName(out);
10195            out.print(" filter ");
10196            out.println(Integer.toHexString(System.identityHashCode(filter)));
10197        }
10198
10199        @Override
10200        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10201            return filter.provider;
10202        }
10203
10204        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10205            PackageParser.Provider provider = (PackageParser.Provider)label;
10206            out.print(prefix); out.print(
10207                    Integer.toHexString(System.identityHashCode(provider)));
10208                    out.print(' ');
10209                    provider.printComponentShortName(out);
10210            if (count > 1) {
10211                out.print(" ("); out.print(count); out.print(" filters)");
10212            }
10213            out.println();
10214        }
10215
10216        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10217                = new ArrayMap<ComponentName, PackageParser.Provider>();
10218        private int mFlags;
10219    }
10220
10221    private static final class EphemeralIntentResolver
10222            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10223        @Override
10224        protected EphemeralResolveIntentInfo[] newArray(int size) {
10225            return new EphemeralResolveIntentInfo[size];
10226        }
10227
10228        @Override
10229        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10230            return true;
10231        }
10232
10233        @Override
10234        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10235                int userId) {
10236            if (!sUserManager.exists(userId)) {
10237                return null;
10238            }
10239            return info.getEphemeralResolveInfo();
10240        }
10241    }
10242
10243    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10244            new Comparator<ResolveInfo>() {
10245        public int compare(ResolveInfo r1, ResolveInfo r2) {
10246            int v1 = r1.priority;
10247            int v2 = r2.priority;
10248            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10249            if (v1 != v2) {
10250                return (v1 > v2) ? -1 : 1;
10251            }
10252            v1 = r1.preferredOrder;
10253            v2 = r2.preferredOrder;
10254            if (v1 != v2) {
10255                return (v1 > v2) ? -1 : 1;
10256            }
10257            if (r1.isDefault != r2.isDefault) {
10258                return r1.isDefault ? -1 : 1;
10259            }
10260            v1 = r1.match;
10261            v2 = r2.match;
10262            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10263            if (v1 != v2) {
10264                return (v1 > v2) ? -1 : 1;
10265            }
10266            if (r1.system != r2.system) {
10267                return r1.system ? -1 : 1;
10268            }
10269            if (r1.activityInfo != null) {
10270                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10271            }
10272            if (r1.serviceInfo != null) {
10273                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10274            }
10275            if (r1.providerInfo != null) {
10276                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10277            }
10278            return 0;
10279        }
10280    };
10281
10282    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10283            new Comparator<ProviderInfo>() {
10284        public int compare(ProviderInfo p1, ProviderInfo p2) {
10285            final int v1 = p1.initOrder;
10286            final int v2 = p2.initOrder;
10287            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10288        }
10289    };
10290
10291    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10292            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10293            final int[] userIds) {
10294        mHandler.post(new Runnable() {
10295            @Override
10296            public void run() {
10297                try {
10298                    final IActivityManager am = ActivityManagerNative.getDefault();
10299                    if (am == null) return;
10300                    final int[] resolvedUserIds;
10301                    if (userIds == null) {
10302                        resolvedUserIds = am.getRunningUserIds();
10303                    } else {
10304                        resolvedUserIds = userIds;
10305                    }
10306                    for (int id : resolvedUserIds) {
10307                        final Intent intent = new Intent(action,
10308                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10309                        if (extras != null) {
10310                            intent.putExtras(extras);
10311                        }
10312                        if (targetPkg != null) {
10313                            intent.setPackage(targetPkg);
10314                        }
10315                        // Modify the UID when posting to other users
10316                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10317                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10318                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10319                            intent.putExtra(Intent.EXTRA_UID, uid);
10320                        }
10321                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10322                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10323                        if (DEBUG_BROADCASTS) {
10324                            RuntimeException here = new RuntimeException("here");
10325                            here.fillInStackTrace();
10326                            Slog.d(TAG, "Sending to user " + id + ": "
10327                                    + intent.toShortString(false, true, false, false)
10328                                    + " " + intent.getExtras(), here);
10329                        }
10330                        am.broadcastIntent(null, intent, null, finishedReceiver,
10331                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10332                                null, finishedReceiver != null, false, id);
10333                    }
10334                } catch (RemoteException ex) {
10335                }
10336            }
10337        });
10338    }
10339
10340    /**
10341     * Check if the external storage media is available. This is true if there
10342     * is a mounted external storage medium or if the external storage is
10343     * emulated.
10344     */
10345    private boolean isExternalMediaAvailable() {
10346        return mMediaMounted || Environment.isExternalStorageEmulated();
10347    }
10348
10349    @Override
10350    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10351        // writer
10352        synchronized (mPackages) {
10353            if (!isExternalMediaAvailable()) {
10354                // If the external storage is no longer mounted at this point,
10355                // the caller may not have been able to delete all of this
10356                // packages files and can not delete any more.  Bail.
10357                return null;
10358            }
10359            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10360            if (lastPackage != null) {
10361                pkgs.remove(lastPackage);
10362            }
10363            if (pkgs.size() > 0) {
10364                return pkgs.get(0);
10365            }
10366        }
10367        return null;
10368    }
10369
10370    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10371        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10372                userId, andCode ? 1 : 0, packageName);
10373        if (mSystemReady) {
10374            msg.sendToTarget();
10375        } else {
10376            if (mPostSystemReadyMessages == null) {
10377                mPostSystemReadyMessages = new ArrayList<>();
10378            }
10379            mPostSystemReadyMessages.add(msg);
10380        }
10381    }
10382
10383    void startCleaningPackages() {
10384        // reader
10385        synchronized (mPackages) {
10386            if (!isExternalMediaAvailable()) {
10387                return;
10388            }
10389            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10390                return;
10391            }
10392        }
10393        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10394        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10395        IActivityManager am = ActivityManagerNative.getDefault();
10396        if (am != null) {
10397            try {
10398                am.startService(null, intent, null, mContext.getOpPackageName(),
10399                        UserHandle.USER_SYSTEM);
10400            } catch (RemoteException e) {
10401            }
10402        }
10403    }
10404
10405    @Override
10406    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10407            int installFlags, String installerPackageName, int userId) {
10408        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10409
10410        final int callingUid = Binder.getCallingUid();
10411        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10412
10413        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10414            try {
10415                if (observer != null) {
10416                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10417                }
10418            } catch (RemoteException re) {
10419            }
10420            return;
10421        }
10422
10423        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10424            installFlags |= PackageManager.INSTALL_FROM_ADB;
10425
10426        } else {
10427            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10428            // about installerPackageName.
10429
10430            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10431            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10432        }
10433
10434        UserHandle user;
10435        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10436            user = UserHandle.ALL;
10437        } else {
10438            user = new UserHandle(userId);
10439        }
10440
10441        // Only system components can circumvent runtime permissions when installing.
10442        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10443                && mContext.checkCallingOrSelfPermission(Manifest.permission
10444                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10445            throw new SecurityException("You need the "
10446                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10447                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10448        }
10449
10450        final File originFile = new File(originPath);
10451        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10452
10453        final Message msg = mHandler.obtainMessage(INIT_COPY);
10454        final VerificationInfo verificationInfo = new VerificationInfo(
10455                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10456        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10457                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10458                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10459        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10460        msg.obj = params;
10461
10462        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10463                System.identityHashCode(msg.obj));
10464        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10465                System.identityHashCode(msg.obj));
10466
10467        mHandler.sendMessage(msg);
10468    }
10469
10470    void installStage(String packageName, File stagedDir, String stagedCid,
10471            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10472            String installerPackageName, int installerUid, UserHandle user) {
10473        if (DEBUG_EPHEMERAL) {
10474            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10475                Slog.d(TAG, "Ephemeral install of " + packageName);
10476            }
10477        }
10478        final VerificationInfo verificationInfo = new VerificationInfo(
10479                sessionParams.originatingUri, sessionParams.referrerUri,
10480                sessionParams.originatingUid, installerUid);
10481
10482        final OriginInfo origin;
10483        if (stagedDir != null) {
10484            origin = OriginInfo.fromStagedFile(stagedDir);
10485        } else {
10486            origin = OriginInfo.fromStagedContainer(stagedCid);
10487        }
10488
10489        final Message msg = mHandler.obtainMessage(INIT_COPY);
10490        final InstallParams params = new InstallParams(origin, null, observer,
10491                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10492                verificationInfo, user, sessionParams.abiOverride,
10493                sessionParams.grantedRuntimePermissions);
10494        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10495        msg.obj = params;
10496
10497        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10498                System.identityHashCode(msg.obj));
10499        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10500                System.identityHashCode(msg.obj));
10501
10502        mHandler.sendMessage(msg);
10503    }
10504
10505    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10506            int userId) {
10507        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10508        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10509    }
10510
10511    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10512            int appId, int userId) {
10513        Bundle extras = new Bundle(1);
10514        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10515
10516        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10517                packageName, extras, 0, null, null, new int[] {userId});
10518        try {
10519            IActivityManager am = ActivityManagerNative.getDefault();
10520            if (isSystem && am.isUserRunning(userId, 0)) {
10521                // The just-installed/enabled app is bundled on the system, so presumed
10522                // to be able to run automatically without needing an explicit launch.
10523                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10524                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10525                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10526                        .setPackage(packageName);
10527                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10528                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10529            }
10530        } catch (RemoteException e) {
10531            // shouldn't happen
10532            Slog.w(TAG, "Unable to bootstrap installed package", e);
10533        }
10534    }
10535
10536    @Override
10537    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10538            int userId) {
10539        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10540        PackageSetting pkgSetting;
10541        final int uid = Binder.getCallingUid();
10542        enforceCrossUserPermission(uid, userId, true, true,
10543                "setApplicationHiddenSetting for user " + userId);
10544
10545        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10546            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10547            return false;
10548        }
10549
10550        long callingId = Binder.clearCallingIdentity();
10551        try {
10552            boolean sendAdded = false;
10553            boolean sendRemoved = false;
10554            // writer
10555            synchronized (mPackages) {
10556                pkgSetting = mSettings.mPackages.get(packageName);
10557                if (pkgSetting == null) {
10558                    return false;
10559                }
10560                if (pkgSetting.getHidden(userId) != hidden) {
10561                    pkgSetting.setHidden(hidden, userId);
10562                    mSettings.writePackageRestrictionsLPr(userId);
10563                    if (hidden) {
10564                        sendRemoved = true;
10565                    } else {
10566                        sendAdded = true;
10567                    }
10568                }
10569            }
10570            if (sendAdded) {
10571                sendPackageAddedForUser(packageName, pkgSetting, userId);
10572                return true;
10573            }
10574            if (sendRemoved) {
10575                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10576                        "hiding pkg");
10577                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10578                return true;
10579            }
10580        } finally {
10581            Binder.restoreCallingIdentity(callingId);
10582        }
10583        return false;
10584    }
10585
10586    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10587            int userId) {
10588        final PackageRemovedInfo info = new PackageRemovedInfo();
10589        info.removedPackage = packageName;
10590        info.removedUsers = new int[] {userId};
10591        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10592        info.sendPackageRemovedBroadcasts();
10593    }
10594
10595    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10596        if (pkgList.length > 0) {
10597            Bundle extras = new Bundle(1);
10598            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10599
10600            sendPackageBroadcast(
10601                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10602                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10603                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10604                    new int[] {userId});
10605        }
10606    }
10607
10608    /**
10609     * Returns true if application is not found or there was an error. Otherwise it returns
10610     * the hidden state of the package for the given user.
10611     */
10612    @Override
10613    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10614        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10615        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10616                false, "getApplicationHidden for user " + userId);
10617        PackageSetting pkgSetting;
10618        long callingId = Binder.clearCallingIdentity();
10619        try {
10620            // writer
10621            synchronized (mPackages) {
10622                pkgSetting = mSettings.mPackages.get(packageName);
10623                if (pkgSetting == null) {
10624                    return true;
10625                }
10626                return pkgSetting.getHidden(userId);
10627            }
10628        } finally {
10629            Binder.restoreCallingIdentity(callingId);
10630        }
10631    }
10632
10633    /**
10634     * @hide
10635     */
10636    @Override
10637    public int installExistingPackageAsUser(String packageName, int userId) {
10638        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10639                null);
10640        PackageSetting pkgSetting;
10641        final int uid = Binder.getCallingUid();
10642        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10643                + userId);
10644        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10645            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10646        }
10647
10648        long callingId = Binder.clearCallingIdentity();
10649        try {
10650            boolean installed = false;
10651
10652            // writer
10653            synchronized (mPackages) {
10654                pkgSetting = mSettings.mPackages.get(packageName);
10655                if (pkgSetting == null) {
10656                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10657                }
10658                if (!pkgSetting.getInstalled(userId)) {
10659                    pkgSetting.setInstalled(true, userId);
10660                    pkgSetting.setHidden(false, userId);
10661                    mSettings.writePackageRestrictionsLPr(userId);
10662                    if (pkgSetting.pkg != null) {
10663                        prepareAppDataAfterInstall(pkgSetting.pkg);
10664                    }
10665                    installed = true;
10666                }
10667            }
10668
10669            if (installed) {
10670                sendPackageAddedForUser(packageName, pkgSetting, userId);
10671            }
10672        } finally {
10673            Binder.restoreCallingIdentity(callingId);
10674        }
10675
10676        return PackageManager.INSTALL_SUCCEEDED;
10677    }
10678
10679    boolean isUserRestricted(int userId, String restrictionKey) {
10680        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10681        if (restrictions.getBoolean(restrictionKey, false)) {
10682            Log.w(TAG, "User is restricted: " + restrictionKey);
10683            return true;
10684        }
10685        return false;
10686    }
10687
10688    @Override
10689    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10690            int userId) {
10691        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10692        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10693                "setPackagesSuspended for user " + userId);
10694
10695        if (ArrayUtils.isEmpty(packageNames)) {
10696            return packageNames;
10697        }
10698
10699        // List of package names for whom the suspended state has changed.
10700        List<String> changedPackages = new ArrayList<>(packageNames.length);
10701        // List of package names for whom the suspended state is not set as requested in this
10702        // method.
10703        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10704        for (int i = 0; i < packageNames.length; i++) {
10705            String packageName = packageNames[i];
10706            long callingId = Binder.clearCallingIdentity();
10707            try {
10708                boolean changed = false;
10709                final int appId;
10710                synchronized (mPackages) {
10711                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10712                    if (pkgSetting == null) {
10713                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10714                                + "\". Skipping suspending/un-suspending.");
10715                        unactionedPackages.add(packageName);
10716                        continue;
10717                    }
10718                    appId = pkgSetting.appId;
10719                    if (pkgSetting.getSuspended(userId) != suspended) {
10720                        if (!canSuspendPackageForUser(packageName, userId)) {
10721                            unactionedPackages.add(packageName);
10722                            continue;
10723                        }
10724                        pkgSetting.setSuspended(suspended, userId);
10725                        mSettings.writePackageRestrictionsLPr(userId);
10726                        changed = true;
10727                        changedPackages.add(packageName);
10728                    }
10729                }
10730
10731                if (changed && suspended) {
10732                    killApplication(packageName, UserHandle.getUid(userId, appId),
10733                            "suspending package");
10734                }
10735            } finally {
10736                Binder.restoreCallingIdentity(callingId);
10737            }
10738        }
10739
10740        if (!changedPackages.isEmpty()) {
10741            sendPackagesSuspendedForUser(changedPackages.toArray(
10742                    new String[changedPackages.size()]), userId, suspended);
10743        }
10744
10745        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10746    }
10747
10748    @Override
10749    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10750        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10751                false, "isPackageSuspendedForUser for user " + userId);
10752        synchronized (mPackages) {
10753            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10754            return pkgSetting != null && pkgSetting.getSuspended(userId);
10755        }
10756    }
10757
10758    // TODO: investigate and add more restrictions for suspending crucial packages.
10759    private boolean canSuspendPackageForUser(String packageName, int userId) {
10760        if (isPackageDeviceAdmin(packageName, userId)) {
10761            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10762                    + "\": has active device admin");
10763            return false;
10764        }
10765
10766        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10767        if (packageName.equals(activeLauncherPackageName)) {
10768            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10769                    + "\" because it is set as the active launcher");
10770            return false;
10771        }
10772
10773        return true;
10774    }
10775
10776    private String getActiveLauncherPackageName(int userId) {
10777        Intent intent = new Intent(Intent.ACTION_MAIN);
10778        intent.addCategory(Intent.CATEGORY_HOME);
10779        ResolveInfo resolveInfo = resolveIntent(
10780                intent,
10781                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10782                PackageManager.MATCH_DEFAULT_ONLY,
10783                userId);
10784
10785        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10786    }
10787
10788    @Override
10789    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10790        mContext.enforceCallingOrSelfPermission(
10791                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10792                "Only package verification agents can verify applications");
10793
10794        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10795        final PackageVerificationResponse response = new PackageVerificationResponse(
10796                verificationCode, Binder.getCallingUid());
10797        msg.arg1 = id;
10798        msg.obj = response;
10799        mHandler.sendMessage(msg);
10800    }
10801
10802    @Override
10803    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10804            long millisecondsToDelay) {
10805        mContext.enforceCallingOrSelfPermission(
10806                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10807                "Only package verification agents can extend verification timeouts");
10808
10809        final PackageVerificationState state = mPendingVerification.get(id);
10810        final PackageVerificationResponse response = new PackageVerificationResponse(
10811                verificationCodeAtTimeout, Binder.getCallingUid());
10812
10813        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10814            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10815        }
10816        if (millisecondsToDelay < 0) {
10817            millisecondsToDelay = 0;
10818        }
10819        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10820                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10821            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10822        }
10823
10824        if ((state != null) && !state.timeoutExtended()) {
10825            state.extendTimeout();
10826
10827            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10828            msg.arg1 = id;
10829            msg.obj = response;
10830            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10831        }
10832    }
10833
10834    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10835            int verificationCode, UserHandle user) {
10836        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10837        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10838        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10839        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10840        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10841
10842        mContext.sendBroadcastAsUser(intent, user,
10843                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10844    }
10845
10846    private ComponentName matchComponentForVerifier(String packageName,
10847            List<ResolveInfo> receivers) {
10848        ActivityInfo targetReceiver = null;
10849
10850        final int NR = receivers.size();
10851        for (int i = 0; i < NR; i++) {
10852            final ResolveInfo info = receivers.get(i);
10853            if (info.activityInfo == null) {
10854                continue;
10855            }
10856
10857            if (packageName.equals(info.activityInfo.packageName)) {
10858                targetReceiver = info.activityInfo;
10859                break;
10860            }
10861        }
10862
10863        if (targetReceiver == null) {
10864            return null;
10865        }
10866
10867        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10868    }
10869
10870    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10871            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10872        if (pkgInfo.verifiers.length == 0) {
10873            return null;
10874        }
10875
10876        final int N = pkgInfo.verifiers.length;
10877        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10878        for (int i = 0; i < N; i++) {
10879            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10880
10881            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10882                    receivers);
10883            if (comp == null) {
10884                continue;
10885            }
10886
10887            final int verifierUid = getUidForVerifier(verifierInfo);
10888            if (verifierUid == -1) {
10889                continue;
10890            }
10891
10892            if (DEBUG_VERIFY) {
10893                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10894                        + " with the correct signature");
10895            }
10896            sufficientVerifiers.add(comp);
10897            verificationState.addSufficientVerifier(verifierUid);
10898        }
10899
10900        return sufficientVerifiers;
10901    }
10902
10903    private int getUidForVerifier(VerifierInfo verifierInfo) {
10904        synchronized (mPackages) {
10905            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10906            if (pkg == null) {
10907                return -1;
10908            } else if (pkg.mSignatures.length != 1) {
10909                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10910                        + " has more than one signature; ignoring");
10911                return -1;
10912            }
10913
10914            /*
10915             * If the public key of the package's signature does not match
10916             * our expected public key, then this is a different package and
10917             * we should skip.
10918             */
10919
10920            final byte[] expectedPublicKey;
10921            try {
10922                final Signature verifierSig = pkg.mSignatures[0];
10923                final PublicKey publicKey = verifierSig.getPublicKey();
10924                expectedPublicKey = publicKey.getEncoded();
10925            } catch (CertificateException e) {
10926                return -1;
10927            }
10928
10929            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10930
10931            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10932                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10933                        + " does not have the expected public key; ignoring");
10934                return -1;
10935            }
10936
10937            return pkg.applicationInfo.uid;
10938        }
10939    }
10940
10941    @Override
10942    public void finishPackageInstall(int token) {
10943        enforceSystemOrRoot("Only the system is allowed to finish installs");
10944
10945        if (DEBUG_INSTALL) {
10946            Slog.v(TAG, "BM finishing package install for " + token);
10947        }
10948        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10949
10950        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10951        mHandler.sendMessage(msg);
10952    }
10953
10954    /**
10955     * Get the verification agent timeout.
10956     *
10957     * @return verification timeout in milliseconds
10958     */
10959    private long getVerificationTimeout() {
10960        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10961                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10962                DEFAULT_VERIFICATION_TIMEOUT);
10963    }
10964
10965    /**
10966     * Get the default verification agent response code.
10967     *
10968     * @return default verification response code
10969     */
10970    private int getDefaultVerificationResponse() {
10971        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10972                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10973                DEFAULT_VERIFICATION_RESPONSE);
10974    }
10975
10976    /**
10977     * Check whether or not package verification has been enabled.
10978     *
10979     * @return true if verification should be performed
10980     */
10981    private boolean isVerificationEnabled(int userId, int installFlags) {
10982        if (!DEFAULT_VERIFY_ENABLE) {
10983            return false;
10984        }
10985        // Ephemeral apps don't get the full verification treatment
10986        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10987            if (DEBUG_EPHEMERAL) {
10988                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10989            }
10990            return false;
10991        }
10992
10993        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10994
10995        // Check if installing from ADB
10996        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10997            // Do not run verification in a test harness environment
10998            if (ActivityManager.isRunningInTestHarness()) {
10999                return false;
11000            }
11001            if (ensureVerifyAppsEnabled) {
11002                return true;
11003            }
11004            // Check if the developer does not want package verification for ADB installs
11005            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11006                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11007                return false;
11008            }
11009        }
11010
11011        if (ensureVerifyAppsEnabled) {
11012            return true;
11013        }
11014
11015        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11016                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11017    }
11018
11019    @Override
11020    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11021            throws RemoteException {
11022        mContext.enforceCallingOrSelfPermission(
11023                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11024                "Only intentfilter verification agents can verify applications");
11025
11026        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11027        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11028                Binder.getCallingUid(), verificationCode, failedDomains);
11029        msg.arg1 = id;
11030        msg.obj = response;
11031        mHandler.sendMessage(msg);
11032    }
11033
11034    @Override
11035    public int getIntentVerificationStatus(String packageName, int userId) {
11036        synchronized (mPackages) {
11037            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11038        }
11039    }
11040
11041    @Override
11042    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11043        mContext.enforceCallingOrSelfPermission(
11044                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11045
11046        boolean result = false;
11047        synchronized (mPackages) {
11048            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11049        }
11050        if (result) {
11051            scheduleWritePackageRestrictionsLocked(userId);
11052        }
11053        return result;
11054    }
11055
11056    @Override
11057    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11058        synchronized (mPackages) {
11059            return mSettings.getIntentFilterVerificationsLPr(packageName);
11060        }
11061    }
11062
11063    @Override
11064    public List<IntentFilter> getAllIntentFilters(String packageName) {
11065        if (TextUtils.isEmpty(packageName)) {
11066            return Collections.<IntentFilter>emptyList();
11067        }
11068        synchronized (mPackages) {
11069            PackageParser.Package pkg = mPackages.get(packageName);
11070            if (pkg == null || pkg.activities == null) {
11071                return Collections.<IntentFilter>emptyList();
11072            }
11073            final int count = pkg.activities.size();
11074            ArrayList<IntentFilter> result = new ArrayList<>();
11075            for (int n=0; n<count; n++) {
11076                PackageParser.Activity activity = pkg.activities.get(n);
11077                if (activity.intents != null && activity.intents.size() > 0) {
11078                    result.addAll(activity.intents);
11079                }
11080            }
11081            return result;
11082        }
11083    }
11084
11085    @Override
11086    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11087        mContext.enforceCallingOrSelfPermission(
11088                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11089
11090        synchronized (mPackages) {
11091            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11092            if (packageName != null) {
11093                result |= updateIntentVerificationStatus(packageName,
11094                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11095                        userId);
11096                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11097                        packageName, userId);
11098            }
11099            return result;
11100        }
11101    }
11102
11103    @Override
11104    public String getDefaultBrowserPackageName(int userId) {
11105        synchronized (mPackages) {
11106            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11107        }
11108    }
11109
11110    /**
11111     * Get the "allow unknown sources" setting.
11112     *
11113     * @return the current "allow unknown sources" setting
11114     */
11115    private int getUnknownSourcesSettings() {
11116        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11117                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11118                -1);
11119    }
11120
11121    @Override
11122    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11123        final int uid = Binder.getCallingUid();
11124        // writer
11125        synchronized (mPackages) {
11126            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11127            if (targetPackageSetting == null) {
11128                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11129            }
11130
11131            PackageSetting installerPackageSetting;
11132            if (installerPackageName != null) {
11133                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11134                if (installerPackageSetting == null) {
11135                    throw new IllegalArgumentException("Unknown installer package: "
11136                            + installerPackageName);
11137                }
11138            } else {
11139                installerPackageSetting = null;
11140            }
11141
11142            Signature[] callerSignature;
11143            Object obj = mSettings.getUserIdLPr(uid);
11144            if (obj != null) {
11145                if (obj instanceof SharedUserSetting) {
11146                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11147                } else if (obj instanceof PackageSetting) {
11148                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11149                } else {
11150                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11151                }
11152            } else {
11153                throw new SecurityException("Unknown calling UID: " + uid);
11154            }
11155
11156            // Verify: can't set installerPackageName to a package that is
11157            // not signed with the same cert as the caller.
11158            if (installerPackageSetting != null) {
11159                if (compareSignatures(callerSignature,
11160                        installerPackageSetting.signatures.mSignatures)
11161                        != PackageManager.SIGNATURE_MATCH) {
11162                    throw new SecurityException(
11163                            "Caller does not have same cert as new installer package "
11164                            + installerPackageName);
11165                }
11166            }
11167
11168            // Verify: if target already has an installer package, it must
11169            // be signed with the same cert as the caller.
11170            if (targetPackageSetting.installerPackageName != null) {
11171                PackageSetting setting = mSettings.mPackages.get(
11172                        targetPackageSetting.installerPackageName);
11173                // If the currently set package isn't valid, then it's always
11174                // okay to change it.
11175                if (setting != null) {
11176                    if (compareSignatures(callerSignature,
11177                            setting.signatures.mSignatures)
11178                            != PackageManager.SIGNATURE_MATCH) {
11179                        throw new SecurityException(
11180                                "Caller does not have same cert as old installer package "
11181                                + targetPackageSetting.installerPackageName);
11182                    }
11183                }
11184            }
11185
11186            // Okay!
11187            targetPackageSetting.installerPackageName = installerPackageName;
11188            scheduleWriteSettingsLocked();
11189        }
11190    }
11191
11192    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11193        // Queue up an async operation since the package installation may take a little while.
11194        mHandler.post(new Runnable() {
11195            public void run() {
11196                mHandler.removeCallbacks(this);
11197                 // Result object to be returned
11198                PackageInstalledInfo res = new PackageInstalledInfo();
11199                res.setReturnCode(currentStatus);
11200                res.uid = -1;
11201                res.pkg = null;
11202                res.removedInfo = null;
11203                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11204                    args.doPreInstall(res.returnCode);
11205                    synchronized (mInstallLock) {
11206                        installPackageTracedLI(args, res);
11207                    }
11208                    args.doPostInstall(res.returnCode, res.uid);
11209                }
11210
11211                // A restore should be performed at this point if (a) the install
11212                // succeeded, (b) the operation is not an update, and (c) the new
11213                // package has not opted out of backup participation.
11214                final boolean update = res.removedInfo != null
11215                        && res.removedInfo.removedPackage != null;
11216                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11217                boolean doRestore = !update
11218                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11219
11220                // Set up the post-install work request bookkeeping.  This will be used
11221                // and cleaned up by the post-install event handling regardless of whether
11222                // there's a restore pass performed.  Token values are >= 1.
11223                int token;
11224                if (mNextInstallToken < 0) mNextInstallToken = 1;
11225                token = mNextInstallToken++;
11226
11227                PostInstallData data = new PostInstallData(args, res);
11228                mRunningInstalls.put(token, data);
11229                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11230
11231                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11232                    // Pass responsibility to the Backup Manager.  It will perform a
11233                    // restore if appropriate, then pass responsibility back to the
11234                    // Package Manager to run the post-install observer callbacks
11235                    // and broadcasts.
11236                    IBackupManager bm = IBackupManager.Stub.asInterface(
11237                            ServiceManager.getService(Context.BACKUP_SERVICE));
11238                    if (bm != null) {
11239                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11240                                + " to BM for possible restore");
11241                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11242                        try {
11243                            // TODO: http://b/22388012
11244                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11245                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11246                            } else {
11247                                doRestore = false;
11248                            }
11249                        } catch (RemoteException e) {
11250                            // can't happen; the backup manager is local
11251                        } catch (Exception e) {
11252                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11253                            doRestore = false;
11254                        }
11255                    } else {
11256                        Slog.e(TAG, "Backup Manager not found!");
11257                        doRestore = false;
11258                    }
11259                }
11260
11261                if (!doRestore) {
11262                    // No restore possible, or the Backup Manager was mysteriously not
11263                    // available -- just fire the post-install work request directly.
11264                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11265
11266                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11267
11268                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11269                    mHandler.sendMessage(msg);
11270                }
11271            }
11272        });
11273    }
11274
11275    private abstract class HandlerParams {
11276        private static final int MAX_RETRIES = 4;
11277
11278        /**
11279         * Number of times startCopy() has been attempted and had a non-fatal
11280         * error.
11281         */
11282        private int mRetries = 0;
11283
11284        /** User handle for the user requesting the information or installation. */
11285        private final UserHandle mUser;
11286        String traceMethod;
11287        int traceCookie;
11288
11289        HandlerParams(UserHandle user) {
11290            mUser = user;
11291        }
11292
11293        UserHandle getUser() {
11294            return mUser;
11295        }
11296
11297        HandlerParams setTraceMethod(String traceMethod) {
11298            this.traceMethod = traceMethod;
11299            return this;
11300        }
11301
11302        HandlerParams setTraceCookie(int traceCookie) {
11303            this.traceCookie = traceCookie;
11304            return this;
11305        }
11306
11307        final boolean startCopy() {
11308            boolean res;
11309            try {
11310                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11311
11312                if (++mRetries > MAX_RETRIES) {
11313                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11314                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11315                    handleServiceError();
11316                    return false;
11317                } else {
11318                    handleStartCopy();
11319                    res = true;
11320                }
11321            } catch (RemoteException e) {
11322                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11323                mHandler.sendEmptyMessage(MCS_RECONNECT);
11324                res = false;
11325            }
11326            handleReturnCode();
11327            return res;
11328        }
11329
11330        final void serviceError() {
11331            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11332            handleServiceError();
11333            handleReturnCode();
11334        }
11335
11336        abstract void handleStartCopy() throws RemoteException;
11337        abstract void handleServiceError();
11338        abstract void handleReturnCode();
11339    }
11340
11341    class MeasureParams extends HandlerParams {
11342        private final PackageStats mStats;
11343        private boolean mSuccess;
11344
11345        private final IPackageStatsObserver mObserver;
11346
11347        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11348            super(new UserHandle(stats.userHandle));
11349            mObserver = observer;
11350            mStats = stats;
11351        }
11352
11353        @Override
11354        public String toString() {
11355            return "MeasureParams{"
11356                + Integer.toHexString(System.identityHashCode(this))
11357                + " " + mStats.packageName + "}";
11358        }
11359
11360        @Override
11361        void handleStartCopy() throws RemoteException {
11362            synchronized (mInstallLock) {
11363                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11364            }
11365
11366            if (mSuccess) {
11367                final boolean mounted;
11368                if (Environment.isExternalStorageEmulated()) {
11369                    mounted = true;
11370                } else {
11371                    final String status = Environment.getExternalStorageState();
11372                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11373                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11374                }
11375
11376                if (mounted) {
11377                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11378
11379                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11380                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11381
11382                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11383                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11384
11385                    // Always subtract cache size, since it's a subdirectory
11386                    mStats.externalDataSize -= mStats.externalCacheSize;
11387
11388                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11389                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11390
11391                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11392                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11393                }
11394            }
11395        }
11396
11397        @Override
11398        void handleReturnCode() {
11399            if (mObserver != null) {
11400                try {
11401                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11402                } catch (RemoteException e) {
11403                    Slog.i(TAG, "Observer no longer exists.");
11404                }
11405            }
11406        }
11407
11408        @Override
11409        void handleServiceError() {
11410            Slog.e(TAG, "Could not measure application " + mStats.packageName
11411                            + " external storage");
11412        }
11413    }
11414
11415    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11416            throws RemoteException {
11417        long result = 0;
11418        for (File path : paths) {
11419            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11420        }
11421        return result;
11422    }
11423
11424    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11425        for (File path : paths) {
11426            try {
11427                mcs.clearDirectory(path.getAbsolutePath());
11428            } catch (RemoteException e) {
11429            }
11430        }
11431    }
11432
11433    static class OriginInfo {
11434        /**
11435         * Location where install is coming from, before it has been
11436         * copied/renamed into place. This could be a single monolithic APK
11437         * file, or a cluster directory. This location may be untrusted.
11438         */
11439        final File file;
11440        final String cid;
11441
11442        /**
11443         * Flag indicating that {@link #file} or {@link #cid} has already been
11444         * staged, meaning downstream users don't need to defensively copy the
11445         * contents.
11446         */
11447        final boolean staged;
11448
11449        /**
11450         * Flag indicating that {@link #file} or {@link #cid} is an already
11451         * installed app that is being moved.
11452         */
11453        final boolean existing;
11454
11455        final String resolvedPath;
11456        final File resolvedFile;
11457
11458        static OriginInfo fromNothing() {
11459            return new OriginInfo(null, null, false, false);
11460        }
11461
11462        static OriginInfo fromUntrustedFile(File file) {
11463            return new OriginInfo(file, null, false, false);
11464        }
11465
11466        static OriginInfo fromExistingFile(File file) {
11467            return new OriginInfo(file, null, false, true);
11468        }
11469
11470        static OriginInfo fromStagedFile(File file) {
11471            return new OriginInfo(file, null, true, false);
11472        }
11473
11474        static OriginInfo fromStagedContainer(String cid) {
11475            return new OriginInfo(null, cid, true, false);
11476        }
11477
11478        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11479            this.file = file;
11480            this.cid = cid;
11481            this.staged = staged;
11482            this.existing = existing;
11483
11484            if (cid != null) {
11485                resolvedPath = PackageHelper.getSdDir(cid);
11486                resolvedFile = new File(resolvedPath);
11487            } else if (file != null) {
11488                resolvedPath = file.getAbsolutePath();
11489                resolvedFile = file;
11490            } else {
11491                resolvedPath = null;
11492                resolvedFile = null;
11493            }
11494        }
11495    }
11496
11497    static class MoveInfo {
11498        final int moveId;
11499        final String fromUuid;
11500        final String toUuid;
11501        final String packageName;
11502        final String dataAppName;
11503        final int appId;
11504        final String seinfo;
11505        final int targetSdkVersion;
11506
11507        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11508                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11509            this.moveId = moveId;
11510            this.fromUuid = fromUuid;
11511            this.toUuid = toUuid;
11512            this.packageName = packageName;
11513            this.dataAppName = dataAppName;
11514            this.appId = appId;
11515            this.seinfo = seinfo;
11516            this.targetSdkVersion = targetSdkVersion;
11517        }
11518    }
11519
11520    static class VerificationInfo {
11521        /** A constant used to indicate that a uid value is not present. */
11522        public static final int NO_UID = -1;
11523
11524        /** URI referencing where the package was downloaded from. */
11525        final Uri originatingUri;
11526
11527        /** HTTP referrer URI associated with the originatingURI. */
11528        final Uri referrer;
11529
11530        /** UID of the application that the install request originated from. */
11531        final int originatingUid;
11532
11533        /** UID of application requesting the install */
11534        final int installerUid;
11535
11536        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11537            this.originatingUri = originatingUri;
11538            this.referrer = referrer;
11539            this.originatingUid = originatingUid;
11540            this.installerUid = installerUid;
11541        }
11542    }
11543
11544    class InstallParams extends HandlerParams {
11545        final OriginInfo origin;
11546        final MoveInfo move;
11547        final IPackageInstallObserver2 observer;
11548        int installFlags;
11549        final String installerPackageName;
11550        final String volumeUuid;
11551        private InstallArgs mArgs;
11552        private int mRet;
11553        final String packageAbiOverride;
11554        final String[] grantedRuntimePermissions;
11555        final VerificationInfo verificationInfo;
11556
11557        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11558                int installFlags, String installerPackageName, String volumeUuid,
11559                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11560                String[] grantedPermissions) {
11561            super(user);
11562            this.origin = origin;
11563            this.move = move;
11564            this.observer = observer;
11565            this.installFlags = installFlags;
11566            this.installerPackageName = installerPackageName;
11567            this.volumeUuid = volumeUuid;
11568            this.verificationInfo = verificationInfo;
11569            this.packageAbiOverride = packageAbiOverride;
11570            this.grantedRuntimePermissions = grantedPermissions;
11571        }
11572
11573        @Override
11574        public String toString() {
11575            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11576                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11577        }
11578
11579        private int installLocationPolicy(PackageInfoLite pkgLite) {
11580            String packageName = pkgLite.packageName;
11581            int installLocation = pkgLite.installLocation;
11582            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11583            // reader
11584            synchronized (mPackages) {
11585                PackageParser.Package pkg = mPackages.get(packageName);
11586                if (pkg != null) {
11587                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11588                        // Check for downgrading.
11589                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11590                            try {
11591                                checkDowngrade(pkg, pkgLite);
11592                            } catch (PackageManagerException e) {
11593                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11594                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11595                            }
11596                        }
11597                        // Check for updated system application.
11598                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11599                            if (onSd) {
11600                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11601                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11602                            }
11603                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11604                        } else {
11605                            if (onSd) {
11606                                // Install flag overrides everything.
11607                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11608                            }
11609                            // If current upgrade specifies particular preference
11610                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11611                                // Application explicitly specified internal.
11612                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11613                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11614                                // App explictly prefers external. Let policy decide
11615                            } else {
11616                                // Prefer previous location
11617                                if (isExternal(pkg)) {
11618                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11619                                }
11620                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11621                            }
11622                        }
11623                    } else {
11624                        // Invalid install. Return error code
11625                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11626                    }
11627                }
11628            }
11629            // All the special cases have been taken care of.
11630            // Return result based on recommended install location.
11631            if (onSd) {
11632                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11633            }
11634            return pkgLite.recommendedInstallLocation;
11635        }
11636
11637        /*
11638         * Invoke remote method to get package information and install
11639         * location values. Override install location based on default
11640         * policy if needed and then create install arguments based
11641         * on the install location.
11642         */
11643        public void handleStartCopy() throws RemoteException {
11644            int ret = PackageManager.INSTALL_SUCCEEDED;
11645
11646            // If we're already staged, we've firmly committed to an install location
11647            if (origin.staged) {
11648                if (origin.file != null) {
11649                    installFlags |= PackageManager.INSTALL_INTERNAL;
11650                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11651                } else if (origin.cid != null) {
11652                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11653                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11654                } else {
11655                    throw new IllegalStateException("Invalid stage location");
11656                }
11657            }
11658
11659            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11660            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11661            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11662            PackageInfoLite pkgLite = null;
11663
11664            if (onInt && onSd) {
11665                // Check if both bits are set.
11666                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11667                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11668            } else if (onSd && ephemeral) {
11669                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11670                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11671            } else {
11672                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11673                        packageAbiOverride);
11674
11675                if (DEBUG_EPHEMERAL && ephemeral) {
11676                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11677                }
11678
11679                /*
11680                 * If we have too little free space, try to free cache
11681                 * before giving up.
11682                 */
11683                if (!origin.staged && pkgLite.recommendedInstallLocation
11684                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11685                    // TODO: focus freeing disk space on the target device
11686                    final StorageManager storage = StorageManager.from(mContext);
11687                    final long lowThreshold = storage.getStorageLowBytes(
11688                            Environment.getDataDirectory());
11689
11690                    final long sizeBytes = mContainerService.calculateInstalledSize(
11691                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11692
11693                    try {
11694                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11695                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11696                                installFlags, packageAbiOverride);
11697                    } catch (InstallerException e) {
11698                        Slog.w(TAG, "Failed to free cache", e);
11699                    }
11700
11701                    /*
11702                     * The cache free must have deleted the file we
11703                     * downloaded to install.
11704                     *
11705                     * TODO: fix the "freeCache" call to not delete
11706                     *       the file we care about.
11707                     */
11708                    if (pkgLite.recommendedInstallLocation
11709                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11710                        pkgLite.recommendedInstallLocation
11711                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11712                    }
11713                }
11714            }
11715
11716            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11717                int loc = pkgLite.recommendedInstallLocation;
11718                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11719                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11720                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11721                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11722                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11723                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11724                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11725                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11726                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11727                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11728                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11729                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11730                } else {
11731                    // Override with defaults if needed.
11732                    loc = installLocationPolicy(pkgLite);
11733                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11734                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11735                    } else if (!onSd && !onInt) {
11736                        // Override install location with flags
11737                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11738                            // Set the flag to install on external media.
11739                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11740                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11741                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11742                            if (DEBUG_EPHEMERAL) {
11743                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11744                            }
11745                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11746                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11747                                    |PackageManager.INSTALL_INTERNAL);
11748                        } else {
11749                            // Make sure the flag for installing on external
11750                            // media is unset
11751                            installFlags |= PackageManager.INSTALL_INTERNAL;
11752                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11753                        }
11754                    }
11755                }
11756            }
11757
11758            final InstallArgs args = createInstallArgs(this);
11759            mArgs = args;
11760
11761            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11762                // TODO: http://b/22976637
11763                // Apps installed for "all" users use the device owner to verify the app
11764                UserHandle verifierUser = getUser();
11765                if (verifierUser == UserHandle.ALL) {
11766                    verifierUser = UserHandle.SYSTEM;
11767                }
11768
11769                /*
11770                 * Determine if we have any installed package verifiers. If we
11771                 * do, then we'll defer to them to verify the packages.
11772                 */
11773                final int requiredUid = mRequiredVerifierPackage == null ? -1
11774                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11775                                verifierUser.getIdentifier());
11776                if (!origin.existing && requiredUid != -1
11777                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11778                    final Intent verification = new Intent(
11779                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11780                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11781                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11782                            PACKAGE_MIME_TYPE);
11783                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11784
11785                    // Query all live verifiers based on current user state
11786                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11787                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11788
11789                    if (DEBUG_VERIFY) {
11790                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11791                                + verification.toString() + " with " + pkgLite.verifiers.length
11792                                + " optional verifiers");
11793                    }
11794
11795                    final int verificationId = mPendingVerificationToken++;
11796
11797                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11798
11799                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11800                            installerPackageName);
11801
11802                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11803                            installFlags);
11804
11805                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11806                            pkgLite.packageName);
11807
11808                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11809                            pkgLite.versionCode);
11810
11811                    if (verificationInfo != null) {
11812                        if (verificationInfo.originatingUri != null) {
11813                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11814                                    verificationInfo.originatingUri);
11815                        }
11816                        if (verificationInfo.referrer != null) {
11817                            verification.putExtra(Intent.EXTRA_REFERRER,
11818                                    verificationInfo.referrer);
11819                        }
11820                        if (verificationInfo.originatingUid >= 0) {
11821                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11822                                    verificationInfo.originatingUid);
11823                        }
11824                        if (verificationInfo.installerUid >= 0) {
11825                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11826                                    verificationInfo.installerUid);
11827                        }
11828                    }
11829
11830                    final PackageVerificationState verificationState = new PackageVerificationState(
11831                            requiredUid, args);
11832
11833                    mPendingVerification.append(verificationId, verificationState);
11834
11835                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11836                            receivers, verificationState);
11837
11838                    /*
11839                     * If any sufficient verifiers were listed in the package
11840                     * manifest, attempt to ask them.
11841                     */
11842                    if (sufficientVerifiers != null) {
11843                        final int N = sufficientVerifiers.size();
11844                        if (N == 0) {
11845                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11846                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11847                        } else {
11848                            for (int i = 0; i < N; i++) {
11849                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11850
11851                                final Intent sufficientIntent = new Intent(verification);
11852                                sufficientIntent.setComponent(verifierComponent);
11853                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11854                            }
11855                        }
11856                    }
11857
11858                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11859                            mRequiredVerifierPackage, receivers);
11860                    if (ret == PackageManager.INSTALL_SUCCEEDED
11861                            && mRequiredVerifierPackage != null) {
11862                        Trace.asyncTraceBegin(
11863                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11864                        /*
11865                         * Send the intent to the required verification agent,
11866                         * but only start the verification timeout after the
11867                         * target BroadcastReceivers have run.
11868                         */
11869                        verification.setComponent(requiredVerifierComponent);
11870                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11871                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11872                                new BroadcastReceiver() {
11873                                    @Override
11874                                    public void onReceive(Context context, Intent intent) {
11875                                        final Message msg = mHandler
11876                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11877                                        msg.arg1 = verificationId;
11878                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11879                                    }
11880                                }, null, 0, null, null);
11881
11882                        /*
11883                         * We don't want the copy to proceed until verification
11884                         * succeeds, so null out this field.
11885                         */
11886                        mArgs = null;
11887                    }
11888                } else {
11889                    /*
11890                     * No package verification is enabled, so immediately start
11891                     * the remote call to initiate copy using temporary file.
11892                     */
11893                    ret = args.copyApk(mContainerService, true);
11894                }
11895            }
11896
11897            mRet = ret;
11898        }
11899
11900        @Override
11901        void handleReturnCode() {
11902            // If mArgs is null, then MCS couldn't be reached. When it
11903            // reconnects, it will try again to install. At that point, this
11904            // will succeed.
11905            if (mArgs != null) {
11906                processPendingInstall(mArgs, mRet);
11907            }
11908        }
11909
11910        @Override
11911        void handleServiceError() {
11912            mArgs = createInstallArgs(this);
11913            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11914        }
11915
11916        public boolean isForwardLocked() {
11917            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11918        }
11919    }
11920
11921    /**
11922     * Used during creation of InstallArgs
11923     *
11924     * @param installFlags package installation flags
11925     * @return true if should be installed on external storage
11926     */
11927    private static boolean installOnExternalAsec(int installFlags) {
11928        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11929            return false;
11930        }
11931        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11932            return true;
11933        }
11934        return false;
11935    }
11936
11937    /**
11938     * Used during creation of InstallArgs
11939     *
11940     * @param installFlags package installation flags
11941     * @return true if should be installed as forward locked
11942     */
11943    private static boolean installForwardLocked(int installFlags) {
11944        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11945    }
11946
11947    private InstallArgs createInstallArgs(InstallParams params) {
11948        if (params.move != null) {
11949            return new MoveInstallArgs(params);
11950        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11951            return new AsecInstallArgs(params);
11952        } else {
11953            return new FileInstallArgs(params);
11954        }
11955    }
11956
11957    /**
11958     * Create args that describe an existing installed package. Typically used
11959     * when cleaning up old installs, or used as a move source.
11960     */
11961    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11962            String resourcePath, String[] instructionSets) {
11963        final boolean isInAsec;
11964        if (installOnExternalAsec(installFlags)) {
11965            /* Apps on SD card are always in ASEC containers. */
11966            isInAsec = true;
11967        } else if (installForwardLocked(installFlags)
11968                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11969            /*
11970             * Forward-locked apps are only in ASEC containers if they're the
11971             * new style
11972             */
11973            isInAsec = true;
11974        } else {
11975            isInAsec = false;
11976        }
11977
11978        if (isInAsec) {
11979            return new AsecInstallArgs(codePath, instructionSets,
11980                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11981        } else {
11982            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11983        }
11984    }
11985
11986    static abstract class InstallArgs {
11987        /** @see InstallParams#origin */
11988        final OriginInfo origin;
11989        /** @see InstallParams#move */
11990        final MoveInfo move;
11991
11992        final IPackageInstallObserver2 observer;
11993        // Always refers to PackageManager flags only
11994        final int installFlags;
11995        final String installerPackageName;
11996        final String volumeUuid;
11997        final UserHandle user;
11998        final String abiOverride;
11999        final String[] installGrantPermissions;
12000        /** If non-null, drop an async trace when the install completes */
12001        final String traceMethod;
12002        final int traceCookie;
12003
12004        // The list of instruction sets supported by this app. This is currently
12005        // only used during the rmdex() phase to clean up resources. We can get rid of this
12006        // if we move dex files under the common app path.
12007        /* nullable */ String[] instructionSets;
12008
12009        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12010                int installFlags, String installerPackageName, String volumeUuid,
12011                UserHandle user, String[] instructionSets,
12012                String abiOverride, String[] installGrantPermissions,
12013                String traceMethod, int traceCookie) {
12014            this.origin = origin;
12015            this.move = move;
12016            this.installFlags = installFlags;
12017            this.observer = observer;
12018            this.installerPackageName = installerPackageName;
12019            this.volumeUuid = volumeUuid;
12020            this.user = user;
12021            this.instructionSets = instructionSets;
12022            this.abiOverride = abiOverride;
12023            this.installGrantPermissions = installGrantPermissions;
12024            this.traceMethod = traceMethod;
12025            this.traceCookie = traceCookie;
12026        }
12027
12028        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12029        abstract int doPreInstall(int status);
12030
12031        /**
12032         * Rename package into final resting place. All paths on the given
12033         * scanned package should be updated to reflect the rename.
12034         */
12035        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12036        abstract int doPostInstall(int status, int uid);
12037
12038        /** @see PackageSettingBase#codePathString */
12039        abstract String getCodePath();
12040        /** @see PackageSettingBase#resourcePathString */
12041        abstract String getResourcePath();
12042
12043        // Need installer lock especially for dex file removal.
12044        abstract void cleanUpResourcesLI();
12045        abstract boolean doPostDeleteLI(boolean delete);
12046
12047        /**
12048         * Called before the source arguments are copied. This is used mostly
12049         * for MoveParams when it needs to read the source file to put it in the
12050         * destination.
12051         */
12052        int doPreCopy() {
12053            return PackageManager.INSTALL_SUCCEEDED;
12054        }
12055
12056        /**
12057         * Called after the source arguments are copied. This is used mostly for
12058         * MoveParams when it needs to read the source file to put it in the
12059         * destination.
12060         *
12061         * @return
12062         */
12063        int doPostCopy(int uid) {
12064            return PackageManager.INSTALL_SUCCEEDED;
12065        }
12066
12067        protected boolean isFwdLocked() {
12068            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12069        }
12070
12071        protected boolean isExternalAsec() {
12072            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12073        }
12074
12075        protected boolean isEphemeral() {
12076            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12077        }
12078
12079        UserHandle getUser() {
12080            return user;
12081        }
12082    }
12083
12084    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12085        if (!allCodePaths.isEmpty()) {
12086            if (instructionSets == null) {
12087                throw new IllegalStateException("instructionSet == null");
12088            }
12089            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12090            for (String codePath : allCodePaths) {
12091                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12092                    try {
12093                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12094                    } catch (InstallerException ignored) {
12095                    }
12096                }
12097            }
12098        }
12099    }
12100
12101    /**
12102     * Logic to handle installation of non-ASEC applications, including copying
12103     * and renaming logic.
12104     */
12105    class FileInstallArgs extends InstallArgs {
12106        private File codeFile;
12107        private File resourceFile;
12108
12109        // Example topology:
12110        // /data/app/com.example/base.apk
12111        // /data/app/com.example/split_foo.apk
12112        // /data/app/com.example/lib/arm/libfoo.so
12113        // /data/app/com.example/lib/arm64/libfoo.so
12114        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12115
12116        /** New install */
12117        FileInstallArgs(InstallParams params) {
12118            super(params.origin, params.move, params.observer, params.installFlags,
12119                    params.installerPackageName, params.volumeUuid,
12120                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12121                    params.grantedRuntimePermissions,
12122                    params.traceMethod, params.traceCookie);
12123            if (isFwdLocked()) {
12124                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12125            }
12126        }
12127
12128        /** Existing install */
12129        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12130            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12131                    null, null, null, 0);
12132            this.codeFile = (codePath != null) ? new File(codePath) : null;
12133            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12134        }
12135
12136        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12137            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12138            try {
12139                return doCopyApk(imcs, temp);
12140            } finally {
12141                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12142            }
12143        }
12144
12145        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12146            if (origin.staged) {
12147                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12148                codeFile = origin.file;
12149                resourceFile = origin.file;
12150                return PackageManager.INSTALL_SUCCEEDED;
12151            }
12152
12153            try {
12154                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12155                final File tempDir =
12156                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12157                codeFile = tempDir;
12158                resourceFile = tempDir;
12159            } catch (IOException e) {
12160                Slog.w(TAG, "Failed to create copy file: " + e);
12161                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12162            }
12163
12164            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12165                @Override
12166                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12167                    if (!FileUtils.isValidExtFilename(name)) {
12168                        throw new IllegalArgumentException("Invalid filename: " + name);
12169                    }
12170                    try {
12171                        final File file = new File(codeFile, name);
12172                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12173                                O_RDWR | O_CREAT, 0644);
12174                        Os.chmod(file.getAbsolutePath(), 0644);
12175                        return new ParcelFileDescriptor(fd);
12176                    } catch (ErrnoException e) {
12177                        throw new RemoteException("Failed to open: " + e.getMessage());
12178                    }
12179                }
12180            };
12181
12182            int ret = PackageManager.INSTALL_SUCCEEDED;
12183            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12184            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12185                Slog.e(TAG, "Failed to copy package");
12186                return ret;
12187            }
12188
12189            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12190            NativeLibraryHelper.Handle handle = null;
12191            try {
12192                handle = NativeLibraryHelper.Handle.create(codeFile);
12193                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12194                        abiOverride);
12195            } catch (IOException e) {
12196                Slog.e(TAG, "Copying native libraries failed", e);
12197                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12198            } finally {
12199                IoUtils.closeQuietly(handle);
12200            }
12201
12202            return ret;
12203        }
12204
12205        int doPreInstall(int status) {
12206            if (status != PackageManager.INSTALL_SUCCEEDED) {
12207                cleanUp();
12208            }
12209            return status;
12210        }
12211
12212        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12213            if (status != PackageManager.INSTALL_SUCCEEDED) {
12214                cleanUp();
12215                return false;
12216            }
12217
12218            final File targetDir = codeFile.getParentFile();
12219            final File beforeCodeFile = codeFile;
12220            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12221
12222            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12223            try {
12224                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12225            } catch (ErrnoException e) {
12226                Slog.w(TAG, "Failed to rename", e);
12227                return false;
12228            }
12229
12230            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12231                Slog.w(TAG, "Failed to restorecon");
12232                return false;
12233            }
12234
12235            // Reflect the rename internally
12236            codeFile = afterCodeFile;
12237            resourceFile = afterCodeFile;
12238
12239            // Reflect the rename in scanned details
12240            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12241            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12242                    afterCodeFile, pkg.baseCodePath));
12243            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12244                    afterCodeFile, pkg.splitCodePaths));
12245
12246            // Reflect the rename in app info
12247            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12248            pkg.setApplicationInfoCodePath(pkg.codePath);
12249            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12250            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12251            pkg.setApplicationInfoResourcePath(pkg.codePath);
12252            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12253            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12254
12255            return true;
12256        }
12257
12258        int doPostInstall(int status, int uid) {
12259            if (status != PackageManager.INSTALL_SUCCEEDED) {
12260                cleanUp();
12261            }
12262            return status;
12263        }
12264
12265        @Override
12266        String getCodePath() {
12267            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12268        }
12269
12270        @Override
12271        String getResourcePath() {
12272            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12273        }
12274
12275        private boolean cleanUp() {
12276            if (codeFile == null || !codeFile.exists()) {
12277                return false;
12278            }
12279
12280            removeCodePathLI(codeFile);
12281
12282            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12283                resourceFile.delete();
12284            }
12285
12286            return true;
12287        }
12288
12289        void cleanUpResourcesLI() {
12290            // Try enumerating all code paths before deleting
12291            List<String> allCodePaths = Collections.EMPTY_LIST;
12292            if (codeFile != null && codeFile.exists()) {
12293                try {
12294                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12295                    allCodePaths = pkg.getAllCodePaths();
12296                } catch (PackageParserException e) {
12297                    // Ignored; we tried our best
12298                }
12299            }
12300
12301            cleanUp();
12302            removeDexFiles(allCodePaths, instructionSets);
12303        }
12304
12305        boolean doPostDeleteLI(boolean delete) {
12306            // XXX err, shouldn't we respect the delete flag?
12307            cleanUpResourcesLI();
12308            return true;
12309        }
12310    }
12311
12312    private boolean isAsecExternal(String cid) {
12313        final String asecPath = PackageHelper.getSdFilesystem(cid);
12314        return !asecPath.startsWith(mAsecInternalPath);
12315    }
12316
12317    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12318            PackageManagerException {
12319        if (copyRet < 0) {
12320            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12321                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12322                throw new PackageManagerException(copyRet, message);
12323            }
12324        }
12325    }
12326
12327    /**
12328     * Extract the MountService "container ID" from the full code path of an
12329     * .apk.
12330     */
12331    static String cidFromCodePath(String fullCodePath) {
12332        int eidx = fullCodePath.lastIndexOf("/");
12333        String subStr1 = fullCodePath.substring(0, eidx);
12334        int sidx = subStr1.lastIndexOf("/");
12335        return subStr1.substring(sidx+1, eidx);
12336    }
12337
12338    /**
12339     * Logic to handle installation of ASEC applications, including copying and
12340     * renaming logic.
12341     */
12342    class AsecInstallArgs extends InstallArgs {
12343        static final String RES_FILE_NAME = "pkg.apk";
12344        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12345
12346        String cid;
12347        String packagePath;
12348        String resourcePath;
12349
12350        /** New install */
12351        AsecInstallArgs(InstallParams params) {
12352            super(params.origin, params.move, params.observer, params.installFlags,
12353                    params.installerPackageName, params.volumeUuid,
12354                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12355                    params.grantedRuntimePermissions,
12356                    params.traceMethod, params.traceCookie);
12357        }
12358
12359        /** Existing install */
12360        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12361                        boolean isExternal, boolean isForwardLocked) {
12362            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12363                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12364                    instructionSets, null, null, null, 0);
12365            // Hackily pretend we're still looking at a full code path
12366            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12367                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12368            }
12369
12370            // Extract cid from fullCodePath
12371            int eidx = fullCodePath.lastIndexOf("/");
12372            String subStr1 = fullCodePath.substring(0, eidx);
12373            int sidx = subStr1.lastIndexOf("/");
12374            cid = subStr1.substring(sidx+1, eidx);
12375            setMountPath(subStr1);
12376        }
12377
12378        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12379            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12380                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12381                    instructionSets, null, null, null, 0);
12382            this.cid = cid;
12383            setMountPath(PackageHelper.getSdDir(cid));
12384        }
12385
12386        void createCopyFile() {
12387            cid = mInstallerService.allocateExternalStageCidLegacy();
12388        }
12389
12390        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12391            if (origin.staged && origin.cid != null) {
12392                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12393                cid = origin.cid;
12394                setMountPath(PackageHelper.getSdDir(cid));
12395                return PackageManager.INSTALL_SUCCEEDED;
12396            }
12397
12398            if (temp) {
12399                createCopyFile();
12400            } else {
12401                /*
12402                 * Pre-emptively destroy the container since it's destroyed if
12403                 * copying fails due to it existing anyway.
12404                 */
12405                PackageHelper.destroySdDir(cid);
12406            }
12407
12408            final String newMountPath = imcs.copyPackageToContainer(
12409                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12410                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12411
12412            if (newMountPath != null) {
12413                setMountPath(newMountPath);
12414                return PackageManager.INSTALL_SUCCEEDED;
12415            } else {
12416                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12417            }
12418        }
12419
12420        @Override
12421        String getCodePath() {
12422            return packagePath;
12423        }
12424
12425        @Override
12426        String getResourcePath() {
12427            return resourcePath;
12428        }
12429
12430        int doPreInstall(int status) {
12431            if (status != PackageManager.INSTALL_SUCCEEDED) {
12432                // Destroy container
12433                PackageHelper.destroySdDir(cid);
12434            } else {
12435                boolean mounted = PackageHelper.isContainerMounted(cid);
12436                if (!mounted) {
12437                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12438                            Process.SYSTEM_UID);
12439                    if (newMountPath != null) {
12440                        setMountPath(newMountPath);
12441                    } else {
12442                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12443                    }
12444                }
12445            }
12446            return status;
12447        }
12448
12449        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12450            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12451            String newMountPath = null;
12452            if (PackageHelper.isContainerMounted(cid)) {
12453                // Unmount the container
12454                if (!PackageHelper.unMountSdDir(cid)) {
12455                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12456                    return false;
12457                }
12458            }
12459            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12460                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12461                        " which might be stale. Will try to clean up.");
12462                // Clean up the stale container and proceed to recreate.
12463                if (!PackageHelper.destroySdDir(newCacheId)) {
12464                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12465                    return false;
12466                }
12467                // Successfully cleaned up stale container. Try to rename again.
12468                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12469                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12470                            + " inspite of cleaning it up.");
12471                    return false;
12472                }
12473            }
12474            if (!PackageHelper.isContainerMounted(newCacheId)) {
12475                Slog.w(TAG, "Mounting container " + newCacheId);
12476                newMountPath = PackageHelper.mountSdDir(newCacheId,
12477                        getEncryptKey(), Process.SYSTEM_UID);
12478            } else {
12479                newMountPath = PackageHelper.getSdDir(newCacheId);
12480            }
12481            if (newMountPath == null) {
12482                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12483                return false;
12484            }
12485            Log.i(TAG, "Succesfully renamed " + cid +
12486                    " to " + newCacheId +
12487                    " at new path: " + newMountPath);
12488            cid = newCacheId;
12489
12490            final File beforeCodeFile = new File(packagePath);
12491            setMountPath(newMountPath);
12492            final File afterCodeFile = new File(packagePath);
12493
12494            // Reflect the rename in scanned details
12495            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12496            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12497                    afterCodeFile, pkg.baseCodePath));
12498            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12499                    afterCodeFile, pkg.splitCodePaths));
12500
12501            // Reflect the rename in app info
12502            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12503            pkg.setApplicationInfoCodePath(pkg.codePath);
12504            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12505            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12506            pkg.setApplicationInfoResourcePath(pkg.codePath);
12507            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12508            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12509
12510            return true;
12511        }
12512
12513        private void setMountPath(String mountPath) {
12514            final File mountFile = new File(mountPath);
12515
12516            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12517            if (monolithicFile.exists()) {
12518                packagePath = monolithicFile.getAbsolutePath();
12519                if (isFwdLocked()) {
12520                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12521                } else {
12522                    resourcePath = packagePath;
12523                }
12524            } else {
12525                packagePath = mountFile.getAbsolutePath();
12526                resourcePath = packagePath;
12527            }
12528        }
12529
12530        int doPostInstall(int status, int uid) {
12531            if (status != PackageManager.INSTALL_SUCCEEDED) {
12532                cleanUp();
12533            } else {
12534                final int groupOwner;
12535                final String protectedFile;
12536                if (isFwdLocked()) {
12537                    groupOwner = UserHandle.getSharedAppGid(uid);
12538                    protectedFile = RES_FILE_NAME;
12539                } else {
12540                    groupOwner = -1;
12541                    protectedFile = null;
12542                }
12543
12544                if (uid < Process.FIRST_APPLICATION_UID
12545                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12546                    Slog.e(TAG, "Failed to finalize " + cid);
12547                    PackageHelper.destroySdDir(cid);
12548                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12549                }
12550
12551                boolean mounted = PackageHelper.isContainerMounted(cid);
12552                if (!mounted) {
12553                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12554                }
12555            }
12556            return status;
12557        }
12558
12559        private void cleanUp() {
12560            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12561
12562            // Destroy secure container
12563            PackageHelper.destroySdDir(cid);
12564        }
12565
12566        private List<String> getAllCodePaths() {
12567            final File codeFile = new File(getCodePath());
12568            if (codeFile != null && codeFile.exists()) {
12569                try {
12570                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12571                    return pkg.getAllCodePaths();
12572                } catch (PackageParserException e) {
12573                    // Ignored; we tried our best
12574                }
12575            }
12576            return Collections.EMPTY_LIST;
12577        }
12578
12579        void cleanUpResourcesLI() {
12580            // Enumerate all code paths before deleting
12581            cleanUpResourcesLI(getAllCodePaths());
12582        }
12583
12584        private void cleanUpResourcesLI(List<String> allCodePaths) {
12585            cleanUp();
12586            removeDexFiles(allCodePaths, instructionSets);
12587        }
12588
12589        String getPackageName() {
12590            return getAsecPackageName(cid);
12591        }
12592
12593        boolean doPostDeleteLI(boolean delete) {
12594            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12595            final List<String> allCodePaths = getAllCodePaths();
12596            boolean mounted = PackageHelper.isContainerMounted(cid);
12597            if (mounted) {
12598                // Unmount first
12599                if (PackageHelper.unMountSdDir(cid)) {
12600                    mounted = false;
12601                }
12602            }
12603            if (!mounted && delete) {
12604                cleanUpResourcesLI(allCodePaths);
12605            }
12606            return !mounted;
12607        }
12608
12609        @Override
12610        int doPreCopy() {
12611            if (isFwdLocked()) {
12612                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12613                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12614                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12615                }
12616            }
12617
12618            return PackageManager.INSTALL_SUCCEEDED;
12619        }
12620
12621        @Override
12622        int doPostCopy(int uid) {
12623            if (isFwdLocked()) {
12624                if (uid < Process.FIRST_APPLICATION_UID
12625                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12626                                RES_FILE_NAME)) {
12627                    Slog.e(TAG, "Failed to finalize " + cid);
12628                    PackageHelper.destroySdDir(cid);
12629                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12630                }
12631            }
12632
12633            return PackageManager.INSTALL_SUCCEEDED;
12634        }
12635    }
12636
12637    /**
12638     * Logic to handle movement of existing installed applications.
12639     */
12640    class MoveInstallArgs extends InstallArgs {
12641        private File codeFile;
12642        private File resourceFile;
12643
12644        /** New install */
12645        MoveInstallArgs(InstallParams params) {
12646            super(params.origin, params.move, params.observer, params.installFlags,
12647                    params.installerPackageName, params.volumeUuid,
12648                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12649                    params.grantedRuntimePermissions,
12650                    params.traceMethod, params.traceCookie);
12651        }
12652
12653        int copyApk(IMediaContainerService imcs, boolean temp) {
12654            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12655                    + move.fromUuid + " to " + move.toUuid);
12656            synchronized (mInstaller) {
12657                try {
12658                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12659                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12660                } catch (InstallerException e) {
12661                    Slog.w(TAG, "Failed to move app", e);
12662                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12663                }
12664            }
12665
12666            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12667            resourceFile = codeFile;
12668            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12669
12670            return PackageManager.INSTALL_SUCCEEDED;
12671        }
12672
12673        int doPreInstall(int status) {
12674            if (status != PackageManager.INSTALL_SUCCEEDED) {
12675                cleanUp(move.toUuid);
12676            }
12677            return status;
12678        }
12679
12680        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12681            if (status != PackageManager.INSTALL_SUCCEEDED) {
12682                cleanUp(move.toUuid);
12683                return false;
12684            }
12685
12686            // Reflect the move in app info
12687            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12688            pkg.setApplicationInfoCodePath(pkg.codePath);
12689            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12690            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12691            pkg.setApplicationInfoResourcePath(pkg.codePath);
12692            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12693            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12694
12695            return true;
12696        }
12697
12698        int doPostInstall(int status, int uid) {
12699            if (status == PackageManager.INSTALL_SUCCEEDED) {
12700                cleanUp(move.fromUuid);
12701            } else {
12702                cleanUp(move.toUuid);
12703            }
12704            return status;
12705        }
12706
12707        @Override
12708        String getCodePath() {
12709            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12710        }
12711
12712        @Override
12713        String getResourcePath() {
12714            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12715        }
12716
12717        private boolean cleanUp(String volumeUuid) {
12718            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12719                    move.dataAppName);
12720            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12721            synchronized (mInstallLock) {
12722                // Clean up both app data and code
12723                removeDataDirsLI(volumeUuid, move.packageName);
12724                removeCodePathLI(codeFile);
12725            }
12726            return true;
12727        }
12728
12729        void cleanUpResourcesLI() {
12730            throw new UnsupportedOperationException();
12731        }
12732
12733        boolean doPostDeleteLI(boolean delete) {
12734            throw new UnsupportedOperationException();
12735        }
12736    }
12737
12738    static String getAsecPackageName(String packageCid) {
12739        int idx = packageCid.lastIndexOf("-");
12740        if (idx == -1) {
12741            return packageCid;
12742        }
12743        return packageCid.substring(0, idx);
12744    }
12745
12746    // Utility method used to create code paths based on package name and available index.
12747    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12748        String idxStr = "";
12749        int idx = 1;
12750        // Fall back to default value of idx=1 if prefix is not
12751        // part of oldCodePath
12752        if (oldCodePath != null) {
12753            String subStr = oldCodePath;
12754            // Drop the suffix right away
12755            if (suffix != null && subStr.endsWith(suffix)) {
12756                subStr = subStr.substring(0, subStr.length() - suffix.length());
12757            }
12758            // If oldCodePath already contains prefix find out the
12759            // ending index to either increment or decrement.
12760            int sidx = subStr.lastIndexOf(prefix);
12761            if (sidx != -1) {
12762                subStr = subStr.substring(sidx + prefix.length());
12763                if (subStr != null) {
12764                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12765                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12766                    }
12767                    try {
12768                        idx = Integer.parseInt(subStr);
12769                        if (idx <= 1) {
12770                            idx++;
12771                        } else {
12772                            idx--;
12773                        }
12774                    } catch(NumberFormatException e) {
12775                    }
12776                }
12777            }
12778        }
12779        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12780        return prefix + idxStr;
12781    }
12782
12783    private File getNextCodePath(File targetDir, String packageName) {
12784        int suffix = 1;
12785        File result;
12786        do {
12787            result = new File(targetDir, packageName + "-" + suffix);
12788            suffix++;
12789        } while (result.exists());
12790        return result;
12791    }
12792
12793    // Utility method that returns the relative package path with respect
12794    // to the installation directory. Like say for /data/data/com.test-1.apk
12795    // string com.test-1 is returned.
12796    static String deriveCodePathName(String codePath) {
12797        if (codePath == null) {
12798            return null;
12799        }
12800        final File codeFile = new File(codePath);
12801        final String name = codeFile.getName();
12802        if (codeFile.isDirectory()) {
12803            return name;
12804        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12805            final int lastDot = name.lastIndexOf('.');
12806            return name.substring(0, lastDot);
12807        } else {
12808            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12809            return null;
12810        }
12811    }
12812
12813    static class PackageInstalledInfo {
12814        String name;
12815        int uid;
12816        // The set of users that originally had this package installed.
12817        int[] origUsers;
12818        // The set of users that now have this package installed.
12819        int[] newUsers;
12820        PackageParser.Package pkg;
12821        int returnCode;
12822        String returnMsg;
12823        PackageRemovedInfo removedInfo;
12824        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12825
12826        public void setError(int code, String msg) {
12827            setReturnCode(code);
12828            setReturnMessage(msg);
12829            Slog.w(TAG, msg);
12830        }
12831
12832        public void setError(String msg, PackageParserException e) {
12833            setReturnCode(e.error);
12834            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12835            Slog.w(TAG, msg, e);
12836        }
12837
12838        public void setError(String msg, PackageManagerException e) {
12839            returnCode = e.error;
12840            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12841            Slog.w(TAG, msg, e);
12842        }
12843
12844        public void setReturnCode(int returnCode) {
12845            this.returnCode = returnCode;
12846            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12847            for (int i = 0; i < childCount; i++) {
12848                addedChildPackages.valueAt(i).returnCode = returnCode;
12849            }
12850        }
12851
12852        private void setReturnMessage(String returnMsg) {
12853            this.returnMsg = returnMsg;
12854            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12855            for (int i = 0; i < childCount; i++) {
12856                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12857            }
12858        }
12859
12860        // In some error cases we want to convey more info back to the observer
12861        String origPackage;
12862        String origPermission;
12863    }
12864
12865    /*
12866     * Install a non-existing package.
12867     */
12868    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12869            UserHandle user, String installerPackageName, String volumeUuid,
12870            PackageInstalledInfo res) {
12871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12872
12873        // Remember this for later, in case we need to rollback this install
12874        String pkgName = pkg.packageName;
12875
12876        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12877
12878        synchronized(mPackages) {
12879            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12880                // A package with the same name is already installed, though
12881                // it has been renamed to an older name.  The package we
12882                // are trying to install should be installed as an update to
12883                // the existing one, but that has not been requested, so bail.
12884                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12885                        + " without first uninstalling package running as "
12886                        + mSettings.mRenamedPackages.get(pkgName));
12887                return;
12888            }
12889            if (mPackages.containsKey(pkgName)) {
12890                // Don't allow installation over an existing package with the same name.
12891                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12892                        + " without first uninstalling.");
12893                return;
12894            }
12895        }
12896
12897        try {
12898            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12899                    System.currentTimeMillis(), user);
12900
12901            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12902
12903            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12904                prepareAppDataAfterInstall(newPackage);
12905
12906            } else {
12907                // Remove package from internal structures, but keep around any
12908                // data that might have already existed
12909                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12910                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12911            }
12912        } catch (PackageManagerException e) {
12913            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12914        }
12915
12916        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12917    }
12918
12919    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12920        // Can't rotate keys during boot or if sharedUser.
12921        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12922                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12923            return false;
12924        }
12925        // app is using upgradeKeySets; make sure all are valid
12926        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12927        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12928        for (int i = 0; i < upgradeKeySets.length; i++) {
12929            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12930                Slog.wtf(TAG, "Package "
12931                         + (oldPs.name != null ? oldPs.name : "<null>")
12932                         + " contains upgrade-key-set reference to unknown key-set: "
12933                         + upgradeKeySets[i]
12934                         + " reverting to signatures check.");
12935                return false;
12936            }
12937        }
12938        return true;
12939    }
12940
12941    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12942        // Upgrade keysets are being used.  Determine if new package has a superset of the
12943        // required keys.
12944        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12945        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12946        for (int i = 0; i < upgradeKeySets.length; i++) {
12947            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12948            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12949                return true;
12950            }
12951        }
12952        return false;
12953    }
12954
12955    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12956            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12957        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12958
12959        final PackageParser.Package oldPackage;
12960        final String pkgName = pkg.packageName;
12961        final int[] allUsers;
12962
12963        // First find the old package info and check signatures
12964        synchronized(mPackages) {
12965            oldPackage = mPackages.get(pkgName);
12966            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12967            if (isEphemeral && !oldIsEphemeral) {
12968                // can't downgrade from full to ephemeral
12969                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12970                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
12971                return;
12972            }
12973            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12974            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12975            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12976                if (!checkUpgradeKeySetLP(ps, pkg)) {
12977                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12978                            "New package not signed by keys specified by upgrade-keysets: "
12979                                    + pkgName);
12980                    return;
12981                }
12982            } else {
12983                // default to original signature matching
12984                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12985                        != PackageManager.SIGNATURE_MATCH) {
12986                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12987                            "New package has a different signature: " + pkgName);
12988                    return;
12989                }
12990            }
12991
12992            // In case of rollback, remember per-user/profile install state
12993            allUsers = sUserManager.getUserIds();
12994        }
12995
12996        // Update what is removed
12997        res.removedInfo = new PackageRemovedInfo();
12998        res.removedInfo.uid = oldPackage.applicationInfo.uid;
12999        res.removedInfo.removedPackage = oldPackage.packageName;
13000        res.removedInfo.isUpdate = true;
13001        final int childCount = (oldPackage.childPackages != null)
13002                ? oldPackage.childPackages.size() : 0;
13003        for (int i = 0; i < childCount; i++) {
13004            boolean childPackageUpdated = false;
13005            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13006            if (res.addedChildPackages != null) {
13007                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13008                if (childRes != null) {
13009                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13010                    childRes.removedInfo.removedPackage = childPkg.packageName;
13011                    childRes.removedInfo.isUpdate = true;
13012                    childPackageUpdated = true;
13013                }
13014            }
13015            if (!childPackageUpdated) {
13016                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13017                childRemovedRes.removedPackage = childPkg.packageName;
13018                childRemovedRes.isUpdate = false;
13019                childRemovedRes.dataRemoved = true;
13020                synchronized (mPackages) {
13021                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13022                    if (childPs != null) {
13023                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13024                    }
13025                }
13026                if (res.removedInfo.removedChildPackages == null) {
13027                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13028                }
13029                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13030            }
13031        }
13032
13033        boolean sysPkg = (isSystemApp(oldPackage));
13034        if (sysPkg) {
13035            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13036                    user, allUsers, installerPackageName, res);
13037        } else {
13038            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13039                    user, allUsers, installerPackageName, res);
13040        }
13041    }
13042
13043    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13044            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13045            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13046        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13047                + deletedPackage);
13048
13049        String pkgName = deletedPackage.packageName;
13050        boolean deletedPkg = true;
13051        boolean addedPkg = false;
13052
13053        final long origUpdateTime = (pkg.mExtras != null)
13054                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13055
13056        // First delete the existing package while retaining the data directory
13057        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13058                res.removedInfo, true, pkg)) {
13059            // If the existing package wasn't successfully deleted
13060            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13061            deletedPkg = false;
13062        } else {
13063            // Successfully deleted the old package; proceed with replace.
13064
13065            // If deleted package lived in a container, give users a chance to
13066            // relinquish resources before killing.
13067            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13068                if (DEBUG_INSTALL) {
13069                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13070                }
13071                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13072                final ArrayList<String> pkgList = new ArrayList<String>(1);
13073                pkgList.add(deletedPackage.applicationInfo.packageName);
13074                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13075            }
13076
13077            deleteCodeCacheDirsLI(pkg);
13078
13079            try {
13080                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13081                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13082                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13083                prepareAppDataAfterInstall(newPackage);
13084                addedPkg = true;
13085            } catch (PackageManagerException e) {
13086                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13087            }
13088        }
13089
13090        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13091            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13092
13093            // Revert all internal state mutations and added folders for the failed install
13094            if (addedPkg) {
13095                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13096                        res.removedInfo, true, null);
13097            }
13098
13099            // Restore the old package
13100            if (deletedPkg) {
13101                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13102                File restoreFile = new File(deletedPackage.codePath);
13103                // Parse old package
13104                boolean oldExternal = isExternal(deletedPackage);
13105                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13106                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13107                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13108                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13109                try {
13110                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13111                            null);
13112                } catch (PackageManagerException e) {
13113                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13114                            + e.getMessage());
13115                    return;
13116                }
13117
13118                synchronized (mPackages) {
13119                    // Ensure the installer package name up to date
13120                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13121
13122                    // Update permissions for restored package
13123                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13124
13125                    mSettings.writeLPr();
13126                }
13127
13128                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13129            }
13130        } else {
13131            synchronized (mPackages) {
13132                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13133                if (ps != null) {
13134                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13135                    if (res.removedInfo.removedChildPackages != null) {
13136                        final int childCount = res.removedInfo.removedChildPackages.size();
13137                        // Iterate in reverse as we may modify the collection
13138                        for (int i = childCount - 1; i >= 0; i--) {
13139                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13140                            if (res.addedChildPackages.containsKey(childPackageName)) {
13141                                res.removedInfo.removedChildPackages.removeAt(i);
13142                            } else {
13143                                PackageRemovedInfo childInfo = res.removedInfo
13144                                        .removedChildPackages.valueAt(i);
13145                                childInfo.removedForAllUsers = mPackages.get(
13146                                        childInfo.removedPackage) == null;
13147                            }
13148                        }
13149                    }
13150                }
13151            }
13152        }
13153    }
13154
13155    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13156            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13157            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13158        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13159                + ", old=" + deletedPackage);
13160
13161        final boolean disabledSystem;
13162
13163        // Set the system/privileged flags as needed
13164        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13165        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13166                != 0) {
13167            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13168        }
13169
13170        // Kill package processes including services, providers, etc.
13171        killPackage(deletedPackage, "replace sys pkg");
13172
13173        // Remove existing system package
13174        removePackageLI(deletedPackage, true);
13175
13176        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13177        if (!disabledSystem) {
13178            // We didn't need to disable the .apk as a current system package,
13179            // which means we are replacing another update that is already
13180            // installed.  We need to make sure to delete the older one's .apk.
13181            res.removedInfo.args = createInstallArgsForExisting(0,
13182                    deletedPackage.applicationInfo.getCodePath(),
13183                    deletedPackage.applicationInfo.getResourcePath(),
13184                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13185        } else {
13186            res.removedInfo.args = null;
13187        }
13188
13189        // Successfully disabled the old package. Now proceed with re-installation
13190        deleteCodeCacheDirsLI(pkg);
13191
13192        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13193        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13194                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13195
13196        PackageParser.Package newPackage = null;
13197        try {
13198            // Add the package to the internal data structures
13199            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13200
13201            // Set the update and install times
13202            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13203            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13204                    System.currentTimeMillis());
13205
13206            // Check for shared user id changes
13207            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13208                    deletedPackage, newPackage);
13209            if (invalidPackageName != null) {
13210                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13211                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13212                                + " to " + invalidPackageName);
13213            }
13214
13215            // Update the package dynamic state if succeeded
13216            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13217                // Now that the install succeeded make sure we remove data
13218                // directories for any child package the update removed.
13219                final int deletedChildCount = (deletedPackage.childPackages != null)
13220                        ? deletedPackage.childPackages.size() : 0;
13221                final int newChildCount = (newPackage.childPackages != null)
13222                        ? newPackage.childPackages.size() : 0;
13223                for (int i = 0; i < deletedChildCount; i++) {
13224                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13225                    boolean childPackageDeleted = true;
13226                    for (int j = 0; j < newChildCount; j++) {
13227                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13228                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13229                            childPackageDeleted = false;
13230                            break;
13231                        }
13232                    }
13233                    if (childPackageDeleted) {
13234                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13235                                deletedChildPkg.packageName);
13236                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13237                            PackageRemovedInfo removedChildRes = res.removedInfo
13238                                    .removedChildPackages.get(deletedChildPkg.packageName);
13239                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13240                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13241                        }
13242                    }
13243                }
13244
13245                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13246                prepareAppDataAfterInstall(newPackage);
13247            }
13248        } catch (PackageManagerException e) {
13249            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13250            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13251        }
13252
13253        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13254            // Re installation failed. Restore old information
13255            // Remove new pkg information
13256            if (newPackage != null) {
13257                removeInstalledPackageLI(newPackage, true);
13258            }
13259            // Add back the old system package
13260            try {
13261                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13262            } catch (PackageManagerException e) {
13263                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13264            }
13265
13266            synchronized (mPackages) {
13267                if (disabledSystem) {
13268                    enableSystemPackageLPw(deletedPackage);
13269                }
13270
13271                // Ensure the installer package name up to date
13272                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13273
13274                // Update permissions for restored package
13275                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13276
13277                mSettings.writeLPr();
13278            }
13279
13280            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13281                    + " after failed upgrade");
13282        }
13283    }
13284
13285    /**
13286     * Checks whether the parent or any of the child packages have a change shared
13287     * user. For a package to be a valid update the shred users of the parent and
13288     * the children should match. We may later support changing child shared users.
13289     * @param oldPkg The updated package.
13290     * @param newPkg The update package.
13291     * @return The shared user that change between the versions.
13292     */
13293    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13294            PackageParser.Package newPkg) {
13295        // Check parent shared user
13296        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13297            return newPkg.packageName;
13298        }
13299        // Check child shared users
13300        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13301        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13302        for (int i = 0; i < newChildCount; i++) {
13303            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13304            // If this child was present, did it have the same shared user?
13305            for (int j = 0; j < oldChildCount; j++) {
13306                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13307                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13308                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13309                    return newChildPkg.packageName;
13310                }
13311            }
13312        }
13313        return null;
13314    }
13315
13316    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13317        // Remove the lib path for the parent package
13318        PackageSetting ps = (PackageSetting) pkg.mExtras;
13319        if (ps != null) {
13320            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13321        }
13322        // Remove the lib path for the child packages
13323        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13324        for (int i = 0; i < childCount; i++) {
13325            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13326            if (ps != null) {
13327                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13328            }
13329        }
13330    }
13331
13332    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13333        // Enable the parent package
13334        mSettings.enableSystemPackageLPw(pkg.packageName);
13335        // Enable the child packages
13336        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13337        for (int i = 0; i < childCount; i++) {
13338            PackageParser.Package childPkg = pkg.childPackages.get(i);
13339            mSettings.enableSystemPackageLPw(childPkg.packageName);
13340        }
13341    }
13342
13343    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13344            PackageParser.Package newPkg) {
13345        // Disable the parent package (parent always replaced)
13346        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13347        // Disable the child packages
13348        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13349        for (int i = 0; i < childCount; i++) {
13350            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13351            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13352            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13353        }
13354        return disabled;
13355    }
13356
13357    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13358            String installerPackageName) {
13359        // Enable the parent package
13360        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13361        // Enable the child packages
13362        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13363        for (int i = 0; i < childCount; i++) {
13364            PackageParser.Package childPkg = pkg.childPackages.get(i);
13365            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13366        }
13367    }
13368
13369    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13370        // Collect all used permissions in the UID
13371        ArraySet<String> usedPermissions = new ArraySet<>();
13372        final int packageCount = su.packages.size();
13373        for (int i = 0; i < packageCount; i++) {
13374            PackageSetting ps = su.packages.valueAt(i);
13375            if (ps.pkg == null) {
13376                continue;
13377            }
13378            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13379            for (int j = 0; j < requestedPermCount; j++) {
13380                String permission = ps.pkg.requestedPermissions.get(j);
13381                BasePermission bp = mSettings.mPermissions.get(permission);
13382                if (bp != null) {
13383                    usedPermissions.add(permission);
13384                }
13385            }
13386        }
13387
13388        PermissionsState permissionsState = su.getPermissionsState();
13389        // Prune install permissions
13390        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13391        final int installPermCount = installPermStates.size();
13392        for (int i = installPermCount - 1; i >= 0;  i--) {
13393            PermissionState permissionState = installPermStates.get(i);
13394            if (!usedPermissions.contains(permissionState.getName())) {
13395                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13396                if (bp != null) {
13397                    permissionsState.revokeInstallPermission(bp);
13398                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13399                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13400                }
13401            }
13402        }
13403
13404        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13405
13406        // Prune runtime permissions
13407        for (int userId : allUserIds) {
13408            List<PermissionState> runtimePermStates = permissionsState
13409                    .getRuntimePermissionStates(userId);
13410            final int runtimePermCount = runtimePermStates.size();
13411            for (int i = runtimePermCount - 1; i >= 0; i--) {
13412                PermissionState permissionState = runtimePermStates.get(i);
13413                if (!usedPermissions.contains(permissionState.getName())) {
13414                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13415                    if (bp != null) {
13416                        permissionsState.revokeRuntimePermission(bp, userId);
13417                        permissionsState.updatePermissionFlags(bp, userId,
13418                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13419                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13420                                runtimePermissionChangedUserIds, userId);
13421                    }
13422                }
13423            }
13424        }
13425
13426        return runtimePermissionChangedUserIds;
13427    }
13428
13429    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13430            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13431        // Update the parent package setting
13432        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13433                res, user);
13434        // Update the child packages setting
13435        final int childCount = (newPackage.childPackages != null)
13436                ? newPackage.childPackages.size() : 0;
13437        for (int i = 0; i < childCount; i++) {
13438            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13439            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13440            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13441                    childRes.origUsers, childRes, user);
13442        }
13443    }
13444
13445    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13446            String installerPackageName, int[] allUsers, int[] installedForUsers,
13447            PackageInstalledInfo res, UserHandle user) {
13448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13449
13450        String pkgName = newPackage.packageName;
13451        synchronized (mPackages) {
13452            //write settings. the installStatus will be incomplete at this stage.
13453            //note that the new package setting would have already been
13454            //added to mPackages. It hasn't been persisted yet.
13455            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13456            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13457            mSettings.writeLPr();
13458            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13459        }
13460
13461        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13462        synchronized (mPackages) {
13463            updatePermissionsLPw(newPackage.packageName, newPackage,
13464                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13465                            ? UPDATE_PERMISSIONS_ALL : 0));
13466            // For system-bundled packages, we assume that installing an upgraded version
13467            // of the package implies that the user actually wants to run that new code,
13468            // so we enable the package.
13469            PackageSetting ps = mSettings.mPackages.get(pkgName);
13470            final int userId = user.getIdentifier();
13471            if (ps != null) {
13472                if (isSystemApp(newPackage)) {
13473                    if (DEBUG_INSTALL) {
13474                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13475                    }
13476                    // Enable system package for requested users
13477                    if (res.origUsers != null) {
13478                        for (int origUserId : res.origUsers) {
13479                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13480                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13481                                        origUserId, installerPackageName);
13482                            }
13483                        }
13484                    }
13485                    // Also convey the prior install/uninstall state
13486                    if (allUsers != null && installedForUsers != null) {
13487                        for (int currentUserId : allUsers) {
13488                            final boolean installed = ArrayUtils.contains(
13489                                    installedForUsers, currentUserId);
13490                            if (DEBUG_INSTALL) {
13491                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13492                            }
13493                            ps.setInstalled(installed, currentUserId);
13494                        }
13495                        // these install state changes will be persisted in the
13496                        // upcoming call to mSettings.writeLPr().
13497                    }
13498                }
13499                // It's implied that when a user requests installation, they want the app to be
13500                // installed and enabled.
13501                if (userId != UserHandle.USER_ALL) {
13502                    ps.setInstalled(true, userId);
13503                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13504                }
13505            }
13506            res.name = pkgName;
13507            res.uid = newPackage.applicationInfo.uid;
13508            res.pkg = newPackage;
13509            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13510            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13511            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13512            //to update install status
13513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13514            mSettings.writeLPr();
13515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13516        }
13517
13518        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13519    }
13520
13521    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13522        try {
13523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13524            installPackageLI(args, res);
13525        } finally {
13526            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13527        }
13528    }
13529
13530    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13531        final int installFlags = args.installFlags;
13532        final String installerPackageName = args.installerPackageName;
13533        final String volumeUuid = args.volumeUuid;
13534        final File tmpPackageFile = new File(args.getCodePath());
13535        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13536        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13537                || (args.volumeUuid != null));
13538        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13539        boolean replace = false;
13540        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13541        if (args.move != null) {
13542            // moving a complete application; perform an initial scan on the new install location
13543            scanFlags |= SCAN_INITIAL;
13544        }
13545
13546        // Result object to be returned
13547        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13548
13549        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13550
13551        // Sanity check
13552        if (ephemeral && (forwardLocked || onExternal)) {
13553            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13554                    + " external=" + onExternal);
13555            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13556            return;
13557        }
13558
13559        // Retrieve PackageSettings and parse package
13560        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13561                | PackageParser.PARSE_ENFORCE_CODE
13562                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13563                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13564                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13565        PackageParser pp = new PackageParser();
13566        pp.setSeparateProcesses(mSeparateProcesses);
13567        pp.setDisplayMetrics(mMetrics);
13568
13569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13570        final PackageParser.Package pkg;
13571        try {
13572            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13573        } catch (PackageParserException e) {
13574            res.setError("Failed parse during installPackageLI", e);
13575            return;
13576        } finally {
13577            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13578        }
13579
13580        // If we are installing a clustered package add results for the children
13581        if (pkg.childPackages != null) {
13582            synchronized (mPackages) {
13583                final int childCount = pkg.childPackages.size();
13584                for (int i = 0; i < childCount; i++) {
13585                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13586                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13587                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13588                    childRes.pkg = childPkg;
13589                    childRes.name = childPkg.packageName;
13590                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13591                    if (childPs != null) {
13592                        childRes.origUsers = childPs.queryInstalledUsers(
13593                                sUserManager.getUserIds(), true);
13594                    }
13595                    if ((mPackages.containsKey(childPkg.packageName))) {
13596                        childRes.removedInfo = new PackageRemovedInfo();
13597                        childRes.removedInfo.removedPackage = childPkg.packageName;
13598                    }
13599                    if (res.addedChildPackages == null) {
13600                        res.addedChildPackages = new ArrayMap<>();
13601                    }
13602                    res.addedChildPackages.put(childPkg.packageName, childRes);
13603                }
13604            }
13605        }
13606
13607        // If package doesn't declare API override, mark that we have an install
13608        // time CPU ABI override.
13609        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13610            pkg.cpuAbiOverride = args.abiOverride;
13611        }
13612
13613        String pkgName = res.name = pkg.packageName;
13614        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13615            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13616                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13617                return;
13618            }
13619        }
13620
13621        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13622        try {
13623            PackageParser.collectCertificates(pkg, parseFlags);
13624        } catch (PackageParserException e) {
13625            res.setError("Failed collect during installPackageLI", e);
13626            return;
13627        } finally {
13628            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13629        }
13630
13631        // Get rid of all references to package scan path via parser.
13632        pp = null;
13633        String oldCodePath = null;
13634        boolean systemApp = false;
13635        synchronized (mPackages) {
13636            // Check if installing already existing package
13637            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13638                String oldName = mSettings.mRenamedPackages.get(pkgName);
13639                if (pkg.mOriginalPackages != null
13640                        && pkg.mOriginalPackages.contains(oldName)
13641                        && mPackages.containsKey(oldName)) {
13642                    // This package is derived from an original package,
13643                    // and this device has been updating from that original
13644                    // name.  We must continue using the original name, so
13645                    // rename the new package here.
13646                    pkg.setPackageName(oldName);
13647                    pkgName = pkg.packageName;
13648                    replace = true;
13649                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13650                            + oldName + " pkgName=" + pkgName);
13651                } else if (mPackages.containsKey(pkgName)) {
13652                    // This package, under its official name, already exists
13653                    // on the device; we should replace it.
13654                    replace = true;
13655                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13656                }
13657
13658                // Child packages are installed through the parent package
13659                if (pkg.parentPackage != null) {
13660                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13661                            "Package " + pkg.packageName + " is child of package "
13662                                    + pkg.parentPackage.parentPackage + ". Child packages "
13663                                    + "can be updated only through the parent package.");
13664                    return;
13665                }
13666
13667                if (replace) {
13668                    // Prevent apps opting out from runtime permissions
13669                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13670                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13671                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13672                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13673                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13674                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13675                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13676                                        + " doesn't support runtime permissions but the old"
13677                                        + " target SDK " + oldTargetSdk + " does.");
13678                        return;
13679                    }
13680
13681                    // Prevent installing of child packages
13682                    if (oldPackage.parentPackage != null) {
13683                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13684                                "Package " + pkg.packageName + " is child of package "
13685                                        + oldPackage.parentPackage + ". Child packages "
13686                                        + "can be updated only through the parent package.");
13687                        return;
13688                    }
13689                }
13690            }
13691
13692            PackageSetting ps = mSettings.mPackages.get(pkgName);
13693            if (ps != null) {
13694                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13695
13696                // Quick sanity check that we're signed correctly if updating;
13697                // we'll check this again later when scanning, but we want to
13698                // bail early here before tripping over redefined permissions.
13699                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13700                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13701                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13702                                + pkg.packageName + " upgrade keys do not match the "
13703                                + "previously installed version");
13704                        return;
13705                    }
13706                } else {
13707                    try {
13708                        verifySignaturesLP(ps, pkg);
13709                    } catch (PackageManagerException e) {
13710                        res.setError(e.error, e.getMessage());
13711                        return;
13712                    }
13713                }
13714
13715                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13716                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13717                    systemApp = (ps.pkg.applicationInfo.flags &
13718                            ApplicationInfo.FLAG_SYSTEM) != 0;
13719                }
13720                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13721            }
13722
13723            // Check whether the newly-scanned package wants to define an already-defined perm
13724            int N = pkg.permissions.size();
13725            for (int i = N-1; i >= 0; i--) {
13726                PackageParser.Permission perm = pkg.permissions.get(i);
13727                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13728                if (bp != null) {
13729                    // If the defining package is signed with our cert, it's okay.  This
13730                    // also includes the "updating the same package" case, of course.
13731                    // "updating same package" could also involve key-rotation.
13732                    final boolean sigsOk;
13733                    if (bp.sourcePackage.equals(pkg.packageName)
13734                            && (bp.packageSetting instanceof PackageSetting)
13735                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13736                                    scanFlags))) {
13737                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13738                    } else {
13739                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13740                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13741                    }
13742                    if (!sigsOk) {
13743                        // If the owning package is the system itself, we log but allow
13744                        // install to proceed; we fail the install on all other permission
13745                        // redefinitions.
13746                        if (!bp.sourcePackage.equals("android")) {
13747                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13748                                    + pkg.packageName + " attempting to redeclare permission "
13749                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13750                            res.origPermission = perm.info.name;
13751                            res.origPackage = bp.sourcePackage;
13752                            return;
13753                        } else {
13754                            Slog.w(TAG, "Package " + pkg.packageName
13755                                    + " attempting to redeclare system permission "
13756                                    + perm.info.name + "; ignoring new declaration");
13757                            pkg.permissions.remove(i);
13758                        }
13759                    }
13760                }
13761            }
13762        }
13763
13764        if (systemApp) {
13765            if (onExternal) {
13766                // Abort update; system app can't be replaced with app on sdcard
13767                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13768                        "Cannot install updates to system apps on sdcard");
13769                return;
13770            } else if (ephemeral) {
13771                // Abort update; system app can't be replaced with an ephemeral app
13772                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13773                        "Cannot update a system app with an ephemeral app");
13774                return;
13775            }
13776        }
13777
13778        if (args.move != null) {
13779            // We did an in-place move, so dex is ready to roll
13780            scanFlags |= SCAN_NO_DEX;
13781            scanFlags |= SCAN_MOVE;
13782
13783            synchronized (mPackages) {
13784                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13785                if (ps == null) {
13786                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13787                            "Missing settings for moved package " + pkgName);
13788                }
13789
13790                // We moved the entire application as-is, so bring over the
13791                // previously derived ABI information.
13792                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13793                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13794            }
13795
13796        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13797            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13798            scanFlags |= SCAN_NO_DEX;
13799
13800            try {
13801                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13802                    args.abiOverride : pkg.cpuAbiOverride);
13803                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13804                        true /* extract libs */);
13805            } catch (PackageManagerException pme) {
13806                Slog.e(TAG, "Error deriving application ABI", pme);
13807                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13808                return;
13809            }
13810
13811            // Extract package to save the VM unzipping the APK in memory during
13812            // launch. Only do this if profile-guided compilation is enabled because
13813            // otherwise BackgroundDexOptService will not dexopt the package later.
13814            if (mUseJitProfiles) {
13815                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13816                // Do not run PackageDexOptimizer through the local performDexOpt
13817                // method because `pkg` is not in `mPackages` yet.
13818                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13819                        false /* useProfiles */, true /* extractOnly */);
13820                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13821                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13822                    String msg = "Extracking package failed for " + pkgName;
13823                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13824                    return;
13825                }
13826            }
13827        }
13828
13829        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13830            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13831            return;
13832        }
13833
13834        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13835
13836        if (replace) {
13837            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13838                    installerPackageName, res);
13839        } else {
13840            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13841                    args.user, installerPackageName, volumeUuid, res);
13842        }
13843        synchronized (mPackages) {
13844            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13845            if (ps != null) {
13846                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13847            }
13848
13849            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13850            for (int i = 0; i < childCount; i++) {
13851                PackageParser.Package childPkg = pkg.childPackages.get(i);
13852                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13853                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13854                if (childPs != null) {
13855                    childRes.newUsers = childPs.queryInstalledUsers(
13856                            sUserManager.getUserIds(), true);
13857                }
13858            }
13859        }
13860    }
13861
13862    private void startIntentFilterVerifications(int userId, boolean replacing,
13863            PackageParser.Package pkg) {
13864        if (mIntentFilterVerifierComponent == null) {
13865            Slog.w(TAG, "No IntentFilter verification will not be done as "
13866                    + "there is no IntentFilterVerifier available!");
13867            return;
13868        }
13869
13870        final int verifierUid = getPackageUid(
13871                mIntentFilterVerifierComponent.getPackageName(),
13872                MATCH_DEBUG_TRIAGED_MISSING,
13873                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13874
13875        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13876        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13877        mHandler.sendMessage(msg);
13878
13879        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13880        for (int i = 0; i < childCount; i++) {
13881            PackageParser.Package childPkg = pkg.childPackages.get(i);
13882            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13883            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13884            mHandler.sendMessage(msg);
13885        }
13886    }
13887
13888    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13889            PackageParser.Package pkg) {
13890        int size = pkg.activities.size();
13891        if (size == 0) {
13892            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13893                    "No activity, so no need to verify any IntentFilter!");
13894            return;
13895        }
13896
13897        final boolean hasDomainURLs = hasDomainURLs(pkg);
13898        if (!hasDomainURLs) {
13899            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13900                    "No domain URLs, so no need to verify any IntentFilter!");
13901            return;
13902        }
13903
13904        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13905                + " if any IntentFilter from the " + size
13906                + " Activities needs verification ...");
13907
13908        int count = 0;
13909        final String packageName = pkg.packageName;
13910
13911        synchronized (mPackages) {
13912            // If this is a new install and we see that we've already run verification for this
13913            // package, we have nothing to do: it means the state was restored from backup.
13914            if (!replacing) {
13915                IntentFilterVerificationInfo ivi =
13916                        mSettings.getIntentFilterVerificationLPr(packageName);
13917                if (ivi != null) {
13918                    if (DEBUG_DOMAIN_VERIFICATION) {
13919                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13920                                + ivi.getStatusString());
13921                    }
13922                    return;
13923                }
13924            }
13925
13926            // If any filters need to be verified, then all need to be.
13927            boolean needToVerify = false;
13928            for (PackageParser.Activity a : pkg.activities) {
13929                for (ActivityIntentInfo filter : a.intents) {
13930                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13931                        if (DEBUG_DOMAIN_VERIFICATION) {
13932                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13933                        }
13934                        needToVerify = true;
13935                        break;
13936                    }
13937                }
13938            }
13939
13940            if (needToVerify) {
13941                final int verificationId = mIntentFilterVerificationToken++;
13942                for (PackageParser.Activity a : pkg.activities) {
13943                    for (ActivityIntentInfo filter : a.intents) {
13944                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13945                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13946                                    "Verification needed for IntentFilter:" + filter.toString());
13947                            mIntentFilterVerifier.addOneIntentFilterVerification(
13948                                    verifierUid, userId, verificationId, filter, packageName);
13949                            count++;
13950                        }
13951                    }
13952                }
13953            }
13954        }
13955
13956        if (count > 0) {
13957            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13958                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13959                    +  " for userId:" + userId);
13960            mIntentFilterVerifier.startVerifications(userId);
13961        } else {
13962            if (DEBUG_DOMAIN_VERIFICATION) {
13963                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13964            }
13965        }
13966    }
13967
13968    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13969        final ComponentName cn  = filter.activity.getComponentName();
13970        final String packageName = cn.getPackageName();
13971
13972        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13973                packageName);
13974        if (ivi == null) {
13975            return true;
13976        }
13977        int status = ivi.getStatus();
13978        switch (status) {
13979            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13980            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13981                return true;
13982
13983            default:
13984                // Nothing to do
13985                return false;
13986        }
13987    }
13988
13989    private static boolean isMultiArch(ApplicationInfo info) {
13990        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13991    }
13992
13993    private static boolean isExternal(PackageParser.Package pkg) {
13994        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13995    }
13996
13997    private static boolean isExternal(PackageSetting ps) {
13998        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13999    }
14000
14001    private static boolean isEphemeral(PackageParser.Package pkg) {
14002        return pkg.applicationInfo.isEphemeralApp();
14003    }
14004
14005    private static boolean isEphemeral(PackageSetting ps) {
14006        return ps.pkg != null && isEphemeral(ps.pkg);
14007    }
14008
14009    private static boolean isSystemApp(PackageParser.Package pkg) {
14010        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14011    }
14012
14013    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14014        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14015    }
14016
14017    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14018        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14019    }
14020
14021    private static boolean isSystemApp(PackageSetting ps) {
14022        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14023    }
14024
14025    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14026        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14027    }
14028
14029    private int packageFlagsToInstallFlags(PackageSetting ps) {
14030        int installFlags = 0;
14031        if (isEphemeral(ps)) {
14032            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14033        }
14034        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14035            // This existing package was an external ASEC install when we have
14036            // the external flag without a UUID
14037            installFlags |= PackageManager.INSTALL_EXTERNAL;
14038        }
14039        if (ps.isForwardLocked()) {
14040            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14041        }
14042        return installFlags;
14043    }
14044
14045    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14046        if (isExternal(pkg)) {
14047            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14048                return StorageManager.UUID_PRIMARY_PHYSICAL;
14049            } else {
14050                return pkg.volumeUuid;
14051            }
14052        } else {
14053            return StorageManager.UUID_PRIVATE_INTERNAL;
14054        }
14055    }
14056
14057    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14058        if (isExternal(pkg)) {
14059            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14060                return mSettings.getExternalVersion();
14061            } else {
14062                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14063            }
14064        } else {
14065            return mSettings.getInternalVersion();
14066        }
14067    }
14068
14069    private void deleteTempPackageFiles() {
14070        final FilenameFilter filter = new FilenameFilter() {
14071            public boolean accept(File dir, String name) {
14072                return name.startsWith("vmdl") && name.endsWith(".tmp");
14073            }
14074        };
14075        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14076            file.delete();
14077        }
14078    }
14079
14080    @Override
14081    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14082            int flags) {
14083        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14084                flags);
14085    }
14086
14087    @Override
14088    public void deletePackage(final String packageName,
14089            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14090        mContext.enforceCallingOrSelfPermission(
14091                android.Manifest.permission.DELETE_PACKAGES, null);
14092        Preconditions.checkNotNull(packageName);
14093        Preconditions.checkNotNull(observer);
14094        final int uid = Binder.getCallingUid();
14095        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14096        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14097        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14098            mContext.enforceCallingOrSelfPermission(
14099                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14100                    "deletePackage for user " + userId);
14101        }
14102
14103        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14104            try {
14105                observer.onPackageDeleted(packageName,
14106                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14107            } catch (RemoteException re) {
14108            }
14109            return;
14110        }
14111
14112        for (int currentUserId : users) {
14113            if (getBlockUninstallForUser(packageName, currentUserId)) {
14114                try {
14115                    observer.onPackageDeleted(packageName,
14116                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14117                } catch (RemoteException re) {
14118                }
14119                return;
14120            }
14121        }
14122
14123        if (DEBUG_REMOVE) {
14124            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
14125        }
14126        // Queue up an async operation since the package deletion may take a little while.
14127        mHandler.post(new Runnable() {
14128            public void run() {
14129                mHandler.removeCallbacks(this);
14130                final int returnCode = deletePackageX(packageName, userId, flags);
14131                try {
14132                    observer.onPackageDeleted(packageName, returnCode, null);
14133                } catch (RemoteException e) {
14134                    Log.i(TAG, "Observer no longer exists.");
14135                } //end catch
14136            } //end run
14137        });
14138    }
14139
14140    @Override
14141    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14142        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14143    }
14144
14145    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14146        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14147                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14148        try {
14149            if (dpm != null) {
14150                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14151                        /* callingUserOnly =*/ false);
14152                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14153                        : deviceOwnerComponentName.getPackageName();
14154                // Does the package contains the device owner?
14155                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14156                // this check is probably not needed, since DO should be registered as a device
14157                // admin on some user too. (Original bug for this: b/17657954)
14158                if (packageName.equals(deviceOwnerPackageName)) {
14159                    return true;
14160                }
14161                // Does it contain a device admin for any user?
14162                int[] users;
14163                if (userId == UserHandle.USER_ALL) {
14164                    users = sUserManager.getUserIds();
14165                } else {
14166                    users = new int[]{userId};
14167                }
14168                for (int i = 0; i < users.length; ++i) {
14169                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14170                        return true;
14171                    }
14172                }
14173            }
14174        } catch (RemoteException e) {
14175        }
14176        return false;
14177    }
14178
14179    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14180        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14181    }
14182
14183    /**
14184     *  This method is an internal method that could be get invoked either
14185     *  to delete an installed package or to clean up a failed installation.
14186     *  After deleting an installed package, a broadcast is sent to notify any
14187     *  listeners that the package has been installed. For cleaning up a failed
14188     *  installation, the broadcast is not necessary since the package's
14189     *  installation wouldn't have sent the initial broadcast either
14190     *  The key steps in deleting a package are
14191     *  deleting the package information in internal structures like mPackages,
14192     *  deleting the packages base directories through installd
14193     *  updating mSettings to reflect current status
14194     *  persisting settings for later use
14195     *  sending a broadcast if necessary
14196     */
14197    private int deletePackageX(String packageName, int userId, int flags) {
14198        final PackageRemovedInfo info = new PackageRemovedInfo();
14199        final boolean res;
14200
14201        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14202                ? UserHandle.ALL : new UserHandle(userId);
14203
14204        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14205            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14206            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14207        }
14208
14209        PackageSetting uninstalledPs = null;
14210
14211        // for the uninstall-updates case and restricted profiles, remember the per-
14212        // user handle installed state
14213        int[] allUsers;
14214        synchronized (mPackages) {
14215            uninstalledPs = mSettings.mPackages.get(packageName);
14216            if (uninstalledPs == null) {
14217                Slog.w(TAG, "Not removing non-existent package " + packageName);
14218                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14219            }
14220            allUsers = sUserManager.getUserIds();
14221            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14222        }
14223
14224        synchronized (mInstallLock) {
14225            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14226            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14227                    flags | REMOVE_CHATTY, info, true, null);
14228            synchronized (mPackages) {
14229                if (res) {
14230                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14231                }
14232            }
14233        }
14234
14235        if (res) {
14236            info.sendPackageRemovedBroadcasts();
14237            info.sendSystemPackageUpdatedBroadcasts();
14238            info.sendSystemPackageAppearedBroadcasts();
14239        }
14240        // Force a gc here.
14241        Runtime.getRuntime().gc();
14242        // Delete the resources here after sending the broadcast to let
14243        // other processes clean up before deleting resources.
14244        if (info.args != null) {
14245            synchronized (mInstallLock) {
14246                info.args.doPostDeleteLI(true);
14247            }
14248        }
14249
14250        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14251    }
14252
14253    class PackageRemovedInfo {
14254        String removedPackage;
14255        int uid = -1;
14256        int removedAppId = -1;
14257        int[] origUsers;
14258        int[] removedUsers = null;
14259        boolean isRemovedPackageSystemUpdate = false;
14260        boolean isUpdate;
14261        boolean dataRemoved;
14262        boolean removedForAllUsers;
14263        // Clean up resources deleted packages.
14264        InstallArgs args = null;
14265        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14266        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14267
14268        void sendPackageRemovedBroadcasts() {
14269            sendPackageRemovedBroadcastInternal();
14270            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14271            for (int i = 0; i < childCount; i++) {
14272                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14273                childInfo.sendPackageRemovedBroadcastInternal();
14274            }
14275        }
14276
14277        void sendSystemPackageUpdatedBroadcasts() {
14278            if (isRemovedPackageSystemUpdate) {
14279                sendSystemPackageUpdatedBroadcastsInternal();
14280                final int childCount = (removedChildPackages != null)
14281                        ? removedChildPackages.size() : 0;
14282                for (int i = 0; i < childCount; i++) {
14283                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14284                    if (childInfo.isRemovedPackageSystemUpdate) {
14285                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14286                    }
14287                }
14288            }
14289        }
14290
14291        void sendSystemPackageAppearedBroadcasts() {
14292            final int packageCount = (appearedChildPackages != null)
14293                    ? appearedChildPackages.size() : 0;
14294            for (int i = 0; i < packageCount; i++) {
14295                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14296                for (int userId : installedInfo.newUsers) {
14297                    sendPackageAddedForUser(installedInfo.name, true,
14298                            UserHandle.getAppId(installedInfo.uid), userId);
14299                }
14300            }
14301        }
14302
14303        private void sendSystemPackageUpdatedBroadcastsInternal() {
14304            Bundle extras = new Bundle(2);
14305            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14306            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14307            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14308                    extras, 0, null, null, null);
14309            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14310                    extras, 0, null, null, null);
14311            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14312                    null, 0, removedPackage, null, null);
14313        }
14314
14315        private void sendPackageRemovedBroadcastInternal() {
14316            Bundle extras = new Bundle(2);
14317            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14318            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14319            if (isUpdate || isRemovedPackageSystemUpdate) {
14320                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14321            }
14322            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14323            if (removedPackage != null) {
14324                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14325                        extras, 0, null, null, removedUsers);
14326                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14327                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14328                            removedPackage, extras, 0, null, null, removedUsers);
14329                }
14330            }
14331            if (removedAppId >= 0) {
14332                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14333                        removedUsers);
14334            }
14335        }
14336    }
14337
14338    /*
14339     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14340     * flag is not set, the data directory is removed as well.
14341     * make sure this flag is set for partially installed apps. If not its meaningless to
14342     * delete a partially installed application.
14343     */
14344    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14345            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14346        String packageName = ps.name;
14347        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14348        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14349        // Retrieve object to delete permissions for shared user later on
14350        final PackageSetting deletedPs;
14351        // reader
14352        synchronized (mPackages) {
14353            deletedPs = mSettings.mPackages.get(packageName);
14354            if (outInfo != null) {
14355                outInfo.removedPackage = packageName;
14356                outInfo.removedUsers = deletedPs != null
14357                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14358                        : null;
14359            }
14360        }
14361        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14362            removeDataDirsLI(ps.volumeUuid, packageName);
14363            if (outInfo != null) {
14364                outInfo.dataRemoved = true;
14365            }
14366            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14367        }
14368        // writer
14369        synchronized (mPackages) {
14370            if (deletedPs != null) {
14371                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14372                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14373                    clearDefaultBrowserIfNeeded(packageName);
14374                    if (outInfo != null) {
14375                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14376                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14377                    }
14378                    updatePermissionsLPw(deletedPs.name, null, 0);
14379                    if (deletedPs.sharedUser != null) {
14380                        // Remove permissions associated with package. Since runtime
14381                        // permissions are per user we have to kill the removed package
14382                        // or packages running under the shared user of the removed
14383                        // package if revoking the permissions requested only by the removed
14384                        // package is successful and this causes a change in gids.
14385                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14386                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14387                                    userId);
14388                            if (userIdToKill == UserHandle.USER_ALL
14389                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14390                                // If gids changed for this user, kill all affected packages.
14391                                mHandler.post(new Runnable() {
14392                                    @Override
14393                                    public void run() {
14394                                        // This has to happen with no lock held.
14395                                        killApplication(deletedPs.name, deletedPs.appId,
14396                                                KILL_APP_REASON_GIDS_CHANGED);
14397                                    }
14398                                });
14399                                break;
14400                            }
14401                        }
14402                    }
14403                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14404                }
14405                // make sure to preserve per-user disabled state if this removal was just
14406                // a downgrade of a system app to the factory package
14407                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14408                    if (DEBUG_REMOVE) {
14409                        Slog.d(TAG, "Propagating install state across downgrade");
14410                    }
14411                    for (int userId : allUserHandles) {
14412                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14413                        if (DEBUG_REMOVE) {
14414                            Slog.d(TAG, "    user " + userId + " => " + installed);
14415                        }
14416                        ps.setInstalled(installed, userId);
14417                    }
14418                }
14419            }
14420            // can downgrade to reader
14421            if (writeSettings) {
14422                // Save settings now
14423                mSettings.writeLPr();
14424            }
14425        }
14426        if (outInfo != null) {
14427            // A user ID was deleted here. Go through all users and remove it
14428            // from KeyStore.
14429            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14430        }
14431    }
14432
14433    static boolean locationIsPrivileged(File path) {
14434        try {
14435            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14436                    .getCanonicalPath();
14437            return path.getCanonicalPath().startsWith(privilegedAppDir);
14438        } catch (IOException e) {
14439            Slog.e(TAG, "Unable to access code path " + path);
14440        }
14441        return false;
14442    }
14443
14444    /*
14445     * Tries to delete system package.
14446     */
14447    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14448            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14449            boolean writeSettings) {
14450        if (deletedPkg.parentPackage != null) {
14451            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14452            return false;
14453        }
14454
14455        final boolean applyUserRestrictions
14456                = (allUserHandles != null) && (outInfo.origUsers != null);
14457        final PackageSetting disabledPs;
14458        // Confirm if the system package has been updated
14459        // An updated system app can be deleted. This will also have to restore
14460        // the system pkg from system partition
14461        // reader
14462        synchronized (mPackages) {
14463            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14464        }
14465
14466        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14467                + " disabledPs=" + disabledPs);
14468
14469        if (disabledPs == null) {
14470            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14471            return false;
14472        } else if (DEBUG_REMOVE) {
14473            Slog.d(TAG, "Deleting system pkg from data partition");
14474        }
14475
14476        if (DEBUG_REMOVE) {
14477            if (applyUserRestrictions) {
14478                Slog.d(TAG, "Remembering install states:");
14479                for (int userId : allUserHandles) {
14480                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14481                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14482                }
14483            }
14484        }
14485
14486        // Delete the updated package
14487        outInfo.isRemovedPackageSystemUpdate = true;
14488        if (outInfo.removedChildPackages != null) {
14489            final int childCount = (deletedPkg.childPackages != null)
14490                    ? deletedPkg.childPackages.size() : 0;
14491            for (int i = 0; i < childCount; i++) {
14492                String childPackageName = deletedPkg.childPackages.get(i).packageName;
14493                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14494                        .contains(childPackageName)) {
14495                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14496                            childPackageName);
14497                    if (childInfo != null) {
14498                        childInfo.isRemovedPackageSystemUpdate = true;
14499                    }
14500                }
14501            }
14502        }
14503
14504        if (disabledPs.versionCode < deletedPs.versionCode) {
14505            // Delete data for downgrades
14506            flags &= ~PackageManager.DELETE_KEEP_DATA;
14507        } else {
14508            // Preserve data by setting flag
14509            flags |= PackageManager.DELETE_KEEP_DATA;
14510        }
14511
14512        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14513                outInfo, writeSettings, disabledPs.pkg);
14514        if (!ret) {
14515            return false;
14516        }
14517
14518        // writer
14519        synchronized (mPackages) {
14520            // Reinstate the old system package
14521            enableSystemPackageLPw(disabledPs.pkg);
14522            // Remove any native libraries from the upgraded package.
14523            removeNativeBinariesLI(deletedPkg);
14524        }
14525
14526        // Install the system package
14527        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14528        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14529        if (locationIsPrivileged(disabledPs.codePath)) {
14530            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14531        }
14532
14533        final PackageParser.Package newPkg;
14534        try {
14535            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14536        } catch (PackageManagerException e) {
14537            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14538                    + e.getMessage());
14539            return false;
14540        }
14541
14542        prepareAppDataAfterInstall(newPkg);
14543
14544        // writer
14545        synchronized (mPackages) {
14546            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14547
14548            // Propagate the permissions state as we do not want to drop on the floor
14549            // runtime permissions. The update permissions method below will take
14550            // care of removing obsolete permissions and grant install permissions.
14551            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14552            updatePermissionsLPw(newPkg.packageName, newPkg,
14553                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14554
14555            if (applyUserRestrictions) {
14556                if (DEBUG_REMOVE) {
14557                    Slog.d(TAG, "Propagating install state across reinstall");
14558                }
14559                for (int userId : allUserHandles) {
14560                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14561                    if (DEBUG_REMOVE) {
14562                        Slog.d(TAG, "    user " + userId + " => " + installed);
14563                    }
14564                    ps.setInstalled(installed, userId);
14565
14566                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14567                }
14568                // Regardless of writeSettings we need to ensure that this restriction
14569                // state propagation is persisted
14570                mSettings.writeAllUsersPackageRestrictionsLPr();
14571            }
14572            // can downgrade to reader here
14573            if (writeSettings) {
14574                mSettings.writeLPr();
14575            }
14576        }
14577        return true;
14578    }
14579
14580    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14581            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14582            PackageRemovedInfo outInfo, boolean writeSettings,
14583            PackageParser.Package replacingPackage) {
14584        PackageSetting ps = null;
14585
14586        synchronized (mPackages) {
14587            pkg = mPackages.get(pkg.packageName);
14588            if (pkg == null) {
14589                return false;
14590            }
14591
14592            ps = mSettings.mPackages.get(pkg.packageName);
14593            if (ps == null) {
14594                return false;
14595            }
14596
14597            if (outInfo != null) {
14598                outInfo.uid = ps.appId;
14599            }
14600
14601            if (outInfo != null && outInfo.removedChildPackages != null) {
14602                final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14603                for (int i = 0; i < childCount; i++) {
14604                    String childPackageName = ps.childPackageNames.get(i);
14605                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14606                    if (childPs == null) {
14607                        return false;
14608                    }
14609                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14610                            childPackageName);
14611                    if (childInfo != null) {
14612                        childInfo.uid = childPs.appId;
14613                    }
14614                }
14615            }
14616        }
14617
14618        // Delete package data from internal structures and also remove data if flag is set
14619        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14620
14621        // Delete the child packages data
14622        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14623        for (int i = 0; i < childCount; i++) {
14624            PackageSetting childPs;
14625            synchronized (mPackages) {
14626                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14627            }
14628            if (childPs != null) {
14629                PackageRemovedInfo childOutInfo = (outInfo != null
14630                        && outInfo.removedChildPackages != null)
14631                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14632                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14633                        && (replacingPackage != null
14634                        && !replacingPackage.hasChildPackage(childPs.name))
14635                        ? flags & ~DELETE_KEEP_DATA : flags;
14636                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14637                        deleteFlags, writeSettings);
14638            }
14639        }
14640
14641        // Delete application code and resources only for parent packages
14642        if (ps.pkg.parentPackage == null) {
14643            if (deleteCodeAndResources && (outInfo != null)) {
14644                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14645                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14646                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14647            }
14648        }
14649
14650        return true;
14651    }
14652
14653    @Override
14654    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14655            int userId) {
14656        mContext.enforceCallingOrSelfPermission(
14657                android.Manifest.permission.DELETE_PACKAGES, null);
14658        synchronized (mPackages) {
14659            PackageSetting ps = mSettings.mPackages.get(packageName);
14660            if (ps == null) {
14661                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14662                return false;
14663            }
14664            if (!ps.getInstalled(userId)) {
14665                // Can't block uninstall for an app that is not installed or enabled.
14666                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14667                return false;
14668            }
14669            ps.setBlockUninstall(blockUninstall, userId);
14670            mSettings.writePackageRestrictionsLPr(userId);
14671        }
14672        return true;
14673    }
14674
14675    @Override
14676    public boolean getBlockUninstallForUser(String packageName, int userId) {
14677        synchronized (mPackages) {
14678            PackageSetting ps = mSettings.mPackages.get(packageName);
14679            if (ps == null) {
14680                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14681                return false;
14682            }
14683            return ps.getBlockUninstall(userId);
14684        }
14685    }
14686
14687    @Override
14688    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14689        int callingUid = Binder.getCallingUid();
14690        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14691            throw new SecurityException(
14692                    "setRequiredForSystemUser can only be run by the system or root");
14693        }
14694        synchronized (mPackages) {
14695            PackageSetting ps = mSettings.mPackages.get(packageName);
14696            if (ps == null) {
14697                Log.w(TAG, "Package doesn't exist: " + packageName);
14698                return false;
14699            }
14700            if (systemUserApp) {
14701                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14702            } else {
14703                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14704            }
14705            mSettings.writeLPr();
14706        }
14707        return true;
14708    }
14709
14710    /*
14711     * This method handles package deletion in general
14712     */
14713    private boolean deletePackageLI(String packageName, UserHandle user,
14714            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14715            PackageRemovedInfo outInfo, boolean writeSettings,
14716            PackageParser.Package replacingPackage) {
14717        if (packageName == null) {
14718            Slog.w(TAG, "Attempt to delete null packageName.");
14719            return false;
14720        }
14721
14722        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14723
14724        PackageSetting ps;
14725
14726        synchronized (mPackages) {
14727            ps = mSettings.mPackages.get(packageName);
14728            if (ps == null) {
14729                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14730                return false;
14731            }
14732
14733            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14734                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14735                if (DEBUG_REMOVE) {
14736                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14737                            + ((user == null) ? UserHandle.USER_ALL : user));
14738                }
14739                final int removedUserId = (user != null) ? user.getIdentifier()
14740                        : UserHandle.USER_ALL;
14741                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14742                    return false;
14743                }
14744                markPackageUninstalledForUserLPw(ps, user);
14745                scheduleWritePackageRestrictionsLocked(user);
14746                return true;
14747            }
14748        }
14749
14750        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14751                && user.getIdentifier() != UserHandle.USER_ALL)) {
14752            // The caller is asking that the package only be deleted for a single
14753            // user.  To do this, we just mark its uninstalled state and delete
14754            // its data. If this is a system app, we only allow this to happen if
14755            // they have set the special DELETE_SYSTEM_APP which requests different
14756            // semantics than normal for uninstalling system apps.
14757            markPackageUninstalledForUserLPw(ps, user);
14758
14759            if (!isSystemApp(ps)) {
14760                // Do not uninstall the APK if an app should be cached
14761                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14762                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14763                    // Other user still have this package installed, so all
14764                    // we need to do is clear this user's data and save that
14765                    // it is uninstalled.
14766                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14767                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14768                        return false;
14769                    }
14770                    scheduleWritePackageRestrictionsLocked(user);
14771                    return true;
14772                } else {
14773                    // We need to set it back to 'installed' so the uninstall
14774                    // broadcasts will be sent correctly.
14775                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14776                    ps.setInstalled(true, user.getIdentifier());
14777                }
14778            } else {
14779                // This is a system app, so we assume that the
14780                // other users still have this package installed, so all
14781                // we need to do is clear this user's data and save that
14782                // it is uninstalled.
14783                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14784                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14785                    return false;
14786                }
14787                scheduleWritePackageRestrictionsLocked(user);
14788                return true;
14789            }
14790        }
14791
14792        // If we are deleting a composite package for all users, keep track
14793        // of result for each child.
14794        if (ps.childPackageNames != null && outInfo != null) {
14795            synchronized (mPackages) {
14796                final int childCount = ps.childPackageNames.size();
14797                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14798                for (int i = 0; i < childCount; i++) {
14799                    String childPackageName = ps.childPackageNames.get(i);
14800                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14801                    childInfo.removedPackage = childPackageName;
14802                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14803                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14804                    if (childPs != null) {
14805                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14806                    }
14807                }
14808            }
14809        }
14810
14811        boolean ret = false;
14812        if (isSystemApp(ps)) {
14813            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14814            // When an updated system application is deleted we delete the existing resources
14815            // as well and fall back to existing code in system partition
14816            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14817        } else {
14818            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14819            // Kill application pre-emptively especially for apps on sd.
14820            killApplication(packageName, ps.appId, "uninstall pkg");
14821            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14822                    outInfo, writeSettings, replacingPackage);
14823        }
14824
14825        // Take a note whether we deleted the package for all users
14826        if (outInfo != null) {
14827            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14828            if (outInfo.removedChildPackages != null) {
14829                synchronized (mPackages) {
14830                    final int childCount = outInfo.removedChildPackages.size();
14831                    for (int i = 0; i < childCount; i++) {
14832                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14833                        if (childInfo != null) {
14834                            childInfo.removedForAllUsers = mPackages.get(
14835                                    childInfo.removedPackage) == null;
14836                        }
14837                    }
14838                }
14839            }
14840            // If we uninstalled an update to a system app there may be some
14841            // child packages that appeared as they are declared in the system
14842            // app but were not declared in the update.
14843            if (isSystemApp(ps)) {
14844                synchronized (mPackages) {
14845                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14846                    final int childCount = (updatedPs.childPackageNames != null)
14847                            ? updatedPs.childPackageNames.size() : 0;
14848                    for (int i = 0; i < childCount; i++) {
14849                        String childPackageName = updatedPs.childPackageNames.get(i);
14850                        if (outInfo.removedChildPackages == null
14851                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14852                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14853                            if (childPs == null) {
14854                                continue;
14855                            }
14856                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14857                            installRes.name = childPackageName;
14858                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14859                            installRes.pkg = mPackages.get(childPackageName);
14860                            installRes.uid = childPs.pkg.applicationInfo.uid;
14861                            if (outInfo.appearedChildPackages == null) {
14862                                outInfo.appearedChildPackages = new ArrayMap<>();
14863                            }
14864                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14865                        }
14866                    }
14867                }
14868            }
14869        }
14870
14871        return ret;
14872    }
14873
14874    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14875        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14876                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14877        for (int nextUserId : userIds) {
14878            if (DEBUG_REMOVE) {
14879                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14880            }
14881            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14882                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14883                    false /*hidden*/, false /*suspended*/, null, null, null,
14884                    false /*blockUninstall*/,
14885                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14886        }
14887    }
14888
14889    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14890            PackageRemovedInfo outInfo) {
14891        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14892                : new int[] {userId};
14893        for (int nextUserId : userIds) {
14894            if (DEBUG_REMOVE) {
14895                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14896                        + nextUserId);
14897            }
14898            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14899            try {
14900                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14901            } catch (InstallerException e) {
14902                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14903                return false;
14904            }
14905            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14906            schedulePackageCleaning(ps.name, nextUserId, false);
14907            synchronized (mPackages) {
14908                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14909                    scheduleWritePackageRestrictionsLocked(nextUserId);
14910                }
14911                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14912            }
14913        }
14914
14915        if (outInfo != null) {
14916            outInfo.removedPackage = ps.name;
14917            outInfo.removedAppId = ps.appId;
14918            outInfo.removedUsers = userIds;
14919        }
14920
14921        return true;
14922    }
14923
14924    private final class ClearStorageConnection implements ServiceConnection {
14925        IMediaContainerService mContainerService;
14926
14927        @Override
14928        public void onServiceConnected(ComponentName name, IBinder service) {
14929            synchronized (this) {
14930                mContainerService = IMediaContainerService.Stub.asInterface(service);
14931                notifyAll();
14932            }
14933        }
14934
14935        @Override
14936        public void onServiceDisconnected(ComponentName name) {
14937        }
14938    }
14939
14940    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14941        final boolean mounted;
14942        if (Environment.isExternalStorageEmulated()) {
14943            mounted = true;
14944        } else {
14945            final String status = Environment.getExternalStorageState();
14946
14947            mounted = status.equals(Environment.MEDIA_MOUNTED)
14948                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14949        }
14950
14951        if (!mounted) {
14952            return;
14953        }
14954
14955        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14956        int[] users;
14957        if (userId == UserHandle.USER_ALL) {
14958            users = sUserManager.getUserIds();
14959        } else {
14960            users = new int[] { userId };
14961        }
14962        final ClearStorageConnection conn = new ClearStorageConnection();
14963        if (mContext.bindServiceAsUser(
14964                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14965            try {
14966                for (int curUser : users) {
14967                    long timeout = SystemClock.uptimeMillis() + 5000;
14968                    synchronized (conn) {
14969                        long now = SystemClock.uptimeMillis();
14970                        while (conn.mContainerService == null && now < timeout) {
14971                            try {
14972                                conn.wait(timeout - now);
14973                            } catch (InterruptedException e) {
14974                            }
14975                        }
14976                    }
14977                    if (conn.mContainerService == null) {
14978                        return;
14979                    }
14980
14981                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14982                    clearDirectory(conn.mContainerService,
14983                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14984                    if (allData) {
14985                        clearDirectory(conn.mContainerService,
14986                                userEnv.buildExternalStorageAppDataDirs(packageName));
14987                        clearDirectory(conn.mContainerService,
14988                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14989                    }
14990                }
14991            } finally {
14992                mContext.unbindService(conn);
14993            }
14994        }
14995    }
14996
14997    @Override
14998    public void clearApplicationUserData(final String packageName,
14999            final IPackageDataObserver observer, final int userId) {
15000        mContext.enforceCallingOrSelfPermission(
15001                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15002        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
15003        // Queue up an async operation since the package deletion may take a little while.
15004        mHandler.post(new Runnable() {
15005            public void run() {
15006                mHandler.removeCallbacks(this);
15007                final boolean succeeded;
15008                synchronized (mInstallLock) {
15009                    succeeded = clearApplicationUserDataLI(packageName, userId);
15010                }
15011                clearExternalStorageDataSync(packageName, userId, true);
15012                if (succeeded) {
15013                    // invoke DeviceStorageMonitor's update method to clear any notifications
15014                    DeviceStorageMonitorInternal
15015                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15016                    if (dsm != null) {
15017                        dsm.checkMemory();
15018                    }
15019                }
15020                if(observer != null) {
15021                    try {
15022                        observer.onRemoveCompleted(packageName, succeeded);
15023                    } catch (RemoteException e) {
15024                        Log.i(TAG, "Observer no longer exists.");
15025                    }
15026                } //end if observer
15027            } //end run
15028        });
15029    }
15030
15031    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15032        if (packageName == null) {
15033            Slog.w(TAG, "Attempt to delete null packageName.");
15034            return false;
15035        }
15036
15037        // Try finding details about the requested package
15038        PackageParser.Package pkg;
15039        synchronized (mPackages) {
15040            pkg = mPackages.get(packageName);
15041            if (pkg == null) {
15042                final PackageSetting ps = mSettings.mPackages.get(packageName);
15043                if (ps != null) {
15044                    pkg = ps.pkg;
15045                }
15046            }
15047
15048            if (pkg == null) {
15049                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15050                return false;
15051            }
15052
15053            PackageSetting ps = (PackageSetting) pkg.mExtras;
15054            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15055        }
15056
15057        // Always delete data directories for package, even if we found no other
15058        // record of app. This helps users recover from UID mismatches without
15059        // resorting to a full data wipe.
15060        // TODO: triage flags as part of 26466827
15061        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15062        try {
15063            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15064        } catch (InstallerException e) {
15065            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15066            return false;
15067        }
15068
15069        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15070        removeKeystoreDataIfNeeded(userId, appId);
15071
15072        // Create a native library symlink only if we have native libraries
15073        // and if the native libraries are 32 bit libraries. We do not provide
15074        // this symlink for 64 bit libraries.
15075        if (pkg.applicationInfo.primaryCpuAbi != null &&
15076                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15077            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15078            try {
15079                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15080                        nativeLibPath, userId);
15081            } catch (InstallerException e) {
15082                Slog.w(TAG, "Failed linking native library dir", e);
15083                return false;
15084            }
15085        }
15086
15087        return true;
15088    }
15089
15090    /**
15091     * Reverts user permission state changes (permissions and flags) in
15092     * all packages for a given user.
15093     *
15094     * @param userId The device user for which to do a reset.
15095     */
15096    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15097        final int packageCount = mPackages.size();
15098        for (int i = 0; i < packageCount; i++) {
15099            PackageParser.Package pkg = mPackages.valueAt(i);
15100            PackageSetting ps = (PackageSetting) pkg.mExtras;
15101            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15102        }
15103    }
15104
15105    /**
15106     * Reverts user permission state changes (permissions and flags).
15107     *
15108     * @param ps The package for which to reset.
15109     * @param userId The device user for which to do a reset.
15110     */
15111    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15112            final PackageSetting ps, final int userId) {
15113        if (ps.pkg == null) {
15114            return;
15115        }
15116
15117        // These are flags that can change base on user actions.
15118        final int userSettableMask = FLAG_PERMISSION_USER_SET
15119                | FLAG_PERMISSION_USER_FIXED
15120                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15121                | FLAG_PERMISSION_REVIEW_REQUIRED;
15122
15123        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15124                | FLAG_PERMISSION_POLICY_FIXED;
15125
15126        boolean writeInstallPermissions = false;
15127        boolean writeRuntimePermissions = false;
15128
15129        final int permissionCount = ps.pkg.requestedPermissions.size();
15130        for (int i = 0; i < permissionCount; i++) {
15131            String permission = ps.pkg.requestedPermissions.get(i);
15132
15133            BasePermission bp = mSettings.mPermissions.get(permission);
15134            if (bp == null) {
15135                continue;
15136            }
15137
15138            // If shared user we just reset the state to which only this app contributed.
15139            if (ps.sharedUser != null) {
15140                boolean used = false;
15141                final int packageCount = ps.sharedUser.packages.size();
15142                for (int j = 0; j < packageCount; j++) {
15143                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15144                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15145                            && pkg.pkg.requestedPermissions.contains(permission)) {
15146                        used = true;
15147                        break;
15148                    }
15149                }
15150                if (used) {
15151                    continue;
15152                }
15153            }
15154
15155            PermissionsState permissionsState = ps.getPermissionsState();
15156
15157            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15158
15159            // Always clear the user settable flags.
15160            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15161                    bp.name) != null;
15162            // If permission review is enabled and this is a legacy app, mark the
15163            // permission as requiring a review as this is the initial state.
15164            int flags = 0;
15165            if (Build.PERMISSIONS_REVIEW_REQUIRED
15166                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15167                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15168            }
15169            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15170                if (hasInstallState) {
15171                    writeInstallPermissions = true;
15172                } else {
15173                    writeRuntimePermissions = true;
15174                }
15175            }
15176
15177            // Below is only runtime permission handling.
15178            if (!bp.isRuntime()) {
15179                continue;
15180            }
15181
15182            // Never clobber system or policy.
15183            if ((oldFlags & policyOrSystemFlags) != 0) {
15184                continue;
15185            }
15186
15187            // If this permission was granted by default, make sure it is.
15188            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15189                if (permissionsState.grantRuntimePermission(bp, userId)
15190                        != PERMISSION_OPERATION_FAILURE) {
15191                    writeRuntimePermissions = true;
15192                }
15193            // If permission review is enabled the permissions for a legacy apps
15194            // are represented as constantly granted runtime ones, so don't revoke.
15195            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15196                // Otherwise, reset the permission.
15197                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15198                switch (revokeResult) {
15199                    case PERMISSION_OPERATION_SUCCESS: {
15200                        writeRuntimePermissions = true;
15201                    } break;
15202
15203                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15204                        writeRuntimePermissions = true;
15205                        final int appId = ps.appId;
15206                        mHandler.post(new Runnable() {
15207                            @Override
15208                            public void run() {
15209                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15210                            }
15211                        });
15212                    } break;
15213                }
15214            }
15215        }
15216
15217        // Synchronously write as we are taking permissions away.
15218        if (writeRuntimePermissions) {
15219            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15220        }
15221
15222        // Synchronously write as we are taking permissions away.
15223        if (writeInstallPermissions) {
15224            mSettings.writeLPr();
15225        }
15226    }
15227
15228    /**
15229     * Remove entries from the keystore daemon. Will only remove it if the
15230     * {@code appId} is valid.
15231     */
15232    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15233        if (appId < 0) {
15234            return;
15235        }
15236
15237        final KeyStore keyStore = KeyStore.getInstance();
15238        if (keyStore != null) {
15239            if (userId == UserHandle.USER_ALL) {
15240                for (final int individual : sUserManager.getUserIds()) {
15241                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15242                }
15243            } else {
15244                keyStore.clearUid(UserHandle.getUid(userId, appId));
15245            }
15246        } else {
15247            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15248        }
15249    }
15250
15251    @Override
15252    public void deleteApplicationCacheFiles(final String packageName,
15253            final IPackageDataObserver observer) {
15254        mContext.enforceCallingOrSelfPermission(
15255                android.Manifest.permission.DELETE_CACHE_FILES, null);
15256        // Queue up an async operation since the package deletion may take a little while.
15257        final int userId = UserHandle.getCallingUserId();
15258        mHandler.post(new Runnable() {
15259            public void run() {
15260                mHandler.removeCallbacks(this);
15261                final boolean succeded;
15262                synchronized (mInstallLock) {
15263                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15264                }
15265                clearExternalStorageDataSync(packageName, userId, false);
15266                if (observer != null) {
15267                    try {
15268                        observer.onRemoveCompleted(packageName, succeded);
15269                    } catch (RemoteException e) {
15270                        Log.i(TAG, "Observer no longer exists.");
15271                    }
15272                } //end if observer
15273            } //end run
15274        });
15275    }
15276
15277    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15278        if (packageName == null) {
15279            Slog.w(TAG, "Attempt to delete null packageName.");
15280            return false;
15281        }
15282        PackageParser.Package p;
15283        synchronized (mPackages) {
15284            p = mPackages.get(packageName);
15285        }
15286        if (p == null) {
15287            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15288            return false;
15289        }
15290        final ApplicationInfo applicationInfo = p.applicationInfo;
15291        if (applicationInfo == null) {
15292            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15293            return false;
15294        }
15295        // TODO: triage flags as part of 26466827
15296        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15297        try {
15298            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15299                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15300        } catch (InstallerException e) {
15301            Slog.w(TAG, "Couldn't remove cache files for package "
15302                    + packageName + " u" + userId, e);
15303            return false;
15304        }
15305        return true;
15306    }
15307
15308    @Override
15309    public void getPackageSizeInfo(final String packageName, int userHandle,
15310            final IPackageStatsObserver observer) {
15311        mContext.enforceCallingOrSelfPermission(
15312                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15313        if (packageName == null) {
15314            throw new IllegalArgumentException("Attempt to get size of null packageName");
15315        }
15316
15317        PackageStats stats = new PackageStats(packageName, userHandle);
15318
15319        /*
15320         * Queue up an async operation since the package measurement may take a
15321         * little while.
15322         */
15323        Message msg = mHandler.obtainMessage(INIT_COPY);
15324        msg.obj = new MeasureParams(stats, observer);
15325        mHandler.sendMessage(msg);
15326    }
15327
15328    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15329            PackageStats pStats) {
15330        if (packageName == null) {
15331            Slog.w(TAG, "Attempt to get size of null packageName.");
15332            return false;
15333        }
15334        PackageParser.Package p;
15335        boolean dataOnly = false;
15336        String libDirRoot = null;
15337        String asecPath = null;
15338        PackageSetting ps = null;
15339        synchronized (mPackages) {
15340            p = mPackages.get(packageName);
15341            ps = mSettings.mPackages.get(packageName);
15342            if(p == null) {
15343                dataOnly = true;
15344                if((ps == null) || (ps.pkg == null)) {
15345                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15346                    return false;
15347                }
15348                p = ps.pkg;
15349            }
15350            if (ps != null) {
15351                libDirRoot = ps.legacyNativeLibraryPathString;
15352            }
15353            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15354                final long token = Binder.clearCallingIdentity();
15355                try {
15356                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15357                    if (secureContainerId != null) {
15358                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15359                    }
15360                } finally {
15361                    Binder.restoreCallingIdentity(token);
15362                }
15363            }
15364        }
15365        String publicSrcDir = null;
15366        if(!dataOnly) {
15367            final ApplicationInfo applicationInfo = p.applicationInfo;
15368            if (applicationInfo == null) {
15369                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15370                return false;
15371            }
15372            if (p.isForwardLocked()) {
15373                publicSrcDir = applicationInfo.getBaseResourcePath();
15374            }
15375        }
15376        // TODO: extend to measure size of split APKs
15377        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15378        // not just the first level.
15379        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15380        // just the primary.
15381        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15382
15383        String apkPath;
15384        File packageDir = new File(p.codePath);
15385
15386        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15387            apkPath = packageDir.getAbsolutePath();
15388            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15389            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15390                libDirRoot = null;
15391            }
15392        } else {
15393            apkPath = p.baseCodePath;
15394        }
15395
15396        // TODO: triage flags as part of 26466827
15397        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15398        try {
15399            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15400                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15401        } catch (InstallerException e) {
15402            return false;
15403        }
15404
15405        // Fix-up for forward-locked applications in ASEC containers.
15406        if (!isExternal(p)) {
15407            pStats.codeSize += pStats.externalCodeSize;
15408            pStats.externalCodeSize = 0L;
15409        }
15410
15411        return true;
15412    }
15413
15414
15415    @Override
15416    public void addPackageToPreferred(String packageName) {
15417        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15418    }
15419
15420    @Override
15421    public void removePackageFromPreferred(String packageName) {
15422        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15423    }
15424
15425    @Override
15426    public List<PackageInfo> getPreferredPackages(int flags) {
15427        return new ArrayList<PackageInfo>();
15428    }
15429
15430    private int getUidTargetSdkVersionLockedLPr(int uid) {
15431        Object obj = mSettings.getUserIdLPr(uid);
15432        if (obj instanceof SharedUserSetting) {
15433            final SharedUserSetting sus = (SharedUserSetting) obj;
15434            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15435            final Iterator<PackageSetting> it = sus.packages.iterator();
15436            while (it.hasNext()) {
15437                final PackageSetting ps = it.next();
15438                if (ps.pkg != null) {
15439                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15440                    if (v < vers) vers = v;
15441                }
15442            }
15443            return vers;
15444        } else if (obj instanceof PackageSetting) {
15445            final PackageSetting ps = (PackageSetting) obj;
15446            if (ps.pkg != null) {
15447                return ps.pkg.applicationInfo.targetSdkVersion;
15448            }
15449        }
15450        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15451    }
15452
15453    @Override
15454    public void addPreferredActivity(IntentFilter filter, int match,
15455            ComponentName[] set, ComponentName activity, int userId) {
15456        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15457                "Adding preferred");
15458    }
15459
15460    private void addPreferredActivityInternal(IntentFilter filter, int match,
15461            ComponentName[] set, ComponentName activity, boolean always, int userId,
15462            String opname) {
15463        // writer
15464        int callingUid = Binder.getCallingUid();
15465        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15466        if (filter.countActions() == 0) {
15467            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15468            return;
15469        }
15470        synchronized (mPackages) {
15471            if (mContext.checkCallingOrSelfPermission(
15472                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15473                    != PackageManager.PERMISSION_GRANTED) {
15474                if (getUidTargetSdkVersionLockedLPr(callingUid)
15475                        < Build.VERSION_CODES.FROYO) {
15476                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15477                            + callingUid);
15478                    return;
15479                }
15480                mContext.enforceCallingOrSelfPermission(
15481                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15482            }
15483
15484            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15485            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15486                    + userId + ":");
15487            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15488            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15489            scheduleWritePackageRestrictionsLocked(userId);
15490        }
15491    }
15492
15493    @Override
15494    public void replacePreferredActivity(IntentFilter filter, int match,
15495            ComponentName[] set, ComponentName activity, int userId) {
15496        if (filter.countActions() != 1) {
15497            throw new IllegalArgumentException(
15498                    "replacePreferredActivity expects filter to have only 1 action.");
15499        }
15500        if (filter.countDataAuthorities() != 0
15501                || filter.countDataPaths() != 0
15502                || filter.countDataSchemes() > 1
15503                || filter.countDataTypes() != 0) {
15504            throw new IllegalArgumentException(
15505                    "replacePreferredActivity expects filter to have no data authorities, " +
15506                    "paths, or types; and at most one scheme.");
15507        }
15508
15509        final int callingUid = Binder.getCallingUid();
15510        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15511        synchronized (mPackages) {
15512            if (mContext.checkCallingOrSelfPermission(
15513                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15514                    != PackageManager.PERMISSION_GRANTED) {
15515                if (getUidTargetSdkVersionLockedLPr(callingUid)
15516                        < Build.VERSION_CODES.FROYO) {
15517                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15518                            + Binder.getCallingUid());
15519                    return;
15520                }
15521                mContext.enforceCallingOrSelfPermission(
15522                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15523            }
15524
15525            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15526            if (pir != null) {
15527                // Get all of the existing entries that exactly match this filter.
15528                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15529                if (existing != null && existing.size() == 1) {
15530                    PreferredActivity cur = existing.get(0);
15531                    if (DEBUG_PREFERRED) {
15532                        Slog.i(TAG, "Checking replace of preferred:");
15533                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15534                        if (!cur.mPref.mAlways) {
15535                            Slog.i(TAG, "  -- CUR; not mAlways!");
15536                        } else {
15537                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15538                            Slog.i(TAG, "  -- CUR: mSet="
15539                                    + Arrays.toString(cur.mPref.mSetComponents));
15540                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15541                            Slog.i(TAG, "  -- NEW: mMatch="
15542                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15543                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15544                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15545                        }
15546                    }
15547                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15548                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15549                            && cur.mPref.sameSet(set)) {
15550                        // Setting the preferred activity to what it happens to be already
15551                        if (DEBUG_PREFERRED) {
15552                            Slog.i(TAG, "Replacing with same preferred activity "
15553                                    + cur.mPref.mShortComponent + " for user "
15554                                    + userId + ":");
15555                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15556                        }
15557                        return;
15558                    }
15559                }
15560
15561                if (existing != null) {
15562                    if (DEBUG_PREFERRED) {
15563                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15564                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15565                    }
15566                    for (int i = 0; i < existing.size(); i++) {
15567                        PreferredActivity pa = existing.get(i);
15568                        if (DEBUG_PREFERRED) {
15569                            Slog.i(TAG, "Removing existing preferred activity "
15570                                    + pa.mPref.mComponent + ":");
15571                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15572                        }
15573                        pir.removeFilter(pa);
15574                    }
15575                }
15576            }
15577            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15578                    "Replacing preferred");
15579        }
15580    }
15581
15582    @Override
15583    public void clearPackagePreferredActivities(String packageName) {
15584        final int uid = Binder.getCallingUid();
15585        // writer
15586        synchronized (mPackages) {
15587            PackageParser.Package pkg = mPackages.get(packageName);
15588            if (pkg == null || pkg.applicationInfo.uid != uid) {
15589                if (mContext.checkCallingOrSelfPermission(
15590                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15591                        != PackageManager.PERMISSION_GRANTED) {
15592                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15593                            < Build.VERSION_CODES.FROYO) {
15594                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15595                                + Binder.getCallingUid());
15596                        return;
15597                    }
15598                    mContext.enforceCallingOrSelfPermission(
15599                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15600                }
15601            }
15602
15603            int user = UserHandle.getCallingUserId();
15604            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15605                scheduleWritePackageRestrictionsLocked(user);
15606            }
15607        }
15608    }
15609
15610    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15611    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15612        ArrayList<PreferredActivity> removed = null;
15613        boolean changed = false;
15614        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15615            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15616            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15617            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15618                continue;
15619            }
15620            Iterator<PreferredActivity> it = pir.filterIterator();
15621            while (it.hasNext()) {
15622                PreferredActivity pa = it.next();
15623                // Mark entry for removal only if it matches the package name
15624                // and the entry is of type "always".
15625                if (packageName == null ||
15626                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15627                                && pa.mPref.mAlways)) {
15628                    if (removed == null) {
15629                        removed = new ArrayList<PreferredActivity>();
15630                    }
15631                    removed.add(pa);
15632                }
15633            }
15634            if (removed != null) {
15635                for (int j=0; j<removed.size(); j++) {
15636                    PreferredActivity pa = removed.get(j);
15637                    pir.removeFilter(pa);
15638                }
15639                changed = true;
15640            }
15641        }
15642        return changed;
15643    }
15644
15645    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15646    private void clearIntentFilterVerificationsLPw(int userId) {
15647        final int packageCount = mPackages.size();
15648        for (int i = 0; i < packageCount; i++) {
15649            PackageParser.Package pkg = mPackages.valueAt(i);
15650            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15651        }
15652    }
15653
15654    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15655    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15656        if (userId == UserHandle.USER_ALL) {
15657            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15658                    sUserManager.getUserIds())) {
15659                for (int oneUserId : sUserManager.getUserIds()) {
15660                    scheduleWritePackageRestrictionsLocked(oneUserId);
15661                }
15662            }
15663        } else {
15664            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15665                scheduleWritePackageRestrictionsLocked(userId);
15666            }
15667        }
15668    }
15669
15670    void clearDefaultBrowserIfNeeded(String packageName) {
15671        for (int oneUserId : sUserManager.getUserIds()) {
15672            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15673            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15674            if (packageName.equals(defaultBrowserPackageName)) {
15675                setDefaultBrowserPackageName(null, oneUserId);
15676            }
15677        }
15678    }
15679
15680    @Override
15681    public void resetApplicationPreferences(int userId) {
15682        mContext.enforceCallingOrSelfPermission(
15683                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15684        // writer
15685        synchronized (mPackages) {
15686            final long identity = Binder.clearCallingIdentity();
15687            try {
15688                clearPackagePreferredActivitiesLPw(null, userId);
15689                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15690                // TODO: We have to reset the default SMS and Phone. This requires
15691                // significant refactoring to keep all default apps in the package
15692                // manager (cleaner but more work) or have the services provide
15693                // callbacks to the package manager to request a default app reset.
15694                applyFactoryDefaultBrowserLPw(userId);
15695                clearIntentFilterVerificationsLPw(userId);
15696                primeDomainVerificationsLPw(userId);
15697                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15698                scheduleWritePackageRestrictionsLocked(userId);
15699            } finally {
15700                Binder.restoreCallingIdentity(identity);
15701            }
15702        }
15703    }
15704
15705    @Override
15706    public int getPreferredActivities(List<IntentFilter> outFilters,
15707            List<ComponentName> outActivities, String packageName) {
15708
15709        int num = 0;
15710        final int userId = UserHandle.getCallingUserId();
15711        // reader
15712        synchronized (mPackages) {
15713            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15714            if (pir != null) {
15715                final Iterator<PreferredActivity> it = pir.filterIterator();
15716                while (it.hasNext()) {
15717                    final PreferredActivity pa = it.next();
15718                    if (packageName == null
15719                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15720                                    && pa.mPref.mAlways)) {
15721                        if (outFilters != null) {
15722                            outFilters.add(new IntentFilter(pa));
15723                        }
15724                        if (outActivities != null) {
15725                            outActivities.add(pa.mPref.mComponent);
15726                        }
15727                    }
15728                }
15729            }
15730        }
15731
15732        return num;
15733    }
15734
15735    @Override
15736    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15737            int userId) {
15738        int callingUid = Binder.getCallingUid();
15739        if (callingUid != Process.SYSTEM_UID) {
15740            throw new SecurityException(
15741                    "addPersistentPreferredActivity can only be run by the system");
15742        }
15743        if (filter.countActions() == 0) {
15744            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15745            return;
15746        }
15747        synchronized (mPackages) {
15748            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15749                    ":");
15750            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15751            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15752                    new PersistentPreferredActivity(filter, activity));
15753            scheduleWritePackageRestrictionsLocked(userId);
15754        }
15755    }
15756
15757    @Override
15758    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15759        int callingUid = Binder.getCallingUid();
15760        if (callingUid != Process.SYSTEM_UID) {
15761            throw new SecurityException(
15762                    "clearPackagePersistentPreferredActivities can only be run by the system");
15763        }
15764        ArrayList<PersistentPreferredActivity> removed = null;
15765        boolean changed = false;
15766        synchronized (mPackages) {
15767            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15768                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15769                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15770                        .valueAt(i);
15771                if (userId != thisUserId) {
15772                    continue;
15773                }
15774                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15775                while (it.hasNext()) {
15776                    PersistentPreferredActivity ppa = it.next();
15777                    // Mark entry for removal only if it matches the package name.
15778                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15779                        if (removed == null) {
15780                            removed = new ArrayList<PersistentPreferredActivity>();
15781                        }
15782                        removed.add(ppa);
15783                    }
15784                }
15785                if (removed != null) {
15786                    for (int j=0; j<removed.size(); j++) {
15787                        PersistentPreferredActivity ppa = removed.get(j);
15788                        ppir.removeFilter(ppa);
15789                    }
15790                    changed = true;
15791                }
15792            }
15793
15794            if (changed) {
15795                scheduleWritePackageRestrictionsLocked(userId);
15796            }
15797        }
15798    }
15799
15800    /**
15801     * Common machinery for picking apart a restored XML blob and passing
15802     * it to a caller-supplied functor to be applied to the running system.
15803     */
15804    private void restoreFromXml(XmlPullParser parser, int userId,
15805            String expectedStartTag, BlobXmlRestorer functor)
15806            throws IOException, XmlPullParserException {
15807        int type;
15808        while ((type = parser.next()) != XmlPullParser.START_TAG
15809                && type != XmlPullParser.END_DOCUMENT) {
15810        }
15811        if (type != XmlPullParser.START_TAG) {
15812            // oops didn't find a start tag?!
15813            if (DEBUG_BACKUP) {
15814                Slog.e(TAG, "Didn't find start tag during restore");
15815            }
15816            return;
15817        }
15818Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15819        // this is supposed to be TAG_PREFERRED_BACKUP
15820        if (!expectedStartTag.equals(parser.getName())) {
15821            if (DEBUG_BACKUP) {
15822                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15823            }
15824            return;
15825        }
15826
15827        // skip interfering stuff, then we're aligned with the backing implementation
15828        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15829Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15830        functor.apply(parser, userId);
15831    }
15832
15833    private interface BlobXmlRestorer {
15834        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15835    }
15836
15837    /**
15838     * Non-Binder method, support for the backup/restore mechanism: write the
15839     * full set of preferred activities in its canonical XML format.  Returns the
15840     * XML output as a byte array, or null if there is none.
15841     */
15842    @Override
15843    public byte[] getPreferredActivityBackup(int userId) {
15844        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15845            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15846        }
15847
15848        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15849        try {
15850            final XmlSerializer serializer = new FastXmlSerializer();
15851            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15852            serializer.startDocument(null, true);
15853            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15854
15855            synchronized (mPackages) {
15856                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15857            }
15858
15859            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15860            serializer.endDocument();
15861            serializer.flush();
15862        } catch (Exception e) {
15863            if (DEBUG_BACKUP) {
15864                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15865            }
15866            return null;
15867        }
15868
15869        return dataStream.toByteArray();
15870    }
15871
15872    @Override
15873    public void restorePreferredActivities(byte[] backup, int userId) {
15874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15875            throw new SecurityException("Only the system may call restorePreferredActivities()");
15876        }
15877
15878        try {
15879            final XmlPullParser parser = Xml.newPullParser();
15880            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15881            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15882                    new BlobXmlRestorer() {
15883                        @Override
15884                        public void apply(XmlPullParser parser, int userId)
15885                                throws XmlPullParserException, IOException {
15886                            synchronized (mPackages) {
15887                                mSettings.readPreferredActivitiesLPw(parser, userId);
15888                            }
15889                        }
15890                    } );
15891        } catch (Exception e) {
15892            if (DEBUG_BACKUP) {
15893                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15894            }
15895        }
15896    }
15897
15898    /**
15899     * Non-Binder method, support for the backup/restore mechanism: write the
15900     * default browser (etc) settings in its canonical XML format.  Returns the default
15901     * browser XML representation as a byte array, or null if there is none.
15902     */
15903    @Override
15904    public byte[] getDefaultAppsBackup(int userId) {
15905        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15906            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15907        }
15908
15909        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15910        try {
15911            final XmlSerializer serializer = new FastXmlSerializer();
15912            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15913            serializer.startDocument(null, true);
15914            serializer.startTag(null, TAG_DEFAULT_APPS);
15915
15916            synchronized (mPackages) {
15917                mSettings.writeDefaultAppsLPr(serializer, userId);
15918            }
15919
15920            serializer.endTag(null, TAG_DEFAULT_APPS);
15921            serializer.endDocument();
15922            serializer.flush();
15923        } catch (Exception e) {
15924            if (DEBUG_BACKUP) {
15925                Slog.e(TAG, "Unable to write default apps for backup", e);
15926            }
15927            return null;
15928        }
15929
15930        return dataStream.toByteArray();
15931    }
15932
15933    @Override
15934    public void restoreDefaultApps(byte[] backup, int userId) {
15935        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15936            throw new SecurityException("Only the system may call restoreDefaultApps()");
15937        }
15938
15939        try {
15940            final XmlPullParser parser = Xml.newPullParser();
15941            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15942            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15943                    new BlobXmlRestorer() {
15944                        @Override
15945                        public void apply(XmlPullParser parser, int userId)
15946                                throws XmlPullParserException, IOException {
15947                            synchronized (mPackages) {
15948                                mSettings.readDefaultAppsLPw(parser, userId);
15949                            }
15950                        }
15951                    } );
15952        } catch (Exception e) {
15953            if (DEBUG_BACKUP) {
15954                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15955            }
15956        }
15957    }
15958
15959    @Override
15960    public byte[] getIntentFilterVerificationBackup(int userId) {
15961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15962            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15963        }
15964
15965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15966        try {
15967            final XmlSerializer serializer = new FastXmlSerializer();
15968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15969            serializer.startDocument(null, true);
15970            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15971
15972            synchronized (mPackages) {
15973                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15974            }
15975
15976            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15977            serializer.endDocument();
15978            serializer.flush();
15979        } catch (Exception e) {
15980            if (DEBUG_BACKUP) {
15981                Slog.e(TAG, "Unable to write default apps for backup", e);
15982            }
15983            return null;
15984        }
15985
15986        return dataStream.toByteArray();
15987    }
15988
15989    @Override
15990    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15992            throw new SecurityException("Only the system may call restorePreferredActivities()");
15993        }
15994
15995        try {
15996            final XmlPullParser parser = Xml.newPullParser();
15997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15998            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15999                    new BlobXmlRestorer() {
16000                        @Override
16001                        public void apply(XmlPullParser parser, int userId)
16002                                throws XmlPullParserException, IOException {
16003                            synchronized (mPackages) {
16004                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16005                                mSettings.writeLPr();
16006                            }
16007                        }
16008                    } );
16009        } catch (Exception e) {
16010            if (DEBUG_BACKUP) {
16011                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16012            }
16013        }
16014    }
16015
16016    @Override
16017    public byte[] getPermissionGrantBackup(int userId) {
16018        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16019            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16020        }
16021
16022        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16023        try {
16024            final XmlSerializer serializer = new FastXmlSerializer();
16025            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16026            serializer.startDocument(null, true);
16027            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16028
16029            synchronized (mPackages) {
16030                serializeRuntimePermissionGrantsLPr(serializer, userId);
16031            }
16032
16033            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16034            serializer.endDocument();
16035            serializer.flush();
16036        } catch (Exception e) {
16037            if (DEBUG_BACKUP) {
16038                Slog.e(TAG, "Unable to write default apps for backup", e);
16039            }
16040            return null;
16041        }
16042
16043        return dataStream.toByteArray();
16044    }
16045
16046    @Override
16047    public void restorePermissionGrants(byte[] backup, int userId) {
16048        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16049            throw new SecurityException("Only the system may call restorePermissionGrants()");
16050        }
16051
16052        try {
16053            final XmlPullParser parser = Xml.newPullParser();
16054            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16055            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16056                    new BlobXmlRestorer() {
16057                        @Override
16058                        public void apply(XmlPullParser parser, int userId)
16059                                throws XmlPullParserException, IOException {
16060                            synchronized (mPackages) {
16061                                processRestoredPermissionGrantsLPr(parser, userId);
16062                            }
16063                        }
16064                    } );
16065        } catch (Exception e) {
16066            if (DEBUG_BACKUP) {
16067                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16068            }
16069        }
16070    }
16071
16072    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16073            throws IOException {
16074        serializer.startTag(null, TAG_ALL_GRANTS);
16075
16076        final int N = mSettings.mPackages.size();
16077        for (int i = 0; i < N; i++) {
16078            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16079            boolean pkgGrantsKnown = false;
16080
16081            PermissionsState packagePerms = ps.getPermissionsState();
16082
16083            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16084                final int grantFlags = state.getFlags();
16085                // only look at grants that are not system/policy fixed
16086                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16087                    final boolean isGranted = state.isGranted();
16088                    // And only back up the user-twiddled state bits
16089                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16090                        final String packageName = mSettings.mPackages.keyAt(i);
16091                        if (!pkgGrantsKnown) {
16092                            serializer.startTag(null, TAG_GRANT);
16093                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16094                            pkgGrantsKnown = true;
16095                        }
16096
16097                        final boolean userSet =
16098                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16099                        final boolean userFixed =
16100                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16101                        final boolean revoke =
16102                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16103
16104                        serializer.startTag(null, TAG_PERMISSION);
16105                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16106                        if (isGranted) {
16107                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16108                        }
16109                        if (userSet) {
16110                            serializer.attribute(null, ATTR_USER_SET, "true");
16111                        }
16112                        if (userFixed) {
16113                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16114                        }
16115                        if (revoke) {
16116                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16117                        }
16118                        serializer.endTag(null, TAG_PERMISSION);
16119                    }
16120                }
16121            }
16122
16123            if (pkgGrantsKnown) {
16124                serializer.endTag(null, TAG_GRANT);
16125            }
16126        }
16127
16128        serializer.endTag(null, TAG_ALL_GRANTS);
16129    }
16130
16131    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16132            throws XmlPullParserException, IOException {
16133        String pkgName = null;
16134        int outerDepth = parser.getDepth();
16135        int type;
16136        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16137                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16138            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16139                continue;
16140            }
16141
16142            final String tagName = parser.getName();
16143            if (tagName.equals(TAG_GRANT)) {
16144                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16145                if (DEBUG_BACKUP) {
16146                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16147                }
16148            } else if (tagName.equals(TAG_PERMISSION)) {
16149
16150                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16151                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16152
16153                int newFlagSet = 0;
16154                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16155                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16156                }
16157                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16158                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16159                }
16160                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16161                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16162                }
16163                if (DEBUG_BACKUP) {
16164                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16165                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16166                }
16167                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16168                if (ps != null) {
16169                    // Already installed so we apply the grant immediately
16170                    if (DEBUG_BACKUP) {
16171                        Slog.v(TAG, "        + already installed; applying");
16172                    }
16173                    PermissionsState perms = ps.getPermissionsState();
16174                    BasePermission bp = mSettings.mPermissions.get(permName);
16175                    if (bp != null) {
16176                        if (isGranted) {
16177                            perms.grantRuntimePermission(bp, userId);
16178                        }
16179                        if (newFlagSet != 0) {
16180                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16181                        }
16182                    }
16183                } else {
16184                    // Need to wait for post-restore install to apply the grant
16185                    if (DEBUG_BACKUP) {
16186                        Slog.v(TAG, "        - not yet installed; saving for later");
16187                    }
16188                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16189                            isGranted, newFlagSet, userId);
16190                }
16191            } else {
16192                PackageManagerService.reportSettingsProblem(Log.WARN,
16193                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16194                XmlUtils.skipCurrentTag(parser);
16195            }
16196        }
16197
16198        scheduleWriteSettingsLocked();
16199        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16200    }
16201
16202    @Override
16203    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16204            int sourceUserId, int targetUserId, int flags) {
16205        mContext.enforceCallingOrSelfPermission(
16206                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16207        int callingUid = Binder.getCallingUid();
16208        enforceOwnerRights(ownerPackage, callingUid);
16209        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16210        if (intentFilter.countActions() == 0) {
16211            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16212            return;
16213        }
16214        synchronized (mPackages) {
16215            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16216                    ownerPackage, targetUserId, flags);
16217            CrossProfileIntentResolver resolver =
16218                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16219            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16220            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16221            if (existing != null) {
16222                int size = existing.size();
16223                for (int i = 0; i < size; i++) {
16224                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16225                        return;
16226                    }
16227                }
16228            }
16229            resolver.addFilter(newFilter);
16230            scheduleWritePackageRestrictionsLocked(sourceUserId);
16231        }
16232    }
16233
16234    @Override
16235    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16236        mContext.enforceCallingOrSelfPermission(
16237                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16238        int callingUid = Binder.getCallingUid();
16239        enforceOwnerRights(ownerPackage, callingUid);
16240        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16241        synchronized (mPackages) {
16242            CrossProfileIntentResolver resolver =
16243                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16244            ArraySet<CrossProfileIntentFilter> set =
16245                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16246            for (CrossProfileIntentFilter filter : set) {
16247                if (filter.getOwnerPackage().equals(ownerPackage)) {
16248                    resolver.removeFilter(filter);
16249                }
16250            }
16251            scheduleWritePackageRestrictionsLocked(sourceUserId);
16252        }
16253    }
16254
16255    // Enforcing that callingUid is owning pkg on userId
16256    private void enforceOwnerRights(String pkg, int callingUid) {
16257        // The system owns everything.
16258        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16259            return;
16260        }
16261        int callingUserId = UserHandle.getUserId(callingUid);
16262        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16263        if (pi == null) {
16264            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16265                    + callingUserId);
16266        }
16267        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16268            throw new SecurityException("Calling uid " + callingUid
16269                    + " does not own package " + pkg);
16270        }
16271    }
16272
16273    @Override
16274    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16275        Intent intent = new Intent(Intent.ACTION_MAIN);
16276        intent.addCategory(Intent.CATEGORY_HOME);
16277
16278        final int callingUserId = UserHandle.getCallingUserId();
16279        List<ResolveInfo> list = queryIntentActivities(intent, null,
16280                PackageManager.GET_META_DATA, callingUserId);
16281        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16282                true, false, false, callingUserId);
16283
16284        allHomeCandidates.clear();
16285        if (list != null) {
16286            for (ResolveInfo ri : list) {
16287                allHomeCandidates.add(ri);
16288            }
16289        }
16290        return (preferred == null || preferred.activityInfo == null)
16291                ? null
16292                : new ComponentName(preferred.activityInfo.packageName,
16293                        preferred.activityInfo.name);
16294    }
16295
16296    @Override
16297    public void setApplicationEnabledSetting(String appPackageName,
16298            int newState, int flags, int userId, String callingPackage) {
16299        if (!sUserManager.exists(userId)) return;
16300        if (callingPackage == null) {
16301            callingPackage = Integer.toString(Binder.getCallingUid());
16302        }
16303        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16304    }
16305
16306    @Override
16307    public void setComponentEnabledSetting(ComponentName componentName,
16308            int newState, int flags, int userId) {
16309        if (!sUserManager.exists(userId)) return;
16310        setEnabledSetting(componentName.getPackageName(),
16311                componentName.getClassName(), newState, flags, userId, null);
16312    }
16313
16314    private void setEnabledSetting(final String packageName, String className, int newState,
16315            final int flags, int userId, String callingPackage) {
16316        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16317              || newState == COMPONENT_ENABLED_STATE_ENABLED
16318              || newState == COMPONENT_ENABLED_STATE_DISABLED
16319              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16320              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16321            throw new IllegalArgumentException("Invalid new component state: "
16322                    + newState);
16323        }
16324        PackageSetting pkgSetting;
16325        final int uid = Binder.getCallingUid();
16326        final int permission = mContext.checkCallingOrSelfPermission(
16327                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16328        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
16329        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16330        boolean sendNow = false;
16331        boolean isApp = (className == null);
16332        String componentName = isApp ? packageName : className;
16333        int packageUid = -1;
16334        ArrayList<String> components;
16335
16336        // writer
16337        synchronized (mPackages) {
16338            pkgSetting = mSettings.mPackages.get(packageName);
16339            if (pkgSetting == null) {
16340                if (className == null) {
16341                    throw new IllegalArgumentException("Unknown package: " + packageName);
16342                }
16343                throw new IllegalArgumentException(
16344                        "Unknown component: " + packageName + "/" + className);
16345            }
16346            // Allow root and verify that userId is not being specified by a different user
16347            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16348                throw new SecurityException(
16349                        "Permission Denial: attempt to change component state from pid="
16350                        + Binder.getCallingPid()
16351                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16352            }
16353            if (className == null) {
16354                // We're dealing with an application/package level state change
16355                if (pkgSetting.getEnabled(userId) == newState) {
16356                    // Nothing to do
16357                    return;
16358                }
16359                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16360                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16361                    // Don't care about who enables an app.
16362                    callingPackage = null;
16363                }
16364                pkgSetting.setEnabled(newState, userId, callingPackage);
16365                // pkgSetting.pkg.mSetEnabled = newState;
16366            } else {
16367                // We're dealing with a component level state change
16368                // First, verify that this is a valid class name.
16369                PackageParser.Package pkg = pkgSetting.pkg;
16370                if (pkg == null || !pkg.hasComponentClassName(className)) {
16371                    if (pkg != null &&
16372                            pkg.applicationInfo.targetSdkVersion >=
16373                                    Build.VERSION_CODES.JELLY_BEAN) {
16374                        throw new IllegalArgumentException("Component class " + className
16375                                + " does not exist in " + packageName);
16376                    } else {
16377                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16378                                + className + " does not exist in " + packageName);
16379                    }
16380                }
16381                switch (newState) {
16382                case COMPONENT_ENABLED_STATE_ENABLED:
16383                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16384                        return;
16385                    }
16386                    break;
16387                case COMPONENT_ENABLED_STATE_DISABLED:
16388                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16389                        return;
16390                    }
16391                    break;
16392                case COMPONENT_ENABLED_STATE_DEFAULT:
16393                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16394                        return;
16395                    }
16396                    break;
16397                default:
16398                    Slog.e(TAG, "Invalid new component state: " + newState);
16399                    return;
16400                }
16401            }
16402            scheduleWritePackageRestrictionsLocked(userId);
16403            components = mPendingBroadcasts.get(userId, packageName);
16404            final boolean newPackage = components == null;
16405            if (newPackage) {
16406                components = new ArrayList<String>();
16407            }
16408            if (!components.contains(componentName)) {
16409                components.add(componentName);
16410            }
16411            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16412                sendNow = true;
16413                // Purge entry from pending broadcast list if another one exists already
16414                // since we are sending one right away.
16415                mPendingBroadcasts.remove(userId, packageName);
16416            } else {
16417                if (newPackage) {
16418                    mPendingBroadcasts.put(userId, packageName, components);
16419                }
16420                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16421                    // Schedule a message
16422                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16423                }
16424            }
16425        }
16426
16427        long callingId = Binder.clearCallingIdentity();
16428        try {
16429            if (sendNow) {
16430                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16431                sendPackageChangedBroadcast(packageName,
16432                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16433            }
16434        } finally {
16435            Binder.restoreCallingIdentity(callingId);
16436        }
16437    }
16438
16439    private void sendPackageChangedBroadcast(String packageName,
16440            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16441        if (DEBUG_INSTALL)
16442            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16443                    + componentNames);
16444        Bundle extras = new Bundle(4);
16445        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16446        String nameList[] = new String[componentNames.size()];
16447        componentNames.toArray(nameList);
16448        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16449        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16450        extras.putInt(Intent.EXTRA_UID, packageUid);
16451        // If this is not reporting a change of the overall package, then only send it
16452        // to registered receivers.  We don't want to launch a swath of apps for every
16453        // little component state change.
16454        final int flags = !componentNames.contains(packageName)
16455                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16456        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16457                new int[] {UserHandle.getUserId(packageUid)});
16458    }
16459
16460    @Override
16461    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16462        if (!sUserManager.exists(userId)) return;
16463        final int uid = Binder.getCallingUid();
16464        final int permission = mContext.checkCallingOrSelfPermission(
16465                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16466        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16467        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16468        // writer
16469        synchronized (mPackages) {
16470            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16471                    allowedByPermission, uid, userId)) {
16472                scheduleWritePackageRestrictionsLocked(userId);
16473            }
16474        }
16475    }
16476
16477    @Override
16478    public String getInstallerPackageName(String packageName) {
16479        // reader
16480        synchronized (mPackages) {
16481            return mSettings.getInstallerPackageNameLPr(packageName);
16482        }
16483    }
16484
16485    @Override
16486    public int getApplicationEnabledSetting(String packageName, int userId) {
16487        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16488        int uid = Binder.getCallingUid();
16489        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16490        // reader
16491        synchronized (mPackages) {
16492            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16493        }
16494    }
16495
16496    @Override
16497    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16498        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16499        int uid = Binder.getCallingUid();
16500        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16501        // reader
16502        synchronized (mPackages) {
16503            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16504        }
16505    }
16506
16507    @Override
16508    public void enterSafeMode() {
16509        enforceSystemOrRoot("Only the system can request entering safe mode");
16510
16511        if (!mSystemReady) {
16512            mSafeMode = true;
16513        }
16514    }
16515
16516    @Override
16517    public void systemReady() {
16518        mSystemReady = true;
16519
16520        // Read the compatibilty setting when the system is ready.
16521        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16522                mContext.getContentResolver(),
16523                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16524        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16525        if (DEBUG_SETTINGS) {
16526            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16527        }
16528
16529        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16530
16531        synchronized (mPackages) {
16532            // Verify that all of the preferred activity components actually
16533            // exist.  It is possible for applications to be updated and at
16534            // that point remove a previously declared activity component that
16535            // had been set as a preferred activity.  We try to clean this up
16536            // the next time we encounter that preferred activity, but it is
16537            // possible for the user flow to never be able to return to that
16538            // situation so here we do a sanity check to make sure we haven't
16539            // left any junk around.
16540            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16541            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16542                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16543                removed.clear();
16544                for (PreferredActivity pa : pir.filterSet()) {
16545                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16546                        removed.add(pa);
16547                    }
16548                }
16549                if (removed.size() > 0) {
16550                    for (int r=0; r<removed.size(); r++) {
16551                        PreferredActivity pa = removed.get(r);
16552                        Slog.w(TAG, "Removing dangling preferred activity: "
16553                                + pa.mPref.mComponent);
16554                        pir.removeFilter(pa);
16555                    }
16556                    mSettings.writePackageRestrictionsLPr(
16557                            mSettings.mPreferredActivities.keyAt(i));
16558                }
16559            }
16560
16561            for (int userId : UserManagerService.getInstance().getUserIds()) {
16562                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16563                    grantPermissionsUserIds = ArrayUtils.appendInt(
16564                            grantPermissionsUserIds, userId);
16565                }
16566            }
16567        }
16568        sUserManager.systemReady();
16569
16570        // If we upgraded grant all default permissions before kicking off.
16571        for (int userId : grantPermissionsUserIds) {
16572            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16573        }
16574
16575        // Kick off any messages waiting for system ready
16576        if (mPostSystemReadyMessages != null) {
16577            for (Message msg : mPostSystemReadyMessages) {
16578                msg.sendToTarget();
16579            }
16580            mPostSystemReadyMessages = null;
16581        }
16582
16583        // Watch for external volumes that come and go over time
16584        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16585        storage.registerListener(mStorageListener);
16586
16587        mInstallerService.systemReady();
16588        mPackageDexOptimizer.systemReady();
16589
16590        MountServiceInternal mountServiceInternal = LocalServices.getService(
16591                MountServiceInternal.class);
16592        mountServiceInternal.addExternalStoragePolicy(
16593                new MountServiceInternal.ExternalStorageMountPolicy() {
16594            @Override
16595            public int getMountMode(int uid, String packageName) {
16596                if (Process.isIsolated(uid)) {
16597                    return Zygote.MOUNT_EXTERNAL_NONE;
16598                }
16599                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16600                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16601                }
16602                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16603                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16604                }
16605                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16606                    return Zygote.MOUNT_EXTERNAL_READ;
16607                }
16608                return Zygote.MOUNT_EXTERNAL_WRITE;
16609            }
16610
16611            @Override
16612            public boolean hasExternalStorage(int uid, String packageName) {
16613                return true;
16614            }
16615        });
16616    }
16617
16618    @Override
16619    public boolean isSafeMode() {
16620        return mSafeMode;
16621    }
16622
16623    @Override
16624    public boolean hasSystemUidErrors() {
16625        return mHasSystemUidErrors;
16626    }
16627
16628    static String arrayToString(int[] array) {
16629        StringBuffer buf = new StringBuffer(128);
16630        buf.append('[');
16631        if (array != null) {
16632            for (int i=0; i<array.length; i++) {
16633                if (i > 0) buf.append(", ");
16634                buf.append(array[i]);
16635            }
16636        }
16637        buf.append(']');
16638        return buf.toString();
16639    }
16640
16641    static class DumpState {
16642        public static final int DUMP_LIBS = 1 << 0;
16643        public static final int DUMP_FEATURES = 1 << 1;
16644        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16645        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16646        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16647        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16648        public static final int DUMP_PERMISSIONS = 1 << 6;
16649        public static final int DUMP_PACKAGES = 1 << 7;
16650        public static final int DUMP_SHARED_USERS = 1 << 8;
16651        public static final int DUMP_MESSAGES = 1 << 9;
16652        public static final int DUMP_PROVIDERS = 1 << 10;
16653        public static final int DUMP_VERIFIERS = 1 << 11;
16654        public static final int DUMP_PREFERRED = 1 << 12;
16655        public static final int DUMP_PREFERRED_XML = 1 << 13;
16656        public static final int DUMP_KEYSETS = 1 << 14;
16657        public static final int DUMP_VERSION = 1 << 15;
16658        public static final int DUMP_INSTALLS = 1 << 16;
16659        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16660        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16661
16662        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16663
16664        private int mTypes;
16665
16666        private int mOptions;
16667
16668        private boolean mTitlePrinted;
16669
16670        private SharedUserSetting mSharedUser;
16671
16672        public boolean isDumping(int type) {
16673            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16674                return true;
16675            }
16676
16677            return (mTypes & type) != 0;
16678        }
16679
16680        public void setDump(int type) {
16681            mTypes |= type;
16682        }
16683
16684        public boolean isOptionEnabled(int option) {
16685            return (mOptions & option) != 0;
16686        }
16687
16688        public void setOptionEnabled(int option) {
16689            mOptions |= option;
16690        }
16691
16692        public boolean onTitlePrinted() {
16693            final boolean printed = mTitlePrinted;
16694            mTitlePrinted = true;
16695            return printed;
16696        }
16697
16698        public boolean getTitlePrinted() {
16699            return mTitlePrinted;
16700        }
16701
16702        public void setTitlePrinted(boolean enabled) {
16703            mTitlePrinted = enabled;
16704        }
16705
16706        public SharedUserSetting getSharedUser() {
16707            return mSharedUser;
16708        }
16709
16710        public void setSharedUser(SharedUserSetting user) {
16711            mSharedUser = user;
16712        }
16713    }
16714
16715    @Override
16716    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16717            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16718        (new PackageManagerShellCommand(this)).exec(
16719                this, in, out, err, args, resultReceiver);
16720    }
16721
16722    @Override
16723    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16724        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16725                != PackageManager.PERMISSION_GRANTED) {
16726            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16727                    + Binder.getCallingPid()
16728                    + ", uid=" + Binder.getCallingUid()
16729                    + " without permission "
16730                    + android.Manifest.permission.DUMP);
16731            return;
16732        }
16733
16734        DumpState dumpState = new DumpState();
16735        boolean fullPreferred = false;
16736        boolean checkin = false;
16737
16738        String packageName = null;
16739        ArraySet<String> permissionNames = null;
16740
16741        int opti = 0;
16742        while (opti < args.length) {
16743            String opt = args[opti];
16744            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16745                break;
16746            }
16747            opti++;
16748
16749            if ("-a".equals(opt)) {
16750                // Right now we only know how to print all.
16751            } else if ("-h".equals(opt)) {
16752                pw.println("Package manager dump options:");
16753                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16754                pw.println("    --checkin: dump for a checkin");
16755                pw.println("    -f: print details of intent filters");
16756                pw.println("    -h: print this help");
16757                pw.println("  cmd may be one of:");
16758                pw.println("    l[ibraries]: list known shared libraries");
16759                pw.println("    f[eatures]: list device features");
16760                pw.println("    k[eysets]: print known keysets");
16761                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16762                pw.println("    perm[issions]: dump permissions");
16763                pw.println("    permission [name ...]: dump declaration and use of given permission");
16764                pw.println("    pref[erred]: print preferred package settings");
16765                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16766                pw.println("    prov[iders]: dump content providers");
16767                pw.println("    p[ackages]: dump installed packages");
16768                pw.println("    s[hared-users]: dump shared user IDs");
16769                pw.println("    m[essages]: print collected runtime messages");
16770                pw.println("    v[erifiers]: print package verifier info");
16771                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16772                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16773                pw.println("    version: print database version info");
16774                pw.println("    write: write current settings now");
16775                pw.println("    installs: details about install sessions");
16776                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16777                pw.println("    <package.name>: info about given package");
16778                return;
16779            } else if ("--checkin".equals(opt)) {
16780                checkin = true;
16781            } else if ("-f".equals(opt)) {
16782                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16783            } else {
16784                pw.println("Unknown argument: " + opt + "; use -h for help");
16785            }
16786        }
16787
16788        // Is the caller requesting to dump a particular piece of data?
16789        if (opti < args.length) {
16790            String cmd = args[opti];
16791            opti++;
16792            // Is this a package name?
16793            if ("android".equals(cmd) || cmd.contains(".")) {
16794                packageName = cmd;
16795                // When dumping a single package, we always dump all of its
16796                // filter information since the amount of data will be reasonable.
16797                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16798            } else if ("check-permission".equals(cmd)) {
16799                if (opti >= args.length) {
16800                    pw.println("Error: check-permission missing permission argument");
16801                    return;
16802                }
16803                String perm = args[opti];
16804                opti++;
16805                if (opti >= args.length) {
16806                    pw.println("Error: check-permission missing package argument");
16807                    return;
16808                }
16809                String pkg = args[opti];
16810                opti++;
16811                int user = UserHandle.getUserId(Binder.getCallingUid());
16812                if (opti < args.length) {
16813                    try {
16814                        user = Integer.parseInt(args[opti]);
16815                    } catch (NumberFormatException e) {
16816                        pw.println("Error: check-permission user argument is not a number: "
16817                                + args[opti]);
16818                        return;
16819                    }
16820                }
16821                pw.println(checkPermission(perm, pkg, user));
16822                return;
16823            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16824                dumpState.setDump(DumpState.DUMP_LIBS);
16825            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16826                dumpState.setDump(DumpState.DUMP_FEATURES);
16827            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16828                if (opti >= args.length) {
16829                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16830                            | DumpState.DUMP_SERVICE_RESOLVERS
16831                            | DumpState.DUMP_RECEIVER_RESOLVERS
16832                            | DumpState.DUMP_CONTENT_RESOLVERS);
16833                } else {
16834                    while (opti < args.length) {
16835                        String name = args[opti];
16836                        if ("a".equals(name) || "activity".equals(name)) {
16837                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16838                        } else if ("s".equals(name) || "service".equals(name)) {
16839                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16840                        } else if ("r".equals(name) || "receiver".equals(name)) {
16841                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16842                        } else if ("c".equals(name) || "content".equals(name)) {
16843                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16844                        } else {
16845                            pw.println("Error: unknown resolver table type: " + name);
16846                            return;
16847                        }
16848                        opti++;
16849                    }
16850                }
16851            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16852                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16853            } else if ("permission".equals(cmd)) {
16854                if (opti >= args.length) {
16855                    pw.println("Error: permission requires permission name");
16856                    return;
16857                }
16858                permissionNames = new ArraySet<>();
16859                while (opti < args.length) {
16860                    permissionNames.add(args[opti]);
16861                    opti++;
16862                }
16863                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16864                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16865            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16866                dumpState.setDump(DumpState.DUMP_PREFERRED);
16867            } else if ("preferred-xml".equals(cmd)) {
16868                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16869                if (opti < args.length && "--full".equals(args[opti])) {
16870                    fullPreferred = true;
16871                    opti++;
16872                }
16873            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16874                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16875            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16876                dumpState.setDump(DumpState.DUMP_PACKAGES);
16877            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16878                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16879            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16880                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16881            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16882                dumpState.setDump(DumpState.DUMP_MESSAGES);
16883            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16884                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16885            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16886                    || "intent-filter-verifiers".equals(cmd)) {
16887                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16888            } else if ("version".equals(cmd)) {
16889                dumpState.setDump(DumpState.DUMP_VERSION);
16890            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16891                dumpState.setDump(DumpState.DUMP_KEYSETS);
16892            } else if ("installs".equals(cmd)) {
16893                dumpState.setDump(DumpState.DUMP_INSTALLS);
16894            } else if ("write".equals(cmd)) {
16895                synchronized (mPackages) {
16896                    mSettings.writeLPr();
16897                    pw.println("Settings written.");
16898                    return;
16899                }
16900            }
16901        }
16902
16903        if (checkin) {
16904            pw.println("vers,1");
16905        }
16906
16907        // reader
16908        synchronized (mPackages) {
16909            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16910                if (!checkin) {
16911                    if (dumpState.onTitlePrinted())
16912                        pw.println();
16913                    pw.println("Database versions:");
16914                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16915                }
16916            }
16917
16918            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16919                if (!checkin) {
16920                    if (dumpState.onTitlePrinted())
16921                        pw.println();
16922                    pw.println("Verifiers:");
16923                    pw.print("  Required: ");
16924                    pw.print(mRequiredVerifierPackage);
16925                    pw.print(" (uid=");
16926                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16927                            UserHandle.USER_SYSTEM));
16928                    pw.println(")");
16929                } else if (mRequiredVerifierPackage != null) {
16930                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16931                    pw.print(",");
16932                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16933                            UserHandle.USER_SYSTEM));
16934                }
16935            }
16936
16937            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16938                    packageName == null) {
16939                if (mIntentFilterVerifierComponent != null) {
16940                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16941                    if (!checkin) {
16942                        if (dumpState.onTitlePrinted())
16943                            pw.println();
16944                        pw.println("Intent Filter Verifier:");
16945                        pw.print("  Using: ");
16946                        pw.print(verifierPackageName);
16947                        pw.print(" (uid=");
16948                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16949                                UserHandle.USER_SYSTEM));
16950                        pw.println(")");
16951                    } else if (verifierPackageName != null) {
16952                        pw.print("ifv,"); pw.print(verifierPackageName);
16953                        pw.print(",");
16954                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16955                                UserHandle.USER_SYSTEM));
16956                    }
16957                } else {
16958                    pw.println();
16959                    pw.println("No Intent Filter Verifier available!");
16960                }
16961            }
16962
16963            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16964                boolean printedHeader = false;
16965                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16966                while (it.hasNext()) {
16967                    String name = it.next();
16968                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16969                    if (!checkin) {
16970                        if (!printedHeader) {
16971                            if (dumpState.onTitlePrinted())
16972                                pw.println();
16973                            pw.println("Libraries:");
16974                            printedHeader = true;
16975                        }
16976                        pw.print("  ");
16977                    } else {
16978                        pw.print("lib,");
16979                    }
16980                    pw.print(name);
16981                    if (!checkin) {
16982                        pw.print(" -> ");
16983                    }
16984                    if (ent.path != null) {
16985                        if (!checkin) {
16986                            pw.print("(jar) ");
16987                            pw.print(ent.path);
16988                        } else {
16989                            pw.print(",jar,");
16990                            pw.print(ent.path);
16991                        }
16992                    } else {
16993                        if (!checkin) {
16994                            pw.print("(apk) ");
16995                            pw.print(ent.apk);
16996                        } else {
16997                            pw.print(",apk,");
16998                            pw.print(ent.apk);
16999                        }
17000                    }
17001                    pw.println();
17002                }
17003            }
17004
17005            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17006                if (dumpState.onTitlePrinted())
17007                    pw.println();
17008                if (!checkin) {
17009                    pw.println("Features:");
17010                }
17011
17012                for (FeatureInfo feat : mAvailableFeatures.values()) {
17013                    if (checkin) {
17014                        pw.print("feat,");
17015                        pw.print(feat.name);
17016                        pw.print(",");
17017                        pw.println(feat.version);
17018                    } else {
17019                        pw.print("  ");
17020                        pw.print(feat.name);
17021                        if (feat.version > 0) {
17022                            pw.print(" version=");
17023                            pw.print(feat.version);
17024                        }
17025                        pw.println();
17026                    }
17027                }
17028            }
17029
17030            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17031                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17032                        : "Activity Resolver Table:", "  ", packageName,
17033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17034                    dumpState.setTitlePrinted(true);
17035                }
17036            }
17037            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17038                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17039                        : "Receiver Resolver Table:", "  ", packageName,
17040                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17041                    dumpState.setTitlePrinted(true);
17042                }
17043            }
17044            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17045                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17046                        : "Service Resolver Table:", "  ", packageName,
17047                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17048                    dumpState.setTitlePrinted(true);
17049                }
17050            }
17051            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17052                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17053                        : "Provider Resolver Table:", "  ", packageName,
17054                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17055                    dumpState.setTitlePrinted(true);
17056                }
17057            }
17058
17059            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17060                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17061                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17062                    int user = mSettings.mPreferredActivities.keyAt(i);
17063                    if (pir.dump(pw,
17064                            dumpState.getTitlePrinted()
17065                                ? "\nPreferred Activities User " + user + ":"
17066                                : "Preferred Activities User " + user + ":", "  ",
17067                            packageName, true, false)) {
17068                        dumpState.setTitlePrinted(true);
17069                    }
17070                }
17071            }
17072
17073            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17074                pw.flush();
17075                FileOutputStream fout = new FileOutputStream(fd);
17076                BufferedOutputStream str = new BufferedOutputStream(fout);
17077                XmlSerializer serializer = new FastXmlSerializer();
17078                try {
17079                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17080                    serializer.startDocument(null, true);
17081                    serializer.setFeature(
17082                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17083                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17084                    serializer.endDocument();
17085                    serializer.flush();
17086                } catch (IllegalArgumentException e) {
17087                    pw.println("Failed writing: " + e);
17088                } catch (IllegalStateException e) {
17089                    pw.println("Failed writing: " + e);
17090                } catch (IOException e) {
17091                    pw.println("Failed writing: " + e);
17092                }
17093            }
17094
17095            if (!checkin
17096                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17097                    && packageName == null) {
17098                pw.println();
17099                int count = mSettings.mPackages.size();
17100                if (count == 0) {
17101                    pw.println("No applications!");
17102                    pw.println();
17103                } else {
17104                    final String prefix = "  ";
17105                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17106                    if (allPackageSettings.size() == 0) {
17107                        pw.println("No domain preferred apps!");
17108                        pw.println();
17109                    } else {
17110                        pw.println("App verification status:");
17111                        pw.println();
17112                        count = 0;
17113                        for (PackageSetting ps : allPackageSettings) {
17114                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17115                            if (ivi == null || ivi.getPackageName() == null) continue;
17116                            pw.println(prefix + "Package: " + ivi.getPackageName());
17117                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17118                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17119                            pw.println();
17120                            count++;
17121                        }
17122                        if (count == 0) {
17123                            pw.println(prefix + "No app verification established.");
17124                            pw.println();
17125                        }
17126                        for (int userId : sUserManager.getUserIds()) {
17127                            pw.println("App linkages for user " + userId + ":");
17128                            pw.println();
17129                            count = 0;
17130                            for (PackageSetting ps : allPackageSettings) {
17131                                final long status = ps.getDomainVerificationStatusForUser(userId);
17132                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17133                                    continue;
17134                                }
17135                                pw.println(prefix + "Package: " + ps.name);
17136                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17137                                String statusStr = IntentFilterVerificationInfo.
17138                                        getStatusStringFromValue(status);
17139                                pw.println(prefix + "Status:  " + statusStr);
17140                                pw.println();
17141                                count++;
17142                            }
17143                            if (count == 0) {
17144                                pw.println(prefix + "No configured app linkages.");
17145                                pw.println();
17146                            }
17147                        }
17148                    }
17149                }
17150            }
17151
17152            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17153                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17154                if (packageName == null && permissionNames == null) {
17155                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17156                        if (iperm == 0) {
17157                            if (dumpState.onTitlePrinted())
17158                                pw.println();
17159                            pw.println("AppOp Permissions:");
17160                        }
17161                        pw.print("  AppOp Permission ");
17162                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17163                        pw.println(":");
17164                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17165                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17166                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17167                        }
17168                    }
17169                }
17170            }
17171
17172            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17173                boolean printedSomething = false;
17174                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17175                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17176                        continue;
17177                    }
17178                    if (!printedSomething) {
17179                        if (dumpState.onTitlePrinted())
17180                            pw.println();
17181                        pw.println("Registered ContentProviders:");
17182                        printedSomething = true;
17183                    }
17184                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17185                    pw.print("    "); pw.println(p.toString());
17186                }
17187                printedSomething = false;
17188                for (Map.Entry<String, PackageParser.Provider> entry :
17189                        mProvidersByAuthority.entrySet()) {
17190                    PackageParser.Provider p = entry.getValue();
17191                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17192                        continue;
17193                    }
17194                    if (!printedSomething) {
17195                        if (dumpState.onTitlePrinted())
17196                            pw.println();
17197                        pw.println("ContentProvider Authorities:");
17198                        printedSomething = true;
17199                    }
17200                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17201                    pw.print("    "); pw.println(p.toString());
17202                    if (p.info != null && p.info.applicationInfo != null) {
17203                        final String appInfo = p.info.applicationInfo.toString();
17204                        pw.print("      applicationInfo="); pw.println(appInfo);
17205                    }
17206                }
17207            }
17208
17209            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17210                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17211            }
17212
17213            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17214                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17215            }
17216
17217            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17218                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17219            }
17220
17221            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17222                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17223            }
17224
17225            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17226                // XXX should handle packageName != null by dumping only install data that
17227                // the given package is involved with.
17228                if (dumpState.onTitlePrinted()) pw.println();
17229                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17230            }
17231
17232            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17233                if (dumpState.onTitlePrinted()) pw.println();
17234                mSettings.dumpReadMessagesLPr(pw, dumpState);
17235
17236                pw.println();
17237                pw.println("Package warning messages:");
17238                BufferedReader in = null;
17239                String line = null;
17240                try {
17241                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17242                    while ((line = in.readLine()) != null) {
17243                        if (line.contains("ignored: updated version")) continue;
17244                        pw.println(line);
17245                    }
17246                } catch (IOException ignored) {
17247                } finally {
17248                    IoUtils.closeQuietly(in);
17249                }
17250            }
17251
17252            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17253                BufferedReader in = null;
17254                String line = null;
17255                try {
17256                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17257                    while ((line = in.readLine()) != null) {
17258                        if (line.contains("ignored: updated version")) continue;
17259                        pw.print("msg,");
17260                        pw.println(line);
17261                    }
17262                } catch (IOException ignored) {
17263                } finally {
17264                    IoUtils.closeQuietly(in);
17265                }
17266            }
17267        }
17268    }
17269
17270    private String dumpDomainString(String packageName) {
17271        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17272        List<IntentFilter> filters = getAllIntentFilters(packageName);
17273
17274        ArraySet<String> result = new ArraySet<>();
17275        if (iviList.size() > 0) {
17276            for (IntentFilterVerificationInfo ivi : iviList) {
17277                for (String host : ivi.getDomains()) {
17278                    result.add(host);
17279                }
17280            }
17281        }
17282        if (filters != null && filters.size() > 0) {
17283            for (IntentFilter filter : filters) {
17284                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17285                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17286                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17287                    result.addAll(filter.getHostsList());
17288                }
17289            }
17290        }
17291
17292        StringBuilder sb = new StringBuilder(result.size() * 16);
17293        for (String domain : result) {
17294            if (sb.length() > 0) sb.append(" ");
17295            sb.append(domain);
17296        }
17297        return sb.toString();
17298    }
17299
17300    // ------- apps on sdcard specific code -------
17301    static final boolean DEBUG_SD_INSTALL = false;
17302
17303    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17304
17305    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17306
17307    private boolean mMediaMounted = false;
17308
17309    static String getEncryptKey() {
17310        try {
17311            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17312                    SD_ENCRYPTION_KEYSTORE_NAME);
17313            if (sdEncKey == null) {
17314                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17315                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17316                if (sdEncKey == null) {
17317                    Slog.e(TAG, "Failed to create encryption keys");
17318                    return null;
17319                }
17320            }
17321            return sdEncKey;
17322        } catch (NoSuchAlgorithmException nsae) {
17323            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17324            return null;
17325        } catch (IOException ioe) {
17326            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17327            return null;
17328        }
17329    }
17330
17331    /*
17332     * Update media status on PackageManager.
17333     */
17334    @Override
17335    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17336        int callingUid = Binder.getCallingUid();
17337        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17338            throw new SecurityException("Media status can only be updated by the system");
17339        }
17340        // reader; this apparently protects mMediaMounted, but should probably
17341        // be a different lock in that case.
17342        synchronized (mPackages) {
17343            Log.i(TAG, "Updating external media status from "
17344                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17345                    + (mediaStatus ? "mounted" : "unmounted"));
17346            if (DEBUG_SD_INSTALL)
17347                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17348                        + ", mMediaMounted=" + mMediaMounted);
17349            if (mediaStatus == mMediaMounted) {
17350                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17351                        : 0, -1);
17352                mHandler.sendMessage(msg);
17353                return;
17354            }
17355            mMediaMounted = mediaStatus;
17356        }
17357        // Queue up an async operation since the package installation may take a
17358        // little while.
17359        mHandler.post(new Runnable() {
17360            public void run() {
17361                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17362            }
17363        });
17364    }
17365
17366    /**
17367     * Called by MountService when the initial ASECs to scan are available.
17368     * Should block until all the ASEC containers are finished being scanned.
17369     */
17370    public void scanAvailableAsecs() {
17371        updateExternalMediaStatusInner(true, false, false);
17372    }
17373
17374    /*
17375     * Collect information of applications on external media, map them against
17376     * existing containers and update information based on current mount status.
17377     * Please note that we always have to report status if reportStatus has been
17378     * set to true especially when unloading packages.
17379     */
17380    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17381            boolean externalStorage) {
17382        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17383        int[] uidArr = EmptyArray.INT;
17384
17385        final String[] list = PackageHelper.getSecureContainerList();
17386        if (ArrayUtils.isEmpty(list)) {
17387            Log.i(TAG, "No secure containers found");
17388        } else {
17389            // Process list of secure containers and categorize them
17390            // as active or stale based on their package internal state.
17391
17392            // reader
17393            synchronized (mPackages) {
17394                for (String cid : list) {
17395                    // Leave stages untouched for now; installer service owns them
17396                    if (PackageInstallerService.isStageName(cid)) continue;
17397
17398                    if (DEBUG_SD_INSTALL)
17399                        Log.i(TAG, "Processing container " + cid);
17400                    String pkgName = getAsecPackageName(cid);
17401                    if (pkgName == null) {
17402                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17403                        continue;
17404                    }
17405                    if (DEBUG_SD_INSTALL)
17406                        Log.i(TAG, "Looking for pkg : " + pkgName);
17407
17408                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17409                    if (ps == null) {
17410                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17411                        continue;
17412                    }
17413
17414                    /*
17415                     * Skip packages that are not external if we're unmounting
17416                     * external storage.
17417                     */
17418                    if (externalStorage && !isMounted && !isExternal(ps)) {
17419                        continue;
17420                    }
17421
17422                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17423                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17424                    // The package status is changed only if the code path
17425                    // matches between settings and the container id.
17426                    if (ps.codePathString != null
17427                            && ps.codePathString.startsWith(args.getCodePath())) {
17428                        if (DEBUG_SD_INSTALL) {
17429                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17430                                    + " at code path: " + ps.codePathString);
17431                        }
17432
17433                        // We do have a valid package installed on sdcard
17434                        processCids.put(args, ps.codePathString);
17435                        final int uid = ps.appId;
17436                        if (uid != -1) {
17437                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17438                        }
17439                    } else {
17440                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17441                                + ps.codePathString);
17442                    }
17443                }
17444            }
17445
17446            Arrays.sort(uidArr);
17447        }
17448
17449        // Process packages with valid entries.
17450        if (isMounted) {
17451            if (DEBUG_SD_INSTALL)
17452                Log.i(TAG, "Loading packages");
17453            loadMediaPackages(processCids, uidArr, externalStorage);
17454            startCleaningPackages();
17455            mInstallerService.onSecureContainersAvailable();
17456        } else {
17457            if (DEBUG_SD_INSTALL)
17458                Log.i(TAG, "Unloading packages");
17459            unloadMediaPackages(processCids, uidArr, reportStatus);
17460        }
17461    }
17462
17463    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17464            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17465        final int size = infos.size();
17466        final String[] packageNames = new String[size];
17467        final int[] packageUids = new int[size];
17468        for (int i = 0; i < size; i++) {
17469            final ApplicationInfo info = infos.get(i);
17470            packageNames[i] = info.packageName;
17471            packageUids[i] = info.uid;
17472        }
17473        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17474                finishedReceiver);
17475    }
17476
17477    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17478            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17479        sendResourcesChangedBroadcast(mediaStatus, replacing,
17480                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17481    }
17482
17483    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17484            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17485        int size = pkgList.length;
17486        if (size > 0) {
17487            // Send broadcasts here
17488            Bundle extras = new Bundle();
17489            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17490            if (uidArr != null) {
17491                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17492            }
17493            if (replacing) {
17494                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17495            }
17496            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17497                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17498            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17499        }
17500    }
17501
17502   /*
17503     * Look at potentially valid container ids from processCids If package
17504     * information doesn't match the one on record or package scanning fails,
17505     * the cid is added to list of removeCids. We currently don't delete stale
17506     * containers.
17507     */
17508    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17509            boolean externalStorage) {
17510        ArrayList<String> pkgList = new ArrayList<String>();
17511        Set<AsecInstallArgs> keys = processCids.keySet();
17512
17513        for (AsecInstallArgs args : keys) {
17514            String codePath = processCids.get(args);
17515            if (DEBUG_SD_INSTALL)
17516                Log.i(TAG, "Loading container : " + args.cid);
17517            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17518            try {
17519                // Make sure there are no container errors first.
17520                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17521                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17522                            + " when installing from sdcard");
17523                    continue;
17524                }
17525                // Check code path here.
17526                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17527                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17528                            + " does not match one in settings " + codePath);
17529                    continue;
17530                }
17531                // Parse package
17532                int parseFlags = mDefParseFlags;
17533                if (args.isExternalAsec()) {
17534                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17535                }
17536                if (args.isFwdLocked()) {
17537                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17538                }
17539
17540                synchronized (mInstallLock) {
17541                    PackageParser.Package pkg = null;
17542                    try {
17543                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17544                    } catch (PackageManagerException e) {
17545                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17546                    }
17547                    // Scan the package
17548                    if (pkg != null) {
17549                        /*
17550                         * TODO why is the lock being held? doPostInstall is
17551                         * called in other places without the lock. This needs
17552                         * to be straightened out.
17553                         */
17554                        // writer
17555                        synchronized (mPackages) {
17556                            retCode = PackageManager.INSTALL_SUCCEEDED;
17557                            pkgList.add(pkg.packageName);
17558                            // Post process args
17559                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17560                                    pkg.applicationInfo.uid);
17561                        }
17562                    } else {
17563                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17564                    }
17565                }
17566
17567            } finally {
17568                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17569                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17570                }
17571            }
17572        }
17573        // writer
17574        synchronized (mPackages) {
17575            // If the platform SDK has changed since the last time we booted,
17576            // we need to re-grant app permission to catch any new ones that
17577            // appear. This is really a hack, and means that apps can in some
17578            // cases get permissions that the user didn't initially explicitly
17579            // allow... it would be nice to have some better way to handle
17580            // this situation.
17581            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17582                    : mSettings.getInternalVersion();
17583            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17584                    : StorageManager.UUID_PRIVATE_INTERNAL;
17585
17586            int updateFlags = UPDATE_PERMISSIONS_ALL;
17587            if (ver.sdkVersion != mSdkVersion) {
17588                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17589                        + mSdkVersion + "; regranting permissions for external");
17590                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17591            }
17592            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17593
17594            // Yay, everything is now upgraded
17595            ver.forceCurrent();
17596
17597            // can downgrade to reader
17598            // Persist settings
17599            mSettings.writeLPr();
17600        }
17601        // Send a broadcast to let everyone know we are done processing
17602        if (pkgList.size() > 0) {
17603            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17604        }
17605    }
17606
17607   /*
17608     * Utility method to unload a list of specified containers
17609     */
17610    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17611        // Just unmount all valid containers.
17612        for (AsecInstallArgs arg : cidArgs) {
17613            synchronized (mInstallLock) {
17614                arg.doPostDeleteLI(false);
17615           }
17616       }
17617   }
17618
17619    /*
17620     * Unload packages mounted on external media. This involves deleting package
17621     * data from internal structures, sending broadcasts about disabled packages,
17622     * gc'ing to free up references, unmounting all secure containers
17623     * corresponding to packages on external media, and posting a
17624     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17625     * that we always have to post this message if status has been requested no
17626     * matter what.
17627     */
17628    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17629            final boolean reportStatus) {
17630        if (DEBUG_SD_INSTALL)
17631            Log.i(TAG, "unloading media packages");
17632        ArrayList<String> pkgList = new ArrayList<String>();
17633        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17634        final Set<AsecInstallArgs> keys = processCids.keySet();
17635        for (AsecInstallArgs args : keys) {
17636            String pkgName = args.getPackageName();
17637            if (DEBUG_SD_INSTALL)
17638                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17639            // Delete package internally
17640            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17641            synchronized (mInstallLock) {
17642                boolean res = deletePackageLI(pkgName, null, false, null,
17643                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17644                if (res) {
17645                    pkgList.add(pkgName);
17646                } else {
17647                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17648                    failedList.add(args);
17649                }
17650            }
17651        }
17652
17653        // reader
17654        synchronized (mPackages) {
17655            // We didn't update the settings after removing each package;
17656            // write them now for all packages.
17657            mSettings.writeLPr();
17658        }
17659
17660        // We have to absolutely send UPDATED_MEDIA_STATUS only
17661        // after confirming that all the receivers processed the ordered
17662        // broadcast when packages get disabled, force a gc to clean things up.
17663        // and unload all the containers.
17664        if (pkgList.size() > 0) {
17665            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17666                    new IIntentReceiver.Stub() {
17667                public void performReceive(Intent intent, int resultCode, String data,
17668                        Bundle extras, boolean ordered, boolean sticky,
17669                        int sendingUser) throws RemoteException {
17670                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17671                            reportStatus ? 1 : 0, 1, keys);
17672                    mHandler.sendMessage(msg);
17673                }
17674            });
17675        } else {
17676            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17677                    keys);
17678            mHandler.sendMessage(msg);
17679        }
17680    }
17681
17682    private void loadPrivatePackages(final VolumeInfo vol) {
17683        mHandler.post(new Runnable() {
17684            @Override
17685            public void run() {
17686                loadPrivatePackagesInner(vol);
17687            }
17688        });
17689    }
17690
17691    private void loadPrivatePackagesInner(VolumeInfo vol) {
17692        final String volumeUuid = vol.fsUuid;
17693        if (TextUtils.isEmpty(volumeUuid)) {
17694            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17695            return;
17696        }
17697
17698        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17699        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17700
17701        final VersionInfo ver;
17702        final List<PackageSetting> packages;
17703        synchronized (mPackages) {
17704            ver = mSettings.findOrCreateVersion(volumeUuid);
17705            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17706        }
17707
17708        // TODO: introduce a new concept similar to "frozen" to prevent these
17709        // apps from being launched until after data has been fully reconciled
17710        for (PackageSetting ps : packages) {
17711            synchronized (mInstallLock) {
17712                final PackageParser.Package pkg;
17713                try {
17714                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17715                    loaded.add(pkg.applicationInfo);
17716
17717                } catch (PackageManagerException e) {
17718                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17719                }
17720
17721                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17722                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17723                }
17724            }
17725        }
17726
17727        // Reconcile app data for all started/unlocked users
17728        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17729        final UserManager um = mContext.getSystemService(UserManager.class);
17730        for (UserInfo user : um.getUsers()) {
17731            final int flags;
17732            if (um.isUserUnlocked(user.id)) {
17733                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17734            } else if (um.isUserRunning(user.id)) {
17735                flags = StorageManager.FLAG_STORAGE_DE;
17736            } else {
17737                continue;
17738            }
17739
17740            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17741            reconcileAppsData(volumeUuid, user.id, flags);
17742        }
17743
17744        synchronized (mPackages) {
17745            int updateFlags = UPDATE_PERMISSIONS_ALL;
17746            if (ver.sdkVersion != mSdkVersion) {
17747                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17748                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17749                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17750            }
17751            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17752
17753            // Yay, everything is now upgraded
17754            ver.forceCurrent();
17755
17756            mSettings.writeLPr();
17757        }
17758
17759        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17760        sendResourcesChangedBroadcast(true, false, loaded, null);
17761    }
17762
17763    private void unloadPrivatePackages(final VolumeInfo vol) {
17764        mHandler.post(new Runnable() {
17765            @Override
17766            public void run() {
17767                unloadPrivatePackagesInner(vol);
17768            }
17769        });
17770    }
17771
17772    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17773        final String volumeUuid = vol.fsUuid;
17774        if (TextUtils.isEmpty(volumeUuid)) {
17775            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17776            return;
17777        }
17778
17779        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17780        synchronized (mInstallLock) {
17781        synchronized (mPackages) {
17782            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17783            for (PackageSetting ps : packages) {
17784                if (ps.pkg == null) continue;
17785
17786                final ApplicationInfo info = ps.pkg.applicationInfo;
17787                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17788                if (deletePackageLI(ps.name, null, false, null,
17789                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17790                    unloaded.add(info);
17791                } else {
17792                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17793                }
17794            }
17795
17796            mSettings.writeLPr();
17797        }
17798        }
17799
17800        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17801        sendResourcesChangedBroadcast(false, false, unloaded, null);
17802    }
17803
17804    /**
17805     * Examine all users present on given mounted volume, and destroy data
17806     * belonging to users that are no longer valid, or whose user ID has been
17807     * recycled.
17808     */
17809    private void reconcileUsers(String volumeUuid) {
17810        // TODO: also reconcile DE directories
17811        final File[] files = FileUtils
17812                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17813        for (File file : files) {
17814            if (!file.isDirectory()) continue;
17815
17816            final int userId;
17817            final UserInfo info;
17818            try {
17819                userId = Integer.parseInt(file.getName());
17820                info = sUserManager.getUserInfo(userId);
17821            } catch (NumberFormatException e) {
17822                Slog.w(TAG, "Invalid user directory " + file);
17823                continue;
17824            }
17825
17826            boolean destroyUser = false;
17827            if (info == null) {
17828                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17829                        + " because no matching user was found");
17830                destroyUser = true;
17831            } else {
17832                try {
17833                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17834                } catch (IOException e) {
17835                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17836                            + " because we failed to enforce serial number: " + e);
17837                    destroyUser = true;
17838                }
17839            }
17840
17841            if (destroyUser) {
17842                synchronized (mInstallLock) {
17843                    try {
17844                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17845                    } catch (InstallerException e) {
17846                        Slog.w(TAG, "Failed to clean up user dirs", e);
17847                    }
17848                }
17849            }
17850        }
17851    }
17852
17853    private void assertPackageKnown(String volumeUuid, String packageName)
17854            throws PackageManagerException {
17855        synchronized (mPackages) {
17856            final PackageSetting ps = mSettings.mPackages.get(packageName);
17857            if (ps == null) {
17858                throw new PackageManagerException("Package " + packageName + " is unknown");
17859            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17860                throw new PackageManagerException(
17861                        "Package " + packageName + " found on unknown volume " + volumeUuid
17862                                + "; expected volume " + ps.volumeUuid);
17863            }
17864        }
17865    }
17866
17867    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17868            throws PackageManagerException {
17869        synchronized (mPackages) {
17870            final PackageSetting ps = mSettings.mPackages.get(packageName);
17871            if (ps == null) {
17872                throw new PackageManagerException("Package " + packageName + " is unknown");
17873            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17874                throw new PackageManagerException(
17875                        "Package " + packageName + " found on unknown volume " + volumeUuid
17876                                + "; expected volume " + ps.volumeUuid);
17877            } else if (!ps.getInstalled(userId)) {
17878                throw new PackageManagerException(
17879                        "Package " + packageName + " not installed for user " + userId);
17880            }
17881        }
17882    }
17883
17884    /**
17885     * Examine all apps present on given mounted volume, and destroy apps that
17886     * aren't expected, either due to uninstallation or reinstallation on
17887     * another volume.
17888     */
17889    private void reconcileApps(String volumeUuid) {
17890        final File[] files = FileUtils
17891                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17892        for (File file : files) {
17893            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17894                    && !PackageInstallerService.isStageName(file.getName());
17895            if (!isPackage) {
17896                // Ignore entries which are not packages
17897                continue;
17898            }
17899
17900            try {
17901                final PackageLite pkg = PackageParser.parsePackageLite(file,
17902                        PackageParser.PARSE_MUST_BE_APK);
17903                assertPackageKnown(volumeUuid, pkg.packageName);
17904
17905            } catch (PackageParserException | PackageManagerException e) {
17906                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17907                synchronized (mInstallLock) {
17908                    removeCodePathLI(file);
17909                }
17910            }
17911        }
17912    }
17913
17914    /**
17915     * Reconcile all app data for the given user.
17916     * <p>
17917     * Verifies that directories exist and that ownership and labeling is
17918     * correct for all installed apps on all mounted volumes.
17919     */
17920    void reconcileAppsData(int userId, int flags) {
17921        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17922        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17923            final String volumeUuid = vol.getFsUuid();
17924            reconcileAppsData(volumeUuid, userId, flags);
17925        }
17926    }
17927
17928    /**
17929     * Reconcile all app data on given mounted volume.
17930     * <p>
17931     * Destroys app data that isn't expected, either due to uninstallation or
17932     * reinstallation on another volume.
17933     * <p>
17934     * Verifies that directories exist and that ownership and labeling is
17935     * correct for all installed apps.
17936     */
17937    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17938        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17939                + Integer.toHexString(flags));
17940
17941        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17942        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17943
17944        boolean restoreconNeeded = false;
17945
17946        // First look for stale data that doesn't belong, and check if things
17947        // have changed since we did our last restorecon
17948        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17949            if (!isUserKeyUnlocked(userId)) {
17950                throw new RuntimeException(
17951                        "Yikes, someone asked us to reconcile CE storage while " + userId
17952                                + " was still locked; this would have caused massive data loss!");
17953            }
17954
17955            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17956
17957            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17958            for (File file : files) {
17959                final String packageName = file.getName();
17960                try {
17961                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17962                } catch (PackageManagerException e) {
17963                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17964                    synchronized (mInstallLock) {
17965                        destroyAppDataLI(volumeUuid, packageName, userId,
17966                                StorageManager.FLAG_STORAGE_CE);
17967                    }
17968                }
17969            }
17970        }
17971        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17972            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17973
17974            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17975            for (File file : files) {
17976                final String packageName = file.getName();
17977                try {
17978                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17979                } catch (PackageManagerException e) {
17980                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17981                    synchronized (mInstallLock) {
17982                        destroyAppDataLI(volumeUuid, packageName, userId,
17983                                StorageManager.FLAG_STORAGE_DE);
17984                    }
17985                }
17986            }
17987        }
17988
17989        // Ensure that data directories are ready to roll for all packages
17990        // installed for this volume and user
17991        final List<PackageSetting> packages;
17992        synchronized (mPackages) {
17993            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17994        }
17995        int preparedCount = 0;
17996        for (PackageSetting ps : packages) {
17997            final String packageName = ps.name;
17998            if (ps.pkg == null) {
17999                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18000                // TODO: might be due to legacy ASEC apps; we should circle back
18001                // and reconcile again once they're scanned
18002                continue;
18003            }
18004
18005            if (ps.getInstalled(userId)) {
18006                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18007                preparedCount++;
18008            }
18009        }
18010
18011        if (restoreconNeeded) {
18012            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18013                SELinuxMMAC.setRestoreconDone(ceDir);
18014            }
18015            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18016                SELinuxMMAC.setRestoreconDone(deDir);
18017            }
18018        }
18019
18020        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18021                + " packages; restoreconNeeded was " + restoreconNeeded);
18022    }
18023
18024    /**
18025     * Prepare app data for the given app just after it was installed or
18026     * upgraded. This method carefully only touches users that it's installed
18027     * for, and it forces a restorecon to handle any seinfo changes.
18028     * <p>
18029     * Verifies that directories exist and that ownership and labeling is
18030     * correct for all installed apps. If there is an ownership mismatch, it
18031     * will try recovering system apps by wiping data; third-party app data is
18032     * left intact.
18033     */
18034    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18035        prepareAppDataAfterInstallInternal(pkg);
18036        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18037        for (int i = 0; i < childCount; i++) {
18038            PackageParser.Package childPackage = pkg.childPackages.get(i);
18039            prepareAppDataAfterInstallInternal(childPackage);
18040        }
18041    }
18042
18043    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18044        final PackageSetting ps;
18045        synchronized (mPackages) {
18046            ps = mSettings.mPackages.get(pkg.packageName);
18047            mSettings.writeKernelMappingLPr(ps);
18048        }
18049
18050        final UserManager um = mContext.getSystemService(UserManager.class);
18051        for (UserInfo user : um.getUsers()) {
18052            final int flags;
18053            if (um.isUserUnlocked(user.id)) {
18054                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18055            } else if (um.isUserRunning(user.id)) {
18056                flags = StorageManager.FLAG_STORAGE_DE;
18057            } else {
18058                continue;
18059            }
18060
18061            if (ps.getInstalled(user.id)) {
18062                // Whenever an app changes, force a restorecon of its data
18063                // TODO: when user data is locked, mark that we're still dirty
18064                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18065            }
18066        }
18067    }
18068
18069    /**
18070     * Prepare app data for the given app.
18071     * <p>
18072     * Verifies that directories exist and that ownership and labeling is
18073     * correct for all installed apps. If there is an ownership mismatch, this
18074     * will try recovering system apps by wiping data; third-party app data is
18075     * left intact.
18076     */
18077    private void prepareAppData(String volumeUuid, int userId, int flags,
18078            PackageParser.Package pkg, boolean restoreconNeeded) {
18079        if (DEBUG_APP_DATA) {
18080            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18081                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18082        }
18083
18084        final String packageName = pkg.packageName;
18085        final ApplicationInfo app = pkg.applicationInfo;
18086        final int appId = UserHandle.getAppId(app.uid);
18087
18088        Preconditions.checkNotNull(app.seinfo);
18089
18090        synchronized (mInstallLock) {
18091            try {
18092                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18093                        appId, app.seinfo, app.targetSdkVersion);
18094            } catch (InstallerException e) {
18095                if (app.isSystemApp()) {
18096                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18097                            + ", but trying to recover: " + e);
18098                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18099                    try {
18100                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18101                                appId, app.seinfo, app.targetSdkVersion);
18102                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18103                    } catch (InstallerException e2) {
18104                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18105                    }
18106                } else {
18107                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18108                }
18109            }
18110
18111            if (restoreconNeeded) {
18112                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18113            }
18114
18115            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18116                // Create a native library symlink only if we have native libraries
18117                // and if the native libraries are 32 bit libraries. We do not provide
18118                // this symlink for 64 bit libraries.
18119                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18120                    final String nativeLibPath = app.nativeLibraryDir;
18121                    try {
18122                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18123                                nativeLibPath, userId);
18124                    } catch (InstallerException e) {
18125                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18126                    }
18127                }
18128            }
18129        }
18130    }
18131
18132    private void unfreezePackage(String packageName) {
18133        synchronized (mPackages) {
18134            final PackageSetting ps = mSettings.mPackages.get(packageName);
18135            if (ps != null) {
18136                ps.frozen = false;
18137            }
18138        }
18139    }
18140
18141    @Override
18142    public int movePackage(final String packageName, final String volumeUuid) {
18143        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18144
18145        final int moveId = mNextMoveId.getAndIncrement();
18146        mHandler.post(new Runnable() {
18147            @Override
18148            public void run() {
18149                try {
18150                    movePackageInternal(packageName, volumeUuid, moveId);
18151                } catch (PackageManagerException e) {
18152                    Slog.w(TAG, "Failed to move " + packageName, e);
18153                    mMoveCallbacks.notifyStatusChanged(moveId,
18154                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18155                }
18156            }
18157        });
18158        return moveId;
18159    }
18160
18161    private void movePackageInternal(final String packageName, final String volumeUuid,
18162            final int moveId) throws PackageManagerException {
18163        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18164        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18165        final PackageManager pm = mContext.getPackageManager();
18166
18167        final boolean currentAsec;
18168        final String currentVolumeUuid;
18169        final File codeFile;
18170        final String installerPackageName;
18171        final String packageAbiOverride;
18172        final int appId;
18173        final String seinfo;
18174        final String label;
18175        final int targetSdkVersion;
18176
18177        // reader
18178        synchronized (mPackages) {
18179            final PackageParser.Package pkg = mPackages.get(packageName);
18180            final PackageSetting ps = mSettings.mPackages.get(packageName);
18181            if (pkg == null || ps == null) {
18182                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18183            }
18184
18185            if (pkg.applicationInfo.isSystemApp()) {
18186                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18187                        "Cannot move system application");
18188            }
18189
18190            if (pkg.applicationInfo.isExternalAsec()) {
18191                currentAsec = true;
18192                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18193            } else if (pkg.applicationInfo.isForwardLocked()) {
18194                currentAsec = true;
18195                currentVolumeUuid = "forward_locked";
18196            } else {
18197                currentAsec = false;
18198                currentVolumeUuid = ps.volumeUuid;
18199
18200                final File probe = new File(pkg.codePath);
18201                final File probeOat = new File(probe, "oat");
18202                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18203                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18204                            "Move only supported for modern cluster style installs");
18205                }
18206            }
18207
18208            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18209                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18210                        "Package already moved to " + volumeUuid);
18211            }
18212            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18213                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18214                        "Device admin cannot be moved");
18215            }
18216
18217            if (ps.frozen) {
18218                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18219                        "Failed to move already frozen package");
18220            }
18221            ps.frozen = true;
18222
18223            codeFile = new File(pkg.codePath);
18224            installerPackageName = ps.installerPackageName;
18225            packageAbiOverride = ps.cpuAbiOverrideString;
18226            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18227            seinfo = pkg.applicationInfo.seinfo;
18228            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18229            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18230        }
18231
18232        // Now that we're guarded by frozen state, kill app during move
18233        final long token = Binder.clearCallingIdentity();
18234        try {
18235            killApplication(packageName, appId, "move pkg");
18236        } finally {
18237            Binder.restoreCallingIdentity(token);
18238        }
18239
18240        final Bundle extras = new Bundle();
18241        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18242        extras.putString(Intent.EXTRA_TITLE, label);
18243        mMoveCallbacks.notifyCreated(moveId, extras);
18244
18245        int installFlags;
18246        final boolean moveCompleteApp;
18247        final File measurePath;
18248
18249        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18250            installFlags = INSTALL_INTERNAL;
18251            moveCompleteApp = !currentAsec;
18252            measurePath = Environment.getDataAppDirectory(volumeUuid);
18253        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18254            installFlags = INSTALL_EXTERNAL;
18255            moveCompleteApp = false;
18256            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18257        } else {
18258            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18259            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18260                    || !volume.isMountedWritable()) {
18261                unfreezePackage(packageName);
18262                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18263                        "Move location not mounted private volume");
18264            }
18265
18266            Preconditions.checkState(!currentAsec);
18267
18268            installFlags = INSTALL_INTERNAL;
18269            moveCompleteApp = true;
18270            measurePath = Environment.getDataAppDirectory(volumeUuid);
18271        }
18272
18273        final PackageStats stats = new PackageStats(null, -1);
18274        synchronized (mInstaller) {
18275            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18276                unfreezePackage(packageName);
18277                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18278                        "Failed to measure package size");
18279            }
18280        }
18281
18282        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18283                + stats.dataSize);
18284
18285        final long startFreeBytes = measurePath.getFreeSpace();
18286        final long sizeBytes;
18287        if (moveCompleteApp) {
18288            sizeBytes = stats.codeSize + stats.dataSize;
18289        } else {
18290            sizeBytes = stats.codeSize;
18291        }
18292
18293        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18294            unfreezePackage(packageName);
18295            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18296                    "Not enough free space to move");
18297        }
18298
18299        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18300
18301        final CountDownLatch installedLatch = new CountDownLatch(1);
18302        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18303            @Override
18304            public void onUserActionRequired(Intent intent) throws RemoteException {
18305                throw new IllegalStateException();
18306            }
18307
18308            @Override
18309            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18310                    Bundle extras) throws RemoteException {
18311                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18312                        + PackageManager.installStatusToString(returnCode, msg));
18313
18314                installedLatch.countDown();
18315
18316                // Regardless of success or failure of the move operation,
18317                // always unfreeze the package
18318                unfreezePackage(packageName);
18319
18320                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18321                switch (status) {
18322                    case PackageInstaller.STATUS_SUCCESS:
18323                        mMoveCallbacks.notifyStatusChanged(moveId,
18324                                PackageManager.MOVE_SUCCEEDED);
18325                        break;
18326                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18327                        mMoveCallbacks.notifyStatusChanged(moveId,
18328                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18329                        break;
18330                    default:
18331                        mMoveCallbacks.notifyStatusChanged(moveId,
18332                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18333                        break;
18334                }
18335            }
18336        };
18337
18338        final MoveInfo move;
18339        if (moveCompleteApp) {
18340            // Kick off a thread to report progress estimates
18341            new Thread() {
18342                @Override
18343                public void run() {
18344                    while (true) {
18345                        try {
18346                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18347                                break;
18348                            }
18349                        } catch (InterruptedException ignored) {
18350                        }
18351
18352                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18353                        final int progress = 10 + (int) MathUtils.constrain(
18354                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18355                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18356                    }
18357                }
18358            }.start();
18359
18360            final String dataAppName = codeFile.getName();
18361            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18362                    dataAppName, appId, seinfo, targetSdkVersion);
18363        } else {
18364            move = null;
18365        }
18366
18367        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18368
18369        final Message msg = mHandler.obtainMessage(INIT_COPY);
18370        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18371        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18372                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18373                packageAbiOverride, null);
18374        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18375        msg.obj = params;
18376
18377        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18378                System.identityHashCode(msg.obj));
18379        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18380                System.identityHashCode(msg.obj));
18381
18382        mHandler.sendMessage(msg);
18383    }
18384
18385    @Override
18386    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18387        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18388
18389        final int realMoveId = mNextMoveId.getAndIncrement();
18390        final Bundle extras = new Bundle();
18391        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18392        mMoveCallbacks.notifyCreated(realMoveId, extras);
18393
18394        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18395            @Override
18396            public void onCreated(int moveId, Bundle extras) {
18397                // Ignored
18398            }
18399
18400            @Override
18401            public void onStatusChanged(int moveId, int status, long estMillis) {
18402                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18403            }
18404        };
18405
18406        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18407        storage.setPrimaryStorageUuid(volumeUuid, callback);
18408        return realMoveId;
18409    }
18410
18411    @Override
18412    public int getMoveStatus(int moveId) {
18413        mContext.enforceCallingOrSelfPermission(
18414                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18415        return mMoveCallbacks.mLastStatus.get(moveId);
18416    }
18417
18418    @Override
18419    public void registerMoveCallback(IPackageMoveObserver callback) {
18420        mContext.enforceCallingOrSelfPermission(
18421                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18422        mMoveCallbacks.register(callback);
18423    }
18424
18425    @Override
18426    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18427        mContext.enforceCallingOrSelfPermission(
18428                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18429        mMoveCallbacks.unregister(callback);
18430    }
18431
18432    @Override
18433    public boolean setInstallLocation(int loc) {
18434        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18435                null);
18436        if (getInstallLocation() == loc) {
18437            return true;
18438        }
18439        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18440                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18441            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18442                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18443            return true;
18444        }
18445        return false;
18446   }
18447
18448    @Override
18449    public int getInstallLocation() {
18450        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18451                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18452                PackageHelper.APP_INSTALL_AUTO);
18453    }
18454
18455    /** Called by UserManagerService */
18456    void cleanUpUser(UserManagerService userManager, int userHandle) {
18457        synchronized (mPackages) {
18458            mDirtyUsers.remove(userHandle);
18459            mUserNeedsBadging.delete(userHandle);
18460            mSettings.removeUserLPw(userHandle);
18461            mPendingBroadcasts.remove(userHandle);
18462            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18463        }
18464        synchronized (mInstallLock) {
18465            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18466            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18467                final String volumeUuid = vol.getFsUuid();
18468                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18469                try {
18470                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18471                } catch (InstallerException e) {
18472                    Slog.w(TAG, "Failed to remove user data", e);
18473                }
18474            }
18475            synchronized (mPackages) {
18476                removeUnusedPackagesLILPw(userManager, userHandle);
18477            }
18478        }
18479    }
18480
18481    /**
18482     * We're removing userHandle and would like to remove any downloaded packages
18483     * that are no longer in use by any other user.
18484     * @param userHandle the user being removed
18485     */
18486    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18487        final boolean DEBUG_CLEAN_APKS = false;
18488        int [] users = userManager.getUserIds();
18489        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18490        while (psit.hasNext()) {
18491            PackageSetting ps = psit.next();
18492            if (ps.pkg == null) {
18493                continue;
18494            }
18495            final String packageName = ps.pkg.packageName;
18496            // Skip over if system app
18497            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18498                continue;
18499            }
18500            if (DEBUG_CLEAN_APKS) {
18501                Slog.i(TAG, "Checking package " + packageName);
18502            }
18503            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18504            if (keep) {
18505                if (DEBUG_CLEAN_APKS) {
18506                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18507                }
18508            } else {
18509                for (int i = 0; i < users.length; i++) {
18510                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18511                        keep = true;
18512                        if (DEBUG_CLEAN_APKS) {
18513                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18514                                    + users[i]);
18515                        }
18516                        break;
18517                    }
18518                }
18519            }
18520            if (!keep) {
18521                if (DEBUG_CLEAN_APKS) {
18522                    Slog.i(TAG, "  Removing package " + packageName);
18523                }
18524                mHandler.post(new Runnable() {
18525                    public void run() {
18526                        deletePackageX(packageName, userHandle, 0);
18527                    } //end run
18528                });
18529            }
18530        }
18531    }
18532
18533    /** Called by UserManagerService */
18534    void createNewUser(int userHandle) {
18535        synchronized (mInstallLock) {
18536            try {
18537                mInstaller.createUserConfig(userHandle);
18538            } catch (InstallerException e) {
18539                Slog.w(TAG, "Failed to create user config", e);
18540            }
18541            mSettings.createNewUserLI(this, mInstaller, userHandle);
18542        }
18543        synchronized (mPackages) {
18544            applyFactoryDefaultBrowserLPw(userHandle);
18545            primeDomainVerificationsLPw(userHandle);
18546        }
18547    }
18548
18549    void newUserCreated(final int userHandle) {
18550        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18551        // If permission review for legacy apps is required, we represent
18552        // dagerous permissions for such apps as always granted runtime
18553        // permissions to keep per user flag state whether review is needed.
18554        // Hence, if a new user is added we have to propagate dangerous
18555        // permission grants for these legacy apps.
18556        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18557            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18558                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18559        }
18560    }
18561
18562    @Override
18563    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18564        mContext.enforceCallingOrSelfPermission(
18565                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18566                "Only package verification agents can read the verifier device identity");
18567
18568        synchronized (mPackages) {
18569            return mSettings.getVerifierDeviceIdentityLPw();
18570        }
18571    }
18572
18573    @Override
18574    public void setPermissionEnforced(String permission, boolean enforced) {
18575        // TODO: Now that we no longer change GID for storage, this should to away.
18576        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18577                "setPermissionEnforced");
18578        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18579            synchronized (mPackages) {
18580                if (mSettings.mReadExternalStorageEnforced == null
18581                        || mSettings.mReadExternalStorageEnforced != enforced) {
18582                    mSettings.mReadExternalStorageEnforced = enforced;
18583                    mSettings.writeLPr();
18584                }
18585            }
18586            // kill any non-foreground processes so we restart them and
18587            // grant/revoke the GID.
18588            final IActivityManager am = ActivityManagerNative.getDefault();
18589            if (am != null) {
18590                final long token = Binder.clearCallingIdentity();
18591                try {
18592                    am.killProcessesBelowForeground("setPermissionEnforcement");
18593                } catch (RemoteException e) {
18594                } finally {
18595                    Binder.restoreCallingIdentity(token);
18596                }
18597            }
18598        } else {
18599            throw new IllegalArgumentException("No selective enforcement for " + permission);
18600        }
18601    }
18602
18603    @Override
18604    @Deprecated
18605    public boolean isPermissionEnforced(String permission) {
18606        return true;
18607    }
18608
18609    @Override
18610    public boolean isStorageLow() {
18611        final long token = Binder.clearCallingIdentity();
18612        try {
18613            final DeviceStorageMonitorInternal
18614                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18615            if (dsm != null) {
18616                return dsm.isMemoryLow();
18617            } else {
18618                return false;
18619            }
18620        } finally {
18621            Binder.restoreCallingIdentity(token);
18622        }
18623    }
18624
18625    @Override
18626    public IPackageInstaller getPackageInstaller() {
18627        return mInstallerService;
18628    }
18629
18630    private boolean userNeedsBadging(int userId) {
18631        int index = mUserNeedsBadging.indexOfKey(userId);
18632        if (index < 0) {
18633            final UserInfo userInfo;
18634            final long token = Binder.clearCallingIdentity();
18635            try {
18636                userInfo = sUserManager.getUserInfo(userId);
18637            } finally {
18638                Binder.restoreCallingIdentity(token);
18639            }
18640            final boolean b;
18641            if (userInfo != null && userInfo.isManagedProfile()) {
18642                b = true;
18643            } else {
18644                b = false;
18645            }
18646            mUserNeedsBadging.put(userId, b);
18647            return b;
18648        }
18649        return mUserNeedsBadging.valueAt(index);
18650    }
18651
18652    @Override
18653    public KeySet getKeySetByAlias(String packageName, String alias) {
18654        if (packageName == null || alias == null) {
18655            return null;
18656        }
18657        synchronized(mPackages) {
18658            final PackageParser.Package pkg = mPackages.get(packageName);
18659            if (pkg == null) {
18660                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18661                throw new IllegalArgumentException("Unknown package: " + packageName);
18662            }
18663            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18664            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18665        }
18666    }
18667
18668    @Override
18669    public KeySet getSigningKeySet(String packageName) {
18670        if (packageName == null) {
18671            return null;
18672        }
18673        synchronized(mPackages) {
18674            final PackageParser.Package pkg = mPackages.get(packageName);
18675            if (pkg == null) {
18676                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18677                throw new IllegalArgumentException("Unknown package: " + packageName);
18678            }
18679            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18680                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18681                throw new SecurityException("May not access signing KeySet of other apps.");
18682            }
18683            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18684            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18685        }
18686    }
18687
18688    @Override
18689    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18690        if (packageName == null || ks == null) {
18691            return false;
18692        }
18693        synchronized(mPackages) {
18694            final PackageParser.Package pkg = mPackages.get(packageName);
18695            if (pkg == null) {
18696                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18697                throw new IllegalArgumentException("Unknown package: " + packageName);
18698            }
18699            IBinder ksh = ks.getToken();
18700            if (ksh instanceof KeySetHandle) {
18701                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18702                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18703            }
18704            return false;
18705        }
18706    }
18707
18708    @Override
18709    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18710        if (packageName == null || ks == null) {
18711            return false;
18712        }
18713        synchronized(mPackages) {
18714            final PackageParser.Package pkg = mPackages.get(packageName);
18715            if (pkg == null) {
18716                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18717                throw new IllegalArgumentException("Unknown package: " + packageName);
18718            }
18719            IBinder ksh = ks.getToken();
18720            if (ksh instanceof KeySetHandle) {
18721                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18722                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18723            }
18724            return false;
18725        }
18726    }
18727
18728    private void deletePackageIfUnusedLPr(final String packageName) {
18729        PackageSetting ps = mSettings.mPackages.get(packageName);
18730        if (ps == null) {
18731            return;
18732        }
18733        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18734            // TODO Implement atomic delete if package is unused
18735            // It is currently possible that the package will be deleted even if it is installed
18736            // after this method returns.
18737            mHandler.post(new Runnable() {
18738                public void run() {
18739                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18740                }
18741            });
18742        }
18743    }
18744
18745    /**
18746     * Check and throw if the given before/after packages would be considered a
18747     * downgrade.
18748     */
18749    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18750            throws PackageManagerException {
18751        if (after.versionCode < before.mVersionCode) {
18752            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18753                    "Update version code " + after.versionCode + " is older than current "
18754                    + before.mVersionCode);
18755        } else if (after.versionCode == before.mVersionCode) {
18756            if (after.baseRevisionCode < before.baseRevisionCode) {
18757                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18758                        "Update base revision code " + after.baseRevisionCode
18759                        + " is older than current " + before.baseRevisionCode);
18760            }
18761
18762            if (!ArrayUtils.isEmpty(after.splitNames)) {
18763                for (int i = 0; i < after.splitNames.length; i++) {
18764                    final String splitName = after.splitNames[i];
18765                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18766                    if (j != -1) {
18767                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18768                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18769                                    "Update split " + splitName + " revision code "
18770                                    + after.splitRevisionCodes[i] + " is older than current "
18771                                    + before.splitRevisionCodes[j]);
18772                        }
18773                    }
18774                }
18775            }
18776        }
18777    }
18778
18779    private static class MoveCallbacks extends Handler {
18780        private static final int MSG_CREATED = 1;
18781        private static final int MSG_STATUS_CHANGED = 2;
18782
18783        private final RemoteCallbackList<IPackageMoveObserver>
18784                mCallbacks = new RemoteCallbackList<>();
18785
18786        private final SparseIntArray mLastStatus = new SparseIntArray();
18787
18788        public MoveCallbacks(Looper looper) {
18789            super(looper);
18790        }
18791
18792        public void register(IPackageMoveObserver callback) {
18793            mCallbacks.register(callback);
18794        }
18795
18796        public void unregister(IPackageMoveObserver callback) {
18797            mCallbacks.unregister(callback);
18798        }
18799
18800        @Override
18801        public void handleMessage(Message msg) {
18802            final SomeArgs args = (SomeArgs) msg.obj;
18803            final int n = mCallbacks.beginBroadcast();
18804            for (int i = 0; i < n; i++) {
18805                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18806                try {
18807                    invokeCallback(callback, msg.what, args);
18808                } catch (RemoteException ignored) {
18809                }
18810            }
18811            mCallbacks.finishBroadcast();
18812            args.recycle();
18813        }
18814
18815        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18816                throws RemoteException {
18817            switch (what) {
18818                case MSG_CREATED: {
18819                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18820                    break;
18821                }
18822                case MSG_STATUS_CHANGED: {
18823                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18824                    break;
18825                }
18826            }
18827        }
18828
18829        private void notifyCreated(int moveId, Bundle extras) {
18830            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18831
18832            final SomeArgs args = SomeArgs.obtain();
18833            args.argi1 = moveId;
18834            args.arg2 = extras;
18835            obtainMessage(MSG_CREATED, args).sendToTarget();
18836        }
18837
18838        private void notifyStatusChanged(int moveId, int status) {
18839            notifyStatusChanged(moveId, status, -1);
18840        }
18841
18842        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18843            Slog.v(TAG, "Move " + moveId + " status " + status);
18844
18845            final SomeArgs args = SomeArgs.obtain();
18846            args.argi1 = moveId;
18847            args.argi2 = status;
18848            args.arg3 = estMillis;
18849            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18850
18851            synchronized (mLastStatus) {
18852                mLastStatus.put(moveId, status);
18853            }
18854        }
18855    }
18856
18857    private final static class OnPermissionChangeListeners extends Handler {
18858        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18859
18860        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18861                new RemoteCallbackList<>();
18862
18863        public OnPermissionChangeListeners(Looper looper) {
18864            super(looper);
18865        }
18866
18867        @Override
18868        public void handleMessage(Message msg) {
18869            switch (msg.what) {
18870                case MSG_ON_PERMISSIONS_CHANGED: {
18871                    final int uid = msg.arg1;
18872                    handleOnPermissionsChanged(uid);
18873                } break;
18874            }
18875        }
18876
18877        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18878            mPermissionListeners.register(listener);
18879
18880        }
18881
18882        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18883            mPermissionListeners.unregister(listener);
18884        }
18885
18886        public void onPermissionsChanged(int uid) {
18887            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18888                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18889            }
18890        }
18891
18892        private void handleOnPermissionsChanged(int uid) {
18893            final int count = mPermissionListeners.beginBroadcast();
18894            try {
18895                for (int i = 0; i < count; i++) {
18896                    IOnPermissionsChangeListener callback = mPermissionListeners
18897                            .getBroadcastItem(i);
18898                    try {
18899                        callback.onPermissionsChanged(uid);
18900                    } catch (RemoteException e) {
18901                        Log.e(TAG, "Permission listener is dead", e);
18902                    }
18903                }
18904            } finally {
18905                mPermissionListeners.finishBroadcast();
18906            }
18907        }
18908    }
18909
18910    private class PackageManagerInternalImpl extends PackageManagerInternal {
18911        @Override
18912        public void setLocationPackagesProvider(PackagesProvider provider) {
18913            synchronized (mPackages) {
18914                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18915            }
18916        }
18917
18918        @Override
18919        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18920            synchronized (mPackages) {
18921                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18922            }
18923        }
18924
18925        @Override
18926        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18927            synchronized (mPackages) {
18928                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18929            }
18930        }
18931
18932        @Override
18933        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18934            synchronized (mPackages) {
18935                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18936            }
18937        }
18938
18939        @Override
18940        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18941            synchronized (mPackages) {
18942                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18943            }
18944        }
18945
18946        @Override
18947        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18948            synchronized (mPackages) {
18949                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18950            }
18951        }
18952
18953        @Override
18954        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18955            synchronized (mPackages) {
18956                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18957                        packageName, userId);
18958            }
18959        }
18960
18961        @Override
18962        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18963            synchronized (mPackages) {
18964                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18965                        packageName, userId);
18966            }
18967        }
18968
18969        @Override
18970        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18971            synchronized (mPackages) {
18972                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18973                        packageName, userId);
18974            }
18975        }
18976
18977        @Override
18978        public void setKeepUninstalledPackages(final List<String> packageList) {
18979            Preconditions.checkNotNull(packageList);
18980            List<String> removedFromList = null;
18981            synchronized (mPackages) {
18982                if (mKeepUninstalledPackages != null) {
18983                    final int packagesCount = mKeepUninstalledPackages.size();
18984                    for (int i = 0; i < packagesCount; i++) {
18985                        String oldPackage = mKeepUninstalledPackages.get(i);
18986                        if (packageList != null && packageList.contains(oldPackage)) {
18987                            continue;
18988                        }
18989                        if (removedFromList == null) {
18990                            removedFromList = new ArrayList<>();
18991                        }
18992                        removedFromList.add(oldPackage);
18993                    }
18994                }
18995                mKeepUninstalledPackages = new ArrayList<>(packageList);
18996                if (removedFromList != null) {
18997                    final int removedCount = removedFromList.size();
18998                    for (int i = 0; i < removedCount; i++) {
18999                        deletePackageIfUnusedLPr(removedFromList.get(i));
19000                    }
19001                }
19002            }
19003        }
19004
19005        @Override
19006        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19007            synchronized (mPackages) {
19008                // If we do not support permission review, done.
19009                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19010                    return false;
19011                }
19012
19013                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19014                if (packageSetting == null) {
19015                    return false;
19016                }
19017
19018                // Permission review applies only to apps not supporting the new permission model.
19019                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19020                    return false;
19021                }
19022
19023                // Legacy apps have the permission and get user consent on launch.
19024                PermissionsState permissionsState = packageSetting.getPermissionsState();
19025                return permissionsState.isPermissionReviewRequired(userId);
19026            }
19027        }
19028    }
19029
19030    @Override
19031    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19032        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19033        synchronized (mPackages) {
19034            final long identity = Binder.clearCallingIdentity();
19035            try {
19036                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19037                        packageNames, userId);
19038            } finally {
19039                Binder.restoreCallingIdentity(identity);
19040            }
19041        }
19042    }
19043
19044    private static void enforceSystemOrPhoneCaller(String tag) {
19045        int callingUid = Binder.getCallingUid();
19046        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19047            throw new SecurityException(
19048                    "Cannot call " + tag + " from UID " + callingUid);
19049        }
19050    }
19051
19052    boolean isHistoricalPackageUsageAvailable() {
19053        return mPackageUsage.isHistoricalPackageUsageAvailable();
19054    }
19055}
19056