PackageManagerService.java revision a67932374dbbfbe4c6440d223fc7922b313dd957
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 this is first boot after an OTA, and a normal boot, then
2453            // we need to clear code cache directories.
2454            if (mIsUpgrade && !onlyCore) {
2455                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2456                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2457                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2458                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2459                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2460                    }
2461                }
2462                ver.fingerprint = Build.FINGERPRINT;
2463            }
2464
2465            checkDefaultBrowser();
2466
2467            // clear only after permissions and other defaults have been updated
2468            mExistingSystemPackages.clear();
2469            mPromoteSystemApps = false;
2470
2471            // All the changes are done during package scanning.
2472            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2473
2474            // can downgrade to reader
2475            mSettings.writeLPr();
2476
2477            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2478                    SystemClock.uptimeMillis());
2479
2480            if (!mOnlyCore) {
2481                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2482                mRequiredInstallerPackage = getRequiredInstallerLPr();
2483                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2484                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2485                        mIntentFilterVerifierComponent);
2486            } else {
2487                mRequiredVerifierPackage = null;
2488                mRequiredInstallerPackage = null;
2489                mIntentFilterVerifierComponent = null;
2490                mIntentFilterVerifier = null;
2491            }
2492
2493            mInstallerService = new PackageInstallerService(context, this);
2494
2495            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2496            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2497            // both the installer and resolver must be present to enable ephemeral
2498            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2499                if (DEBUG_EPHEMERAL) {
2500                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2501                            + " installer:" + ephemeralInstallerComponent);
2502                }
2503                mEphemeralResolverComponent = ephemeralResolverComponent;
2504                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2505                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2506                mEphemeralResolverConnection =
2507                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2508            } else {
2509                if (DEBUG_EPHEMERAL) {
2510                    final String missingComponent =
2511                            (ephemeralResolverComponent == null)
2512                            ? (ephemeralInstallerComponent == null)
2513                                    ? "resolver and installer"
2514                                    : "resolver"
2515                            : "installer";
2516                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2517                }
2518                mEphemeralResolverComponent = null;
2519                mEphemeralInstallerComponent = null;
2520                mEphemeralResolverConnection = null;
2521            }
2522
2523            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2524        } // synchronized (mPackages)
2525        } // synchronized (mInstallLock)
2526
2527        // Now after opening every single application zip, make sure they
2528        // are all flushed.  Not really needed, but keeps things nice and
2529        // tidy.
2530        Runtime.getRuntime().gc();
2531
2532        // The initial scanning above does many calls into installd while
2533        // holding the mPackages lock, but we're mostly interested in yelling
2534        // once we have a booted system.
2535        mInstaller.setWarnIfHeld(mPackages);
2536
2537        // Expose private service for system components to use.
2538        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2539    }
2540
2541    @Override
2542    public boolean isFirstBoot() {
2543        return !mRestoredSettings;
2544    }
2545
2546    @Override
2547    public boolean isOnlyCoreApps() {
2548        return mOnlyCore;
2549    }
2550
2551    @Override
2552    public boolean isUpgrade() {
2553        return mIsUpgrade;
2554    }
2555
2556    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2557        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2558
2559        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561        if (matches.size() == 1) {
2562            return matches.get(0).getComponentInfo().packageName;
2563        } else {
2564            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2565            return null;
2566        }
2567    }
2568
2569    private @NonNull String getRequiredInstallerLPr() {
2570        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2571        intent.addCategory(Intent.CATEGORY_DEFAULT);
2572        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2573
2574        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2575                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2576        if (matches.size() == 1) {
2577            return matches.get(0).getComponentInfo().packageName;
2578        } else {
2579            throw new RuntimeException("There must be exactly one installer; found " + matches);
2580        }
2581    }
2582
2583    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2584        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_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        ResolveInfo best = null;
2589        final int N = matches.size();
2590        for (int i = 0; i < N; i++) {
2591            final ResolveInfo cur = matches.get(i);
2592            final String packageName = cur.getComponentInfo().packageName;
2593            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2594                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2595                continue;
2596            }
2597
2598            if (best == null || cur.priority > best.priority) {
2599                best = cur;
2600            }
2601        }
2602
2603        if (best != null) {
2604            return best.getComponentInfo().getComponentName();
2605        } else {
2606            throw new RuntimeException("There must be at least one intent filter verifier");
2607        }
2608    }
2609
2610    private @Nullable ComponentName getEphemeralResolverLPr() {
2611        final String[] packageArray =
2612                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2613        if (packageArray.length == 0) {
2614            if (DEBUG_EPHEMERAL) {
2615                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2616            }
2617            return null;
2618        }
2619
2620        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2621        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2622                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2623
2624        final int N = resolvers.size();
2625        if (N == 0) {
2626            if (DEBUG_EPHEMERAL) {
2627                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2628            }
2629            return null;
2630        }
2631
2632        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2633        for (int i = 0; i < N; i++) {
2634            final ResolveInfo info = resolvers.get(i);
2635
2636            if (info.serviceInfo == null) {
2637                continue;
2638            }
2639
2640            final String packageName = info.serviceInfo.packageName;
2641            if (!possiblePackages.contains(packageName)) {
2642                if (DEBUG_EPHEMERAL) {
2643                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2644                            + " pkg: " + packageName + ", info:" + info);
2645                }
2646                continue;
2647            }
2648
2649            if (DEBUG_EPHEMERAL) {
2650                Slog.v(TAG, "Ephemeral resolver found;"
2651                        + " pkg: " + packageName + ", info:" + info);
2652            }
2653            return new ComponentName(packageName, info.serviceInfo.name);
2654        }
2655        if (DEBUG_EPHEMERAL) {
2656            Slog.v(TAG, "Ephemeral resolver NOT found");
2657        }
2658        return null;
2659    }
2660
2661    private @Nullable ComponentName getEphemeralInstallerLPr() {
2662        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2663        intent.addCategory(Intent.CATEGORY_DEFAULT);
2664        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2665
2666        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2667                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2668        if (matches.size() == 0) {
2669            return null;
2670        } else if (matches.size() == 1) {
2671            return matches.get(0).getComponentInfo().getComponentName();
2672        } else {
2673            throw new RuntimeException(
2674                    "There must be at most one ephemeral installer; found " + matches);
2675        }
2676    }
2677
2678    private void primeDomainVerificationsLPw(int userId) {
2679        if (DEBUG_DOMAIN_VERIFICATION) {
2680            Slog.d(TAG, "Priming domain verifications in user " + userId);
2681        }
2682
2683        SystemConfig systemConfig = SystemConfig.getInstance();
2684        ArraySet<String> packages = systemConfig.getLinkedApps();
2685        ArraySet<String> domains = new ArraySet<String>();
2686
2687        for (String packageName : packages) {
2688            PackageParser.Package pkg = mPackages.get(packageName);
2689            if (pkg != null) {
2690                if (!pkg.isSystemApp()) {
2691                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2692                    continue;
2693                }
2694
2695                domains.clear();
2696                for (PackageParser.Activity a : pkg.activities) {
2697                    for (ActivityIntentInfo filter : a.intents) {
2698                        if (hasValidDomains(filter)) {
2699                            domains.addAll(filter.getHostsList());
2700                        }
2701                    }
2702                }
2703
2704                if (domains.size() > 0) {
2705                    if (DEBUG_DOMAIN_VERIFICATION) {
2706                        Slog.v(TAG, "      + " + packageName);
2707                    }
2708                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2709                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2710                    // and then 'always' in the per-user state actually used for intent resolution.
2711                    final IntentFilterVerificationInfo ivi;
2712                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2713                            new ArrayList<String>(domains));
2714                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2715                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2716                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2717                } else {
2718                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2719                            + "' does not handle web links");
2720                }
2721            } else {
2722                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2723            }
2724        }
2725
2726        scheduleWritePackageRestrictionsLocked(userId);
2727        scheduleWriteSettingsLocked();
2728    }
2729
2730    private void applyFactoryDefaultBrowserLPw(int userId) {
2731        // The default browser app's package name is stored in a string resource,
2732        // with a product-specific overlay used for vendor customization.
2733        String browserPkg = mContext.getResources().getString(
2734                com.android.internal.R.string.default_browser);
2735        if (!TextUtils.isEmpty(browserPkg)) {
2736            // non-empty string => required to be a known package
2737            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2738            if (ps == null) {
2739                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2740                browserPkg = null;
2741            } else {
2742                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2743            }
2744        }
2745
2746        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2747        // default.  If there's more than one, just leave everything alone.
2748        if (browserPkg == null) {
2749            calculateDefaultBrowserLPw(userId);
2750        }
2751    }
2752
2753    private void calculateDefaultBrowserLPw(int userId) {
2754        List<String> allBrowsers = resolveAllBrowserApps(userId);
2755        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2756        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2757    }
2758
2759    private List<String> resolveAllBrowserApps(int userId) {
2760        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2761        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2762                PackageManager.MATCH_ALL, userId);
2763
2764        final int count = list.size();
2765        List<String> result = new ArrayList<String>(count);
2766        for (int i=0; i<count; i++) {
2767            ResolveInfo info = list.get(i);
2768            if (info.activityInfo == null
2769                    || !info.handleAllWebDataURI
2770                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2771                    || result.contains(info.activityInfo.packageName)) {
2772                continue;
2773            }
2774            result.add(info.activityInfo.packageName);
2775        }
2776
2777        return result;
2778    }
2779
2780    private boolean packageIsBrowser(String packageName, int userId) {
2781        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2782                PackageManager.MATCH_ALL, userId);
2783        final int N = list.size();
2784        for (int i = 0; i < N; i++) {
2785            ResolveInfo info = list.get(i);
2786            if (packageName.equals(info.activityInfo.packageName)) {
2787                return true;
2788            }
2789        }
2790        return false;
2791    }
2792
2793    private void checkDefaultBrowser() {
2794        final int myUserId = UserHandle.myUserId();
2795        final String packageName = getDefaultBrowserPackageName(myUserId);
2796        if (packageName != null) {
2797            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2798            if (info == null) {
2799                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2800                synchronized (mPackages) {
2801                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2802                }
2803            }
2804        }
2805    }
2806
2807    @Override
2808    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2809            throws RemoteException {
2810        try {
2811            return super.onTransact(code, data, reply, flags);
2812        } catch (RuntimeException e) {
2813            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2814                Slog.wtf(TAG, "Package Manager Crash", e);
2815            }
2816            throw e;
2817        }
2818    }
2819
2820    void cleanupInstallFailedPackage(PackageSetting ps) {
2821        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2822
2823        removeDataDirsLI(ps.volumeUuid, ps.name);
2824        if (ps.codePath != null) {
2825            removeCodePathLI(ps.codePath);
2826        }
2827        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2828            if (ps.resourcePath.isDirectory()) {
2829                FileUtils.deleteContents(ps.resourcePath);
2830            }
2831            ps.resourcePath.delete();
2832        }
2833        mSettings.removePackageLPw(ps.name);
2834    }
2835
2836    static int[] appendInts(int[] cur, int[] add) {
2837        if (add == null) return cur;
2838        if (cur == null) return add;
2839        final int N = add.length;
2840        for (int i=0; i<N; i++) {
2841            cur = appendInt(cur, add[i]);
2842        }
2843        return cur;
2844    }
2845
2846    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2847        if (!sUserManager.exists(userId)) return null;
2848        final PackageSetting ps = (PackageSetting) p.mExtras;
2849        if (ps == null) {
2850            return null;
2851        }
2852
2853        final PermissionsState permissionsState = ps.getPermissionsState();
2854
2855        final int[] gids = permissionsState.computeGids(userId);
2856        final Set<String> permissions = permissionsState.getPermissions(userId);
2857        final PackageUserState state = ps.readUserState(userId);
2858
2859        return PackageParser.generatePackageInfo(p, gids, flags,
2860                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2861    }
2862
2863    @Override
2864    public void checkPackageStartable(String packageName, int userId) {
2865        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2866
2867        synchronized (mPackages) {
2868            final PackageSetting ps = mSettings.mPackages.get(packageName);
2869            if (ps == null) {
2870                throw new SecurityException("Package " + packageName + " was not found!");
2871            }
2872
2873            if (mSafeMode && !ps.isSystem()) {
2874                throw new SecurityException("Package " + packageName + " not a system app!");
2875            }
2876
2877            if (ps.frozen) {
2878                throw new SecurityException("Package " + packageName + " is currently frozen!");
2879            }
2880
2881            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2882                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2883                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2884            }
2885        }
2886    }
2887
2888    @Override
2889    public boolean isPackageAvailable(String packageName, int userId) {
2890        if (!sUserManager.exists(userId)) return false;
2891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2892        synchronized (mPackages) {
2893            PackageParser.Package p = mPackages.get(packageName);
2894            if (p != null) {
2895                final PackageSetting ps = (PackageSetting) p.mExtras;
2896                if (ps != null) {
2897                    final PackageUserState state = ps.readUserState(userId);
2898                    if (state != null) {
2899                        return PackageParser.isAvailable(state);
2900                    }
2901                }
2902            }
2903        }
2904        return false;
2905    }
2906
2907    @Override
2908    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2909        if (!sUserManager.exists(userId)) return null;
2910        flags = updateFlagsForPackage(flags, userId, packageName);
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2912        // reader
2913        synchronized (mPackages) {
2914            PackageParser.Package p = mPackages.get(packageName);
2915            if (DEBUG_PACKAGE_INFO)
2916                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2917            if (p != null) {
2918                return generatePackageInfo(p, flags, userId);
2919            }
2920            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2921                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2922            }
2923        }
2924        return null;
2925    }
2926
2927    @Override
2928    public String[] currentToCanonicalPackageNames(String[] names) {
2929        String[] out = new String[names.length];
2930        // reader
2931        synchronized (mPackages) {
2932            for (int i=names.length-1; i>=0; i--) {
2933                PackageSetting ps = mSettings.mPackages.get(names[i]);
2934                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2935            }
2936        }
2937        return out;
2938    }
2939
2940    @Override
2941    public String[] canonicalToCurrentPackageNames(String[] names) {
2942        String[] out = new String[names.length];
2943        // reader
2944        synchronized (mPackages) {
2945            for (int i=names.length-1; i>=0; i--) {
2946                String cur = mSettings.mRenamedPackages.get(names[i]);
2947                out[i] = cur != null ? cur : names[i];
2948            }
2949        }
2950        return out;
2951    }
2952
2953    @Override
2954    public int getPackageUid(String packageName, int flags, int userId) {
2955        if (!sUserManager.exists(userId)) return -1;
2956        flags = updateFlagsForPackage(flags, userId, packageName);
2957        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2958
2959        // reader
2960        synchronized (mPackages) {
2961            final PackageParser.Package p = mPackages.get(packageName);
2962            if (p != null && p.isMatch(flags)) {
2963                return UserHandle.getUid(userId, p.applicationInfo.uid);
2964            }
2965            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2966                final PackageSetting ps = mSettings.mPackages.get(packageName);
2967                if (ps != null && ps.isMatch(flags)) {
2968                    return UserHandle.getUid(userId, ps.appId);
2969                }
2970            }
2971        }
2972
2973        return -1;
2974    }
2975
2976    @Override
2977    public int[] getPackageGids(String packageName, int flags, int userId) {
2978        if (!sUserManager.exists(userId)) return null;
2979        flags = updateFlagsForPackage(flags, userId, packageName);
2980        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2981                "getPackageGids");
2982
2983        // reader
2984        synchronized (mPackages) {
2985            final PackageParser.Package p = mPackages.get(packageName);
2986            if (p != null && p.isMatch(flags)) {
2987                PackageSetting ps = (PackageSetting) p.mExtras;
2988                return ps.getPermissionsState().computeGids(userId);
2989            }
2990            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2991                final PackageSetting ps = mSettings.mPackages.get(packageName);
2992                if (ps != null && ps.isMatch(flags)) {
2993                    return ps.getPermissionsState().computeGids(userId);
2994                }
2995            }
2996        }
2997
2998        return null;
2999    }
3000
3001    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3002        if (bp.perm != null) {
3003            return PackageParser.generatePermissionInfo(bp.perm, flags);
3004        }
3005        PermissionInfo pi = new PermissionInfo();
3006        pi.name = bp.name;
3007        pi.packageName = bp.sourcePackage;
3008        pi.nonLocalizedLabel = bp.name;
3009        pi.protectionLevel = bp.protectionLevel;
3010        return pi;
3011    }
3012
3013    @Override
3014    public PermissionInfo getPermissionInfo(String name, int flags) {
3015        // reader
3016        synchronized (mPackages) {
3017            final BasePermission p = mSettings.mPermissions.get(name);
3018            if (p != null) {
3019                return generatePermissionInfo(p, flags);
3020            }
3021            return null;
3022        }
3023    }
3024
3025    @Override
3026    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3027        // reader
3028        synchronized (mPackages) {
3029            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3030            for (BasePermission p : mSettings.mPermissions.values()) {
3031                if (group == null) {
3032                    if (p.perm == null || p.perm.info.group == null) {
3033                        out.add(generatePermissionInfo(p, flags));
3034                    }
3035                } else {
3036                    if (p.perm != null && group.equals(p.perm.info.group)) {
3037                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3038                    }
3039                }
3040            }
3041
3042            if (out.size() > 0) {
3043                return out;
3044            }
3045            return mPermissionGroups.containsKey(group) ? out : null;
3046        }
3047    }
3048
3049    @Override
3050    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3051        // reader
3052        synchronized (mPackages) {
3053            return PackageParser.generatePermissionGroupInfo(
3054                    mPermissionGroups.get(name), flags);
3055        }
3056    }
3057
3058    @Override
3059    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3060        // reader
3061        synchronized (mPackages) {
3062            final int N = mPermissionGroups.size();
3063            ArrayList<PermissionGroupInfo> out
3064                    = new ArrayList<PermissionGroupInfo>(N);
3065            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3066                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3067            }
3068            return out;
3069        }
3070    }
3071
3072    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3073            int userId) {
3074        if (!sUserManager.exists(userId)) return null;
3075        PackageSetting ps = mSettings.mPackages.get(packageName);
3076        if (ps != null) {
3077            if (ps.pkg == null) {
3078                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3079                        flags, userId);
3080                if (pInfo != null) {
3081                    return pInfo.applicationInfo;
3082                }
3083                return null;
3084            }
3085            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3086                    ps.readUserState(userId), userId);
3087        }
3088        return null;
3089    }
3090
3091    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3092            int userId) {
3093        if (!sUserManager.exists(userId)) return null;
3094        PackageSetting ps = mSettings.mPackages.get(packageName);
3095        if (ps != null) {
3096            PackageParser.Package pkg = ps.pkg;
3097            if (pkg == null) {
3098                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3099                    return null;
3100                }
3101                // Only data remains, so we aren't worried about code paths
3102                pkg = new PackageParser.Package(packageName);
3103                pkg.applicationInfo.packageName = packageName;
3104                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3105                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3106                pkg.applicationInfo.uid = ps.appId;
3107                pkg.applicationInfo.initForUser(userId);
3108                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3109                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3110            }
3111            return generatePackageInfo(pkg, flags, userId);
3112        }
3113        return null;
3114    }
3115
3116    @Override
3117    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3118        if (!sUserManager.exists(userId)) return null;
3119        flags = updateFlagsForApplication(flags, userId, packageName);
3120        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3121        // writer
3122        synchronized (mPackages) {
3123            PackageParser.Package p = mPackages.get(packageName);
3124            if (DEBUG_PACKAGE_INFO) Log.v(
3125                    TAG, "getApplicationInfo " + packageName
3126                    + ": " + p);
3127            if (p != null) {
3128                PackageSetting ps = mSettings.mPackages.get(packageName);
3129                if (ps == null) return null;
3130                // Note: isEnabledLP() does not apply here - always return info
3131                return PackageParser.generateApplicationInfo(
3132                        p, flags, ps.readUserState(userId), userId);
3133            }
3134            if ("android".equals(packageName)||"system".equals(packageName)) {
3135                return mAndroidApplication;
3136            }
3137            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3138                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3139            }
3140        }
3141        return null;
3142    }
3143
3144    @Override
3145    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3146            final IPackageDataObserver observer) {
3147        mContext.enforceCallingOrSelfPermission(
3148                android.Manifest.permission.CLEAR_APP_CACHE, null);
3149        // Queue up an async operation since clearing cache may take a little while.
3150        mHandler.post(new Runnable() {
3151            public void run() {
3152                mHandler.removeCallbacks(this);
3153                boolean success = true;
3154                synchronized (mInstallLock) {
3155                    try {
3156                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3157                    } catch (InstallerException e) {
3158                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3159                        success = false;
3160                    }
3161                }
3162                if (observer != null) {
3163                    try {
3164                        observer.onRemoveCompleted(null, success);
3165                    } catch (RemoteException e) {
3166                        Slog.w(TAG, "RemoveException when invoking call back");
3167                    }
3168                }
3169            }
3170        });
3171    }
3172
3173    @Override
3174    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3175            final IntentSender pi) {
3176        mContext.enforceCallingOrSelfPermission(
3177                android.Manifest.permission.CLEAR_APP_CACHE, null);
3178        // Queue up an async operation since clearing cache may take a little while.
3179        mHandler.post(new Runnable() {
3180            public void run() {
3181                mHandler.removeCallbacks(this);
3182                boolean success = true;
3183                synchronized (mInstallLock) {
3184                    try {
3185                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3186                    } catch (InstallerException e) {
3187                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3188                        success = false;
3189                    }
3190                }
3191                if(pi != null) {
3192                    try {
3193                        // Callback via pending intent
3194                        int code = success ? 1 : 0;
3195                        pi.sendIntent(null, code, null,
3196                                null, null);
3197                    } catch (SendIntentException e1) {
3198                        Slog.i(TAG, "Failed to send pending intent");
3199                    }
3200                }
3201            }
3202        });
3203    }
3204
3205    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3206        synchronized (mInstallLock) {
3207            try {
3208                mInstaller.freeCache(volumeUuid, freeStorageSize);
3209            } catch (InstallerException e) {
3210                throw new IOException("Failed to free enough space", e);
3211            }
3212        }
3213    }
3214
3215    /**
3216     * Return if the user key is currently unlocked.
3217     */
3218    private boolean isUserKeyUnlocked(int userId) {
3219        if (StorageManager.isFileBasedEncryptionEnabled()) {
3220            final IMountService mount = IMountService.Stub
3221                    .asInterface(ServiceManager.getService("mount"));
3222            if (mount == null) {
3223                Slog.w(TAG, "Early during boot, assuming locked");
3224                return false;
3225            }
3226            final long token = Binder.clearCallingIdentity();
3227            try {
3228                return mount.isUserKeyUnlocked(userId);
3229            } catch (RemoteException e) {
3230                throw e.rethrowAsRuntimeException();
3231            } finally {
3232                Binder.restoreCallingIdentity(token);
3233            }
3234        } else {
3235            return true;
3236        }
3237    }
3238
3239    /**
3240     * Update given flags based on encryption status of current user.
3241     */
3242    private int updateFlags(int flags, int userId) {
3243        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3244                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3245            // Caller expressed an explicit opinion about what encryption
3246            // aware/unaware components they want to see, so fall through and
3247            // give them what they want
3248        } else {
3249            // Caller expressed no opinion, so match based on user state
3250            if (isUserKeyUnlocked(userId)) {
3251                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3252            } else {
3253                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3254            }
3255        }
3256        return flags;
3257    }
3258
3259    /**
3260     * Update given flags when being used to request {@link PackageInfo}.
3261     */
3262    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3263        boolean triaged = true;
3264        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3265                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3266            // Caller is asking for component details, so they'd better be
3267            // asking for specific encryption matching behavior, or be triaged
3268            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3269                    | PackageManager.MATCH_ENCRYPTION_AWARE
3270                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3271                triaged = false;
3272            }
3273        }
3274        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3275                | PackageManager.MATCH_SYSTEM_ONLY
3276                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3277            triaged = false;
3278        }
3279        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3280            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3281                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3282        }
3283        return updateFlags(flags, userId);
3284    }
3285
3286    /**
3287     * Update given flags when being used to request {@link ApplicationInfo}.
3288     */
3289    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3290        return updateFlagsForPackage(flags, userId, cookie);
3291    }
3292
3293    /**
3294     * Update given flags when being used to request {@link ComponentInfo}.
3295     */
3296    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3297        if (cookie instanceof Intent) {
3298            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3299                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3300            }
3301        }
3302
3303        boolean triaged = true;
3304        // Caller is asking for component details, so they'd better be
3305        // asking for specific encryption matching behavior, or be triaged
3306        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3307                | PackageManager.MATCH_ENCRYPTION_AWARE
3308                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3309            triaged = false;
3310        }
3311        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3312            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3313                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3314        }
3315
3316        return updateFlags(flags, userId);
3317    }
3318
3319    /**
3320     * Update given flags when being used to request {@link ResolveInfo}.
3321     */
3322    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3323        // Safe mode means we shouldn't match any third-party components
3324        if (mSafeMode) {
3325            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3326        }
3327
3328        return updateFlagsForComponent(flags, userId, cookie);
3329    }
3330
3331    @Override
3332    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3333        if (!sUserManager.exists(userId)) return null;
3334        flags = updateFlagsForComponent(flags, userId, component);
3335        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3336        synchronized (mPackages) {
3337            PackageParser.Activity a = mActivities.mActivities.get(component);
3338
3339            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3340            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3341                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3342                if (ps == null) return null;
3343                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3344                        userId);
3345            }
3346            if (mResolveComponentName.equals(component)) {
3347                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3348                        new PackageUserState(), userId);
3349            }
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3356            String resolvedType) {
3357        synchronized (mPackages) {
3358            if (component.equals(mResolveComponentName)) {
3359                // The resolver supports EVERYTHING!
3360                return true;
3361            }
3362            PackageParser.Activity a = mActivities.mActivities.get(component);
3363            if (a == null) {
3364                return false;
3365            }
3366            for (int i=0; i<a.intents.size(); i++) {
3367                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3368                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3369                    return true;
3370                }
3371            }
3372            return false;
3373        }
3374    }
3375
3376    @Override
3377    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return null;
3379        flags = updateFlagsForComponent(flags, userId, component);
3380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3381        synchronized (mPackages) {
3382            PackageParser.Activity a = mReceivers.mActivities.get(component);
3383            if (DEBUG_PACKAGE_INFO) Log.v(
3384                TAG, "getReceiverInfo " + component + ": " + a);
3385            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3386                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3387                if (ps == null) return null;
3388                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3389                        userId);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3397        if (!sUserManager.exists(userId)) return null;
3398        flags = updateFlagsForComponent(flags, userId, component);
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3400        synchronized (mPackages) {
3401            PackageParser.Service s = mServices.mServices.get(component);
3402            if (DEBUG_PACKAGE_INFO) Log.v(
3403                TAG, "getServiceInfo " + component + ": " + s);
3404            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3405                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3406                if (ps == null) return null;
3407                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3408                        userId);
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3416        if (!sUserManager.exists(userId)) return null;
3417        flags = updateFlagsForComponent(flags, userId, component);
3418        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3419        synchronized (mPackages) {
3420            PackageParser.Provider p = mProviders.mProviders.get(component);
3421            if (DEBUG_PACKAGE_INFO) Log.v(
3422                TAG, "getProviderInfo " + component + ": " + p);
3423            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3424                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3425                if (ps == null) return null;
3426                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3427                        userId);
3428            }
3429        }
3430        return null;
3431    }
3432
3433    @Override
3434    public String[] getSystemSharedLibraryNames() {
3435        Set<String> libSet;
3436        synchronized (mPackages) {
3437            libSet = mSharedLibraries.keySet();
3438            int size = libSet.size();
3439            if (size > 0) {
3440                String[] libs = new String[size];
3441                libSet.toArray(libs);
3442                return libs;
3443            }
3444        }
3445        return null;
3446    }
3447
3448    @Override
3449    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3450        synchronized (mPackages) {
3451            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3452                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3453            if (libraryEntry != null) {
3454                return libraryEntry.apk;
3455            }
3456        }
3457        return null;
3458    }
3459
3460    @Override
3461    public FeatureInfo[] getSystemAvailableFeatures() {
3462        Collection<FeatureInfo> featSet;
3463        synchronized (mPackages) {
3464            featSet = mAvailableFeatures.values();
3465            int size = featSet.size();
3466            if (size > 0) {
3467                FeatureInfo[] features = new FeatureInfo[size+1];
3468                featSet.toArray(features);
3469                FeatureInfo fi = new FeatureInfo();
3470                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3471                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3472                features[size] = fi;
3473                return features;
3474            }
3475        }
3476        return null;
3477    }
3478
3479    @Override
3480    public boolean hasSystemFeature(String name, int version) {
3481        synchronized (mPackages) {
3482            final FeatureInfo feat = mAvailableFeatures.get(name);
3483            if (feat == null) {
3484                return false;
3485            } else {
3486                return feat.version >= version;
3487            }
3488        }
3489    }
3490
3491    @Override
3492    public int checkPermission(String permName, String pkgName, int userId) {
3493        if (!sUserManager.exists(userId)) {
3494            return PackageManager.PERMISSION_DENIED;
3495        }
3496
3497        synchronized (mPackages) {
3498            final PackageParser.Package p = mPackages.get(pkgName);
3499            if (p != null && p.mExtras != null) {
3500                final PackageSetting ps = (PackageSetting) p.mExtras;
3501                final PermissionsState permissionsState = ps.getPermissionsState();
3502                if (permissionsState.hasPermission(permName, userId)) {
3503                    return PackageManager.PERMISSION_GRANTED;
3504                }
3505                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3506                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3507                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3508                    return PackageManager.PERMISSION_GRANTED;
3509                }
3510            }
3511        }
3512
3513        return PackageManager.PERMISSION_DENIED;
3514    }
3515
3516    @Override
3517    public int checkUidPermission(String permName, int uid) {
3518        final int userId = UserHandle.getUserId(uid);
3519
3520        if (!sUserManager.exists(userId)) {
3521            return PackageManager.PERMISSION_DENIED;
3522        }
3523
3524        synchronized (mPackages) {
3525            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3526            if (obj != null) {
3527                final SettingBase ps = (SettingBase) obj;
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            } else {
3538                ArraySet<String> perms = mSystemPermissions.get(uid);
3539                if (perms != null) {
3540                    if (perms.contains(permName)) {
3541                        return PackageManager.PERMISSION_GRANTED;
3542                    }
3543                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3544                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3545                        return PackageManager.PERMISSION_GRANTED;
3546                    }
3547                }
3548            }
3549        }
3550
3551        return PackageManager.PERMISSION_DENIED;
3552    }
3553
3554    @Override
3555    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3556        if (UserHandle.getCallingUserId() != userId) {
3557            mContext.enforceCallingPermission(
3558                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3559                    "isPermissionRevokedByPolicy for user " + userId);
3560        }
3561
3562        if (checkPermission(permission, packageName, userId)
3563                == PackageManager.PERMISSION_GRANTED) {
3564            return false;
3565        }
3566
3567        final long identity = Binder.clearCallingIdentity();
3568        try {
3569            final int flags = getPermissionFlags(permission, packageName, userId);
3570            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3571        } finally {
3572            Binder.restoreCallingIdentity(identity);
3573        }
3574    }
3575
3576    @Override
3577    public String getPermissionControllerPackageName() {
3578        synchronized (mPackages) {
3579            return mRequiredInstallerPackage;
3580        }
3581    }
3582
3583    /**
3584     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3585     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3586     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3587     * @param message the message to log on security exception
3588     */
3589    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3590            boolean checkShell, String message) {
3591        if (userId < 0) {
3592            throw new IllegalArgumentException("Invalid userId " + userId);
3593        }
3594        if (checkShell) {
3595            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3596        }
3597        if (userId == UserHandle.getUserId(callingUid)) return;
3598        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3599            if (requireFullPermission) {
3600                mContext.enforceCallingOrSelfPermission(
3601                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3602            } else {
3603                try {
3604                    mContext.enforceCallingOrSelfPermission(
3605                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3606                } catch (SecurityException se) {
3607                    mContext.enforceCallingOrSelfPermission(
3608                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3609                }
3610            }
3611        }
3612    }
3613
3614    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3615        if (callingUid == Process.SHELL_UID) {
3616            if (userHandle >= 0
3617                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3618                throw new SecurityException("Shell does not have permission to access user "
3619                        + userHandle);
3620            } else if (userHandle < 0) {
3621                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3622                        + Debug.getCallers(3));
3623            }
3624        }
3625    }
3626
3627    private BasePermission findPermissionTreeLP(String permName) {
3628        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3629            if (permName.startsWith(bp.name) &&
3630                    permName.length() > bp.name.length() &&
3631                    permName.charAt(bp.name.length()) == '.') {
3632                return bp;
3633            }
3634        }
3635        return null;
3636    }
3637
3638    private BasePermission checkPermissionTreeLP(String permName) {
3639        if (permName != null) {
3640            BasePermission bp = findPermissionTreeLP(permName);
3641            if (bp != null) {
3642                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3643                    return bp;
3644                }
3645                throw new SecurityException("Calling uid "
3646                        + Binder.getCallingUid()
3647                        + " is not allowed to add to permission tree "
3648                        + bp.name + " owned by uid " + bp.uid);
3649            }
3650        }
3651        throw new SecurityException("No permission tree found for " + permName);
3652    }
3653
3654    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3655        if (s1 == null) {
3656            return s2 == null;
3657        }
3658        if (s2 == null) {
3659            return false;
3660        }
3661        if (s1.getClass() != s2.getClass()) {
3662            return false;
3663        }
3664        return s1.equals(s2);
3665    }
3666
3667    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3668        if (pi1.icon != pi2.icon) return false;
3669        if (pi1.logo != pi2.logo) return false;
3670        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3671        if (!compareStrings(pi1.name, pi2.name)) return false;
3672        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3673        // We'll take care of setting this one.
3674        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3675        // These are not currently stored in settings.
3676        //if (!compareStrings(pi1.group, pi2.group)) return false;
3677        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3678        //if (pi1.labelRes != pi2.labelRes) return false;
3679        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3680        return true;
3681    }
3682
3683    int permissionInfoFootprint(PermissionInfo info) {
3684        int size = info.name.length();
3685        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3686        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3687        return size;
3688    }
3689
3690    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3691        int size = 0;
3692        for (BasePermission perm : mSettings.mPermissions.values()) {
3693            if (perm.uid == tree.uid) {
3694                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3695            }
3696        }
3697        return size;
3698    }
3699
3700    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3701        // We calculate the max size of permissions defined by this uid and throw
3702        // if that plus the size of 'info' would exceed our stated maximum.
3703        if (tree.uid != Process.SYSTEM_UID) {
3704            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3705            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3706                throw new SecurityException("Permission tree size cap exceeded");
3707            }
3708        }
3709    }
3710
3711    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3712        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3713            throw new SecurityException("Label must be specified in permission");
3714        }
3715        BasePermission tree = checkPermissionTreeLP(info.name);
3716        BasePermission bp = mSettings.mPermissions.get(info.name);
3717        boolean added = bp == null;
3718        boolean changed = true;
3719        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3720        if (added) {
3721            enforcePermissionCapLocked(info, tree);
3722            bp = new BasePermission(info.name, tree.sourcePackage,
3723                    BasePermission.TYPE_DYNAMIC);
3724        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3725            throw new SecurityException(
3726                    "Not allowed to modify non-dynamic permission "
3727                    + info.name);
3728        } else {
3729            if (bp.protectionLevel == fixedLevel
3730                    && bp.perm.owner.equals(tree.perm.owner)
3731                    && bp.uid == tree.uid
3732                    && comparePermissionInfos(bp.perm.info, info)) {
3733                changed = false;
3734            }
3735        }
3736        bp.protectionLevel = fixedLevel;
3737        info = new PermissionInfo(info);
3738        info.protectionLevel = fixedLevel;
3739        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3740        bp.perm.info.packageName = tree.perm.info.packageName;
3741        bp.uid = tree.uid;
3742        if (added) {
3743            mSettings.mPermissions.put(info.name, bp);
3744        }
3745        if (changed) {
3746            if (!async) {
3747                mSettings.writeLPr();
3748            } else {
3749                scheduleWriteSettingsLocked();
3750            }
3751        }
3752        return added;
3753    }
3754
3755    @Override
3756    public boolean addPermission(PermissionInfo info) {
3757        synchronized (mPackages) {
3758            return addPermissionLocked(info, false);
3759        }
3760    }
3761
3762    @Override
3763    public boolean addPermissionAsync(PermissionInfo info) {
3764        synchronized (mPackages) {
3765            return addPermissionLocked(info, true);
3766        }
3767    }
3768
3769    @Override
3770    public void removePermission(String name) {
3771        synchronized (mPackages) {
3772            checkPermissionTreeLP(name);
3773            BasePermission bp = mSettings.mPermissions.get(name);
3774            if (bp != null) {
3775                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3776                    throw new SecurityException(
3777                            "Not allowed to modify non-dynamic permission "
3778                            + name);
3779                }
3780                mSettings.mPermissions.remove(name);
3781                mSettings.writeLPr();
3782            }
3783        }
3784    }
3785
3786    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3787            BasePermission bp) {
3788        int index = pkg.requestedPermissions.indexOf(bp.name);
3789        if (index == -1) {
3790            throw new SecurityException("Package " + pkg.packageName
3791                    + " has not requested permission " + bp.name);
3792        }
3793        if (!bp.isRuntime() && !bp.isDevelopment()) {
3794            throw new SecurityException("Permission " + bp.name
3795                    + " is not a changeable permission type");
3796        }
3797    }
3798
3799    @Override
3800    public void grantRuntimePermission(String packageName, String name, final int userId) {
3801        if (!sUserManager.exists(userId)) {
3802            Log.e(TAG, "No such user:" + userId);
3803            return;
3804        }
3805
3806        mContext.enforceCallingOrSelfPermission(
3807                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3808                "grantRuntimePermission");
3809
3810        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3811                "grantRuntimePermission");
3812
3813        final int uid;
3814        final SettingBase sb;
3815
3816        synchronized (mPackages) {
3817            final PackageParser.Package pkg = mPackages.get(packageName);
3818            if (pkg == null) {
3819                throw new IllegalArgumentException("Unknown package: " + packageName);
3820            }
3821
3822            final BasePermission bp = mSettings.mPermissions.get(name);
3823            if (bp == null) {
3824                throw new IllegalArgumentException("Unknown permission: " + name);
3825            }
3826
3827            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3828
3829            // If a permission review is required for legacy apps we represent
3830            // their permissions as always granted runtime ones since we need
3831            // to keep the review required permission flag per user while an
3832            // install permission's state is shared across all users.
3833            if (Build.PERMISSIONS_REVIEW_REQUIRED
3834                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3835                    && bp.isRuntime()) {
3836                return;
3837            }
3838
3839            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3840            sb = (SettingBase) pkg.mExtras;
3841            if (sb == null) {
3842                throw new IllegalArgumentException("Unknown package: " + packageName);
3843            }
3844
3845            final PermissionsState permissionsState = sb.getPermissionsState();
3846
3847            final int flags = permissionsState.getPermissionFlags(name, userId);
3848            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3849                throw new SecurityException("Cannot grant system fixed permission "
3850                        + name + " for package " + packageName);
3851            }
3852
3853            if (bp.isDevelopment()) {
3854                // Development permissions must be handled specially, since they are not
3855                // normal runtime permissions.  For now they apply to all users.
3856                if (permissionsState.grantInstallPermission(bp) !=
3857                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3858                    scheduleWriteSettingsLocked();
3859                }
3860                return;
3861            }
3862
3863            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3864                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3865                return;
3866            }
3867
3868            final int result = permissionsState.grantRuntimePermission(bp, userId);
3869            switch (result) {
3870                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3871                    return;
3872                }
3873
3874                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3875                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3876                    mHandler.post(new Runnable() {
3877                        @Override
3878                        public void run() {
3879                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3880                        }
3881                    });
3882                }
3883                break;
3884            }
3885
3886            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3887
3888            // Not critical if that is lost - app has to request again.
3889            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3890        }
3891
3892        // Only need to do this if user is initialized. Otherwise it's a new user
3893        // and there are no processes running as the user yet and there's no need
3894        // to make an expensive call to remount processes for the changed permissions.
3895        if (READ_EXTERNAL_STORAGE.equals(name)
3896                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3897            final long token = Binder.clearCallingIdentity();
3898            try {
3899                if (sUserManager.isInitialized(userId)) {
3900                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3901                            MountServiceInternal.class);
3902                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3903                }
3904            } finally {
3905                Binder.restoreCallingIdentity(token);
3906            }
3907        }
3908    }
3909
3910    @Override
3911    public void revokeRuntimePermission(String packageName, String name, int userId) {
3912        if (!sUserManager.exists(userId)) {
3913            Log.e(TAG, "No such user:" + userId);
3914            return;
3915        }
3916
3917        mContext.enforceCallingOrSelfPermission(
3918                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3919                "revokeRuntimePermission");
3920
3921        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3922                "revokeRuntimePermission");
3923
3924        final int appId;
3925
3926        synchronized (mPackages) {
3927            final PackageParser.Package pkg = mPackages.get(packageName);
3928            if (pkg == null) {
3929                throw new IllegalArgumentException("Unknown package: " + packageName);
3930            }
3931
3932            final BasePermission bp = mSettings.mPermissions.get(name);
3933            if (bp == null) {
3934                throw new IllegalArgumentException("Unknown permission: " + name);
3935            }
3936
3937            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3938
3939            // If a permission review is required for legacy apps we represent
3940            // their permissions as always granted runtime ones since we need
3941            // to keep the review required permission flag per user while an
3942            // install permission's state is shared across all users.
3943            if (Build.PERMISSIONS_REVIEW_REQUIRED
3944                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3945                    && bp.isRuntime()) {
3946                return;
3947            }
3948
3949            SettingBase sb = (SettingBase) pkg.mExtras;
3950            if (sb == null) {
3951                throw new IllegalArgumentException("Unknown package: " + packageName);
3952            }
3953
3954            final PermissionsState permissionsState = sb.getPermissionsState();
3955
3956            final int flags = permissionsState.getPermissionFlags(name, userId);
3957            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3958                throw new SecurityException("Cannot revoke system fixed permission "
3959                        + name + " for package " + packageName);
3960            }
3961
3962            if (bp.isDevelopment()) {
3963                // Development permissions must be handled specially, since they are not
3964                // normal runtime permissions.  For now they apply to all users.
3965                if (permissionsState.revokeInstallPermission(bp) !=
3966                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3967                    scheduleWriteSettingsLocked();
3968                }
3969                return;
3970            }
3971
3972            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3973                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3974                return;
3975            }
3976
3977            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3978
3979            // Critical, after this call app should never have the permission.
3980            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3981
3982            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3983        }
3984
3985        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3986    }
3987
3988    @Override
3989    public void resetRuntimePermissions() {
3990        mContext.enforceCallingOrSelfPermission(
3991                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3992                "revokeRuntimePermission");
3993
3994        int callingUid = Binder.getCallingUid();
3995        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3996            mContext.enforceCallingOrSelfPermission(
3997                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3998                    "resetRuntimePermissions");
3999        }
4000
4001        synchronized (mPackages) {
4002            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4003            for (int userId : UserManagerService.getInstance().getUserIds()) {
4004                final int packageCount = mPackages.size();
4005                for (int i = 0; i < packageCount; i++) {
4006                    PackageParser.Package pkg = mPackages.valueAt(i);
4007                    if (!(pkg.mExtras instanceof PackageSetting)) {
4008                        continue;
4009                    }
4010                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4011                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4012                }
4013            }
4014        }
4015    }
4016
4017    @Override
4018    public int getPermissionFlags(String name, String packageName, int userId) {
4019        if (!sUserManager.exists(userId)) {
4020            return 0;
4021        }
4022
4023        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4024
4025        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4026                "getPermissionFlags");
4027
4028        synchronized (mPackages) {
4029            final PackageParser.Package pkg = mPackages.get(packageName);
4030            if (pkg == null) {
4031                throw new IllegalArgumentException("Unknown package: " + packageName);
4032            }
4033
4034            final BasePermission bp = mSettings.mPermissions.get(name);
4035            if (bp == null) {
4036                throw new IllegalArgumentException("Unknown permission: " + name);
4037            }
4038
4039            SettingBase sb = (SettingBase) pkg.mExtras;
4040            if (sb == null) {
4041                throw new IllegalArgumentException("Unknown package: " + packageName);
4042            }
4043
4044            PermissionsState permissionsState = sb.getPermissionsState();
4045            return permissionsState.getPermissionFlags(name, userId);
4046        }
4047    }
4048
4049    @Override
4050    public void updatePermissionFlags(String name, String packageName, int flagMask,
4051            int flagValues, int userId) {
4052        if (!sUserManager.exists(userId)) {
4053            return;
4054        }
4055
4056        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4057
4058        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4059                "updatePermissionFlags");
4060
4061        // Only the system can change these flags and nothing else.
4062        if (getCallingUid() != Process.SYSTEM_UID) {
4063            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4064            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4065            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4066            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4067            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4068        }
4069
4070        synchronized (mPackages) {
4071            final PackageParser.Package pkg = mPackages.get(packageName);
4072            if (pkg == null) {
4073                throw new IllegalArgumentException("Unknown package: " + packageName);
4074            }
4075
4076            final BasePermission bp = mSettings.mPermissions.get(name);
4077            if (bp == null) {
4078                throw new IllegalArgumentException("Unknown permission: " + name);
4079            }
4080
4081            SettingBase sb = (SettingBase) pkg.mExtras;
4082            if (sb == null) {
4083                throw new IllegalArgumentException("Unknown package: " + packageName);
4084            }
4085
4086            PermissionsState permissionsState = sb.getPermissionsState();
4087
4088            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4089
4090            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4091                // Install and runtime permissions are stored in different places,
4092                // so figure out what permission changed and persist the change.
4093                if (permissionsState.getInstallPermissionState(name) != null) {
4094                    scheduleWriteSettingsLocked();
4095                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4096                        || hadState) {
4097                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4098                }
4099            }
4100        }
4101    }
4102
4103    /**
4104     * Update the permission flags for all packages and runtime permissions of a user in order
4105     * to allow device or profile owner to remove POLICY_FIXED.
4106     */
4107    @Override
4108    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4109        if (!sUserManager.exists(userId)) {
4110            return;
4111        }
4112
4113        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4114
4115        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4116                "updatePermissionFlagsForAllApps");
4117
4118        // Only the system can change system fixed flags.
4119        if (getCallingUid() != Process.SYSTEM_UID) {
4120            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4121            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4122        }
4123
4124        synchronized (mPackages) {
4125            boolean changed = false;
4126            final int packageCount = mPackages.size();
4127            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4128                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4129                SettingBase sb = (SettingBase) pkg.mExtras;
4130                if (sb == null) {
4131                    continue;
4132                }
4133                PermissionsState permissionsState = sb.getPermissionsState();
4134                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4135                        userId, flagMask, flagValues);
4136            }
4137            if (changed) {
4138                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4139            }
4140        }
4141    }
4142
4143    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4144        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4145                != PackageManager.PERMISSION_GRANTED
4146            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4147                != PackageManager.PERMISSION_GRANTED) {
4148            throw new SecurityException(message + " requires "
4149                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4150                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4151        }
4152    }
4153
4154    @Override
4155    public boolean shouldShowRequestPermissionRationale(String permissionName,
4156            String packageName, int userId) {
4157        if (UserHandle.getCallingUserId() != userId) {
4158            mContext.enforceCallingPermission(
4159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4160                    "canShowRequestPermissionRationale for user " + userId);
4161        }
4162
4163        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4164        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4165            return false;
4166        }
4167
4168        if (checkPermission(permissionName, packageName, userId)
4169                == PackageManager.PERMISSION_GRANTED) {
4170            return false;
4171        }
4172
4173        final int flags;
4174
4175        final long identity = Binder.clearCallingIdentity();
4176        try {
4177            flags = getPermissionFlags(permissionName,
4178                    packageName, userId);
4179        } finally {
4180            Binder.restoreCallingIdentity(identity);
4181        }
4182
4183        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4184                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4185                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4186
4187        if ((flags & fixedFlags) != 0) {
4188            return false;
4189        }
4190
4191        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4192    }
4193
4194    @Override
4195    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4196        mContext.enforceCallingOrSelfPermission(
4197                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4198                "addOnPermissionsChangeListener");
4199
4200        synchronized (mPackages) {
4201            mOnPermissionChangeListeners.addListenerLocked(listener);
4202        }
4203    }
4204
4205    @Override
4206    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4207        synchronized (mPackages) {
4208            mOnPermissionChangeListeners.removeListenerLocked(listener);
4209        }
4210    }
4211
4212    @Override
4213    public boolean isProtectedBroadcast(String actionName) {
4214        synchronized (mPackages) {
4215            if (mProtectedBroadcasts.contains(actionName)) {
4216                return true;
4217            } else if (actionName != null) {
4218                // TODO: remove these terrible hacks
4219                if (actionName.startsWith("android.net.netmon.lingerExpired")
4220                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4221                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")) {
4222                    return true;
4223                }
4224            }
4225        }
4226        return false;
4227    }
4228
4229    @Override
4230    public int checkSignatures(String pkg1, String pkg2) {
4231        synchronized (mPackages) {
4232            final PackageParser.Package p1 = mPackages.get(pkg1);
4233            final PackageParser.Package p2 = mPackages.get(pkg2);
4234            if (p1 == null || p1.mExtras == null
4235                    || p2 == null || p2.mExtras == null) {
4236                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4237            }
4238            return compareSignatures(p1.mSignatures, p2.mSignatures);
4239        }
4240    }
4241
4242    @Override
4243    public int checkUidSignatures(int uid1, int uid2) {
4244        // Map to base uids.
4245        uid1 = UserHandle.getAppId(uid1);
4246        uid2 = UserHandle.getAppId(uid2);
4247        // reader
4248        synchronized (mPackages) {
4249            Signature[] s1;
4250            Signature[] s2;
4251            Object obj = mSettings.getUserIdLPr(uid1);
4252            if (obj != null) {
4253                if (obj instanceof SharedUserSetting) {
4254                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4255                } else if (obj instanceof PackageSetting) {
4256                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4257                } else {
4258                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4259                }
4260            } else {
4261                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4262            }
4263            obj = mSettings.getUserIdLPr(uid2);
4264            if (obj != null) {
4265                if (obj instanceof SharedUserSetting) {
4266                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4267                } else if (obj instanceof PackageSetting) {
4268                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4269                } else {
4270                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4271                }
4272            } else {
4273                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4274            }
4275            return compareSignatures(s1, s2);
4276        }
4277    }
4278
4279    private void killUid(int appId, int userId, String reason) {
4280        final long identity = Binder.clearCallingIdentity();
4281        try {
4282            IActivityManager am = ActivityManagerNative.getDefault();
4283            if (am != null) {
4284                try {
4285                    am.killUid(appId, userId, reason);
4286                } catch (RemoteException e) {
4287                    /* ignore - same process */
4288                }
4289            }
4290        } finally {
4291            Binder.restoreCallingIdentity(identity);
4292        }
4293    }
4294
4295    /**
4296     * Compares two sets of signatures. Returns:
4297     * <br />
4298     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4299     * <br />
4300     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4301     * <br />
4302     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4303     * <br />
4304     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4305     * <br />
4306     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4307     */
4308    static int compareSignatures(Signature[] s1, Signature[] s2) {
4309        if (s1 == null) {
4310            return s2 == null
4311                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4312                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4313        }
4314
4315        if (s2 == null) {
4316            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4317        }
4318
4319        if (s1.length != s2.length) {
4320            return PackageManager.SIGNATURE_NO_MATCH;
4321        }
4322
4323        // Since both signature sets are of size 1, we can compare without HashSets.
4324        if (s1.length == 1) {
4325            return s1[0].equals(s2[0]) ?
4326                    PackageManager.SIGNATURE_MATCH :
4327                    PackageManager.SIGNATURE_NO_MATCH;
4328        }
4329
4330        ArraySet<Signature> set1 = new ArraySet<Signature>();
4331        for (Signature sig : s1) {
4332            set1.add(sig);
4333        }
4334        ArraySet<Signature> set2 = new ArraySet<Signature>();
4335        for (Signature sig : s2) {
4336            set2.add(sig);
4337        }
4338        // Make sure s2 contains all signatures in s1.
4339        if (set1.equals(set2)) {
4340            return PackageManager.SIGNATURE_MATCH;
4341        }
4342        return PackageManager.SIGNATURE_NO_MATCH;
4343    }
4344
4345    /**
4346     * If the database version for this type of package (internal storage or
4347     * external storage) is less than the version where package signatures
4348     * were updated, return true.
4349     */
4350    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4351        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4352        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4353    }
4354
4355    /**
4356     * Used for backward compatibility to make sure any packages with
4357     * certificate chains get upgraded to the new style. {@code existingSigs}
4358     * will be in the old format (since they were stored on disk from before the
4359     * system upgrade) and {@code scannedSigs} will be in the newer format.
4360     */
4361    private int compareSignaturesCompat(PackageSignatures existingSigs,
4362            PackageParser.Package scannedPkg) {
4363        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4364            return PackageManager.SIGNATURE_NO_MATCH;
4365        }
4366
4367        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4368        for (Signature sig : existingSigs.mSignatures) {
4369            existingSet.add(sig);
4370        }
4371        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4372        for (Signature sig : scannedPkg.mSignatures) {
4373            try {
4374                Signature[] chainSignatures = sig.getChainSignatures();
4375                for (Signature chainSig : chainSignatures) {
4376                    scannedCompatSet.add(chainSig);
4377                }
4378            } catch (CertificateEncodingException e) {
4379                scannedCompatSet.add(sig);
4380            }
4381        }
4382        /*
4383         * Make sure the expanded scanned set contains all signatures in the
4384         * existing one.
4385         */
4386        if (scannedCompatSet.equals(existingSet)) {
4387            // Migrate the old signatures to the new scheme.
4388            existingSigs.assignSignatures(scannedPkg.mSignatures);
4389            // The new KeySets will be re-added later in the scanning process.
4390            synchronized (mPackages) {
4391                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4392            }
4393            return PackageManager.SIGNATURE_MATCH;
4394        }
4395        return PackageManager.SIGNATURE_NO_MATCH;
4396    }
4397
4398    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4399        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4400        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4401    }
4402
4403    private int compareSignaturesRecover(PackageSignatures existingSigs,
4404            PackageParser.Package scannedPkg) {
4405        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4406            return PackageManager.SIGNATURE_NO_MATCH;
4407        }
4408
4409        String msg = null;
4410        try {
4411            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4412                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4413                        + scannedPkg.packageName);
4414                return PackageManager.SIGNATURE_MATCH;
4415            }
4416        } catch (CertificateException e) {
4417            msg = e.getMessage();
4418        }
4419
4420        logCriticalInfo(Log.INFO,
4421                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4422        return PackageManager.SIGNATURE_NO_MATCH;
4423    }
4424
4425    @Override
4426    public String[] getPackagesForUid(int uid) {
4427        uid = UserHandle.getAppId(uid);
4428        // reader
4429        synchronized (mPackages) {
4430            Object obj = mSettings.getUserIdLPr(uid);
4431            if (obj instanceof SharedUserSetting) {
4432                final SharedUserSetting sus = (SharedUserSetting) obj;
4433                final int N = sus.packages.size();
4434                final String[] res = new String[N];
4435                final Iterator<PackageSetting> it = sus.packages.iterator();
4436                int i = 0;
4437                while (it.hasNext()) {
4438                    res[i++] = it.next().name;
4439                }
4440                return res;
4441            } else if (obj instanceof PackageSetting) {
4442                final PackageSetting ps = (PackageSetting) obj;
4443                return new String[] { ps.name };
4444            }
4445        }
4446        return null;
4447    }
4448
4449    @Override
4450    public String getNameForUid(int uid) {
4451        // reader
4452        synchronized (mPackages) {
4453            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4454            if (obj instanceof SharedUserSetting) {
4455                final SharedUserSetting sus = (SharedUserSetting) obj;
4456                return sus.name + ":" + sus.userId;
4457            } else if (obj instanceof PackageSetting) {
4458                final PackageSetting ps = (PackageSetting) obj;
4459                return ps.name;
4460            }
4461        }
4462        return null;
4463    }
4464
4465    @Override
4466    public int getUidForSharedUser(String sharedUserName) {
4467        if(sharedUserName == null) {
4468            return -1;
4469        }
4470        // reader
4471        synchronized (mPackages) {
4472            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4473            if (suid == null) {
4474                return -1;
4475            }
4476            return suid.userId;
4477        }
4478    }
4479
4480    @Override
4481    public int getFlagsForUid(int uid) {
4482        synchronized (mPackages) {
4483            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4484            if (obj instanceof SharedUserSetting) {
4485                final SharedUserSetting sus = (SharedUserSetting) obj;
4486                return sus.pkgFlags;
4487            } else if (obj instanceof PackageSetting) {
4488                final PackageSetting ps = (PackageSetting) obj;
4489                return ps.pkgFlags;
4490            }
4491        }
4492        return 0;
4493    }
4494
4495    @Override
4496    public int getPrivateFlagsForUid(int uid) {
4497        synchronized (mPackages) {
4498            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4499            if (obj instanceof SharedUserSetting) {
4500                final SharedUserSetting sus = (SharedUserSetting) obj;
4501                return sus.pkgPrivateFlags;
4502            } else if (obj instanceof PackageSetting) {
4503                final PackageSetting ps = (PackageSetting) obj;
4504                return ps.pkgPrivateFlags;
4505            }
4506        }
4507        return 0;
4508    }
4509
4510    @Override
4511    public boolean isUidPrivileged(int uid) {
4512        uid = UserHandle.getAppId(uid);
4513        // reader
4514        synchronized (mPackages) {
4515            Object obj = mSettings.getUserIdLPr(uid);
4516            if (obj instanceof SharedUserSetting) {
4517                final SharedUserSetting sus = (SharedUserSetting) obj;
4518                final Iterator<PackageSetting> it = sus.packages.iterator();
4519                while (it.hasNext()) {
4520                    if (it.next().isPrivileged()) {
4521                        return true;
4522                    }
4523                }
4524            } else if (obj instanceof PackageSetting) {
4525                final PackageSetting ps = (PackageSetting) obj;
4526                return ps.isPrivileged();
4527            }
4528        }
4529        return false;
4530    }
4531
4532    @Override
4533    public String[] getAppOpPermissionPackages(String permissionName) {
4534        synchronized (mPackages) {
4535            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4536            if (pkgs == null) {
4537                return null;
4538            }
4539            return pkgs.toArray(new String[pkgs.size()]);
4540        }
4541    }
4542
4543    @Override
4544    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4545            int flags, int userId) {
4546        if (!sUserManager.exists(userId)) return null;
4547        flags = updateFlagsForResolve(flags, userId, intent);
4548        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4549        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4550        final ResolveInfo bestChoice =
4551                chooseBestActivity(intent, resolvedType, flags, query, userId);
4552
4553        if (isEphemeralAllowed(intent, query, userId)) {
4554            final EphemeralResolveInfo ai =
4555                    getEphemeralResolveInfo(intent, resolvedType, userId);
4556            if (ai != null) {
4557                if (DEBUG_EPHEMERAL) {
4558                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4559                }
4560                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4561                bestChoice.ephemeralResolveInfo = ai;
4562            }
4563        }
4564        return bestChoice;
4565    }
4566
4567    @Override
4568    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4569            IntentFilter filter, int match, ComponentName activity) {
4570        final int userId = UserHandle.getCallingUserId();
4571        if (DEBUG_PREFERRED) {
4572            Log.v(TAG, "setLastChosenActivity intent=" + intent
4573                + " resolvedType=" + resolvedType
4574                + " flags=" + flags
4575                + " filter=" + filter
4576                + " match=" + match
4577                + " activity=" + activity);
4578            filter.dump(new PrintStreamPrinter(System.out), "    ");
4579        }
4580        intent.setComponent(null);
4581        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4582        // Find any earlier preferred or last chosen entries and nuke them
4583        findPreferredActivity(intent, resolvedType,
4584                flags, query, 0, false, true, false, userId);
4585        // Add the new activity as the last chosen for this filter
4586        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4587                "Setting last chosen");
4588    }
4589
4590    @Override
4591    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4592        final int userId = UserHandle.getCallingUserId();
4593        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4594        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4595        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4596                false, false, false, userId);
4597    }
4598
4599
4600    private boolean isEphemeralAllowed(
4601            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4602        // Short circuit and return early if possible.
4603        if (DISABLE_EPHEMERAL_APPS) {
4604            return false;
4605        }
4606        final int callingUser = UserHandle.getCallingUserId();
4607        if (callingUser != UserHandle.USER_SYSTEM) {
4608            return false;
4609        }
4610        if (mEphemeralResolverConnection == null) {
4611            return false;
4612        }
4613        if (intent.getComponent() != null) {
4614            return false;
4615        }
4616        if (intent.getPackage() != null) {
4617            return false;
4618        }
4619        final boolean isWebUri = hasWebURI(intent);
4620        if (!isWebUri) {
4621            return false;
4622        }
4623        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4624        synchronized (mPackages) {
4625            final int count = resolvedActivites.size();
4626            for (int n = 0; n < count; n++) {
4627                ResolveInfo info = resolvedActivites.get(n);
4628                String packageName = info.activityInfo.packageName;
4629                PackageSetting ps = mSettings.mPackages.get(packageName);
4630                if (ps != null) {
4631                    // Try to get the status from User settings first
4632                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4633                    int status = (int) (packedStatus >> 32);
4634                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4635                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4636                        if (DEBUG_EPHEMERAL) {
4637                            Slog.v(TAG, "DENY ephemeral apps;"
4638                                + " pkg: " + packageName + ", status: " + status);
4639                        }
4640                        return false;
4641                    }
4642                }
4643            }
4644        }
4645        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4646        return true;
4647    }
4648
4649    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4650            int userId) {
4651        MessageDigest digest = null;
4652        try {
4653            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4654        } catch (NoSuchAlgorithmException e) {
4655            // If we can't create a digest, ignore ephemeral apps.
4656            return null;
4657        }
4658
4659        final byte[] hostBytes = intent.getData().getHost().getBytes();
4660        final byte[] digestBytes = digest.digest(hostBytes);
4661        int shaPrefix =
4662                digestBytes[0] << 24
4663                | digestBytes[1] << 16
4664                | digestBytes[2] << 8
4665                | digestBytes[3] << 0;
4666        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4667                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4668        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4669            // No hash prefix match; there are no ephemeral apps for this domain.
4670            return null;
4671        }
4672        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4673            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4674            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4675                continue;
4676            }
4677            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4678            // No filters; this should never happen.
4679            if (filters.isEmpty()) {
4680                continue;
4681            }
4682            // We have a domain match; resolve the filters to see if anything matches.
4683            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4684            for (int j = filters.size() - 1; j >= 0; --j) {
4685                final EphemeralResolveIntentInfo intentInfo =
4686                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4687                ephemeralResolver.addFilter(intentInfo);
4688            }
4689            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4690                    intent, resolvedType, false /*defaultOnly*/, userId);
4691            if (!matchedResolveInfoList.isEmpty()) {
4692                return matchedResolveInfoList.get(0);
4693            }
4694        }
4695        // Hash or filter mis-match; no ephemeral apps for this domain.
4696        return null;
4697    }
4698
4699    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4700            int flags, List<ResolveInfo> query, int userId) {
4701        if (query != null) {
4702            final int N = query.size();
4703            if (N == 1) {
4704                return query.get(0);
4705            } else if (N > 1) {
4706                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4707                // If there is more than one activity with the same priority,
4708                // then let the user decide between them.
4709                ResolveInfo r0 = query.get(0);
4710                ResolveInfo r1 = query.get(1);
4711                if (DEBUG_INTENT_MATCHING || debug) {
4712                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4713                            + r1.activityInfo.name + "=" + r1.priority);
4714                }
4715                // If the first activity has a higher priority, or a different
4716                // default, then it is always desirable to pick it.
4717                if (r0.priority != r1.priority
4718                        || r0.preferredOrder != r1.preferredOrder
4719                        || r0.isDefault != r1.isDefault) {
4720                    return query.get(0);
4721                }
4722                // If we have saved a preference for a preferred activity for
4723                // this Intent, use that.
4724                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4725                        flags, query, r0.priority, true, false, debug, userId);
4726                if (ri != null) {
4727                    return ri;
4728                }
4729                ri = new ResolveInfo(mResolveInfo);
4730                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4731                ri.activityInfo.applicationInfo = new ApplicationInfo(
4732                        ri.activityInfo.applicationInfo);
4733                if (userId != 0) {
4734                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4735                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4736                }
4737                // Make sure that the resolver is displayable in car mode
4738                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4739                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4740                return ri;
4741            }
4742        }
4743        return null;
4744    }
4745
4746    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4747            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4748        final int N = query.size();
4749        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4750                .get(userId);
4751        // Get the list of persistent preferred activities that handle the intent
4752        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4753        List<PersistentPreferredActivity> pprefs = ppir != null
4754                ? ppir.queryIntent(intent, resolvedType,
4755                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4756                : null;
4757        if (pprefs != null && pprefs.size() > 0) {
4758            final int M = pprefs.size();
4759            for (int i=0; i<M; i++) {
4760                final PersistentPreferredActivity ppa = pprefs.get(i);
4761                if (DEBUG_PREFERRED || debug) {
4762                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4763                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4764                            + "\n  component=" + ppa.mComponent);
4765                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4766                }
4767                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4768                        flags | MATCH_DISABLED_COMPONENTS, userId);
4769                if (DEBUG_PREFERRED || debug) {
4770                    Slog.v(TAG, "Found persistent preferred activity:");
4771                    if (ai != null) {
4772                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4773                    } else {
4774                        Slog.v(TAG, "  null");
4775                    }
4776                }
4777                if (ai == null) {
4778                    // This previously registered persistent preferred activity
4779                    // component is no longer known. Ignore it and do NOT remove it.
4780                    continue;
4781                }
4782                for (int j=0; j<N; j++) {
4783                    final ResolveInfo ri = query.get(j);
4784                    if (!ri.activityInfo.applicationInfo.packageName
4785                            .equals(ai.applicationInfo.packageName)) {
4786                        continue;
4787                    }
4788                    if (!ri.activityInfo.name.equals(ai.name)) {
4789                        continue;
4790                    }
4791                    //  Found a persistent preference that can handle the intent.
4792                    if (DEBUG_PREFERRED || debug) {
4793                        Slog.v(TAG, "Returning persistent preferred activity: " +
4794                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4795                    }
4796                    return ri;
4797                }
4798            }
4799        }
4800        return null;
4801    }
4802
4803    // TODO: handle preferred activities missing while user has amnesia
4804    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4805            List<ResolveInfo> query, int priority, boolean always,
4806            boolean removeMatches, boolean debug, int userId) {
4807        if (!sUserManager.exists(userId)) return null;
4808        flags = updateFlagsForResolve(flags, userId, intent);
4809        // writer
4810        synchronized (mPackages) {
4811            if (intent.getSelector() != null) {
4812                intent = intent.getSelector();
4813            }
4814            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4815
4816            // Try to find a matching persistent preferred activity.
4817            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4818                    debug, userId);
4819
4820            // If a persistent preferred activity matched, use it.
4821            if (pri != null) {
4822                return pri;
4823            }
4824
4825            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4826            // Get the list of preferred activities that handle the intent
4827            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4828            List<PreferredActivity> prefs = pir != null
4829                    ? pir.queryIntent(intent, resolvedType,
4830                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4831                    : null;
4832            if (prefs != null && prefs.size() > 0) {
4833                boolean changed = false;
4834                try {
4835                    // First figure out how good the original match set is.
4836                    // We will only allow preferred activities that came
4837                    // from the same match quality.
4838                    int match = 0;
4839
4840                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4841
4842                    final int N = query.size();
4843                    for (int j=0; j<N; j++) {
4844                        final ResolveInfo ri = query.get(j);
4845                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4846                                + ": 0x" + Integer.toHexString(match));
4847                        if (ri.match > match) {
4848                            match = ri.match;
4849                        }
4850                    }
4851
4852                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4853                            + Integer.toHexString(match));
4854
4855                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4856                    final int M = prefs.size();
4857                    for (int i=0; i<M; i++) {
4858                        final PreferredActivity pa = prefs.get(i);
4859                        if (DEBUG_PREFERRED || debug) {
4860                            Slog.v(TAG, "Checking PreferredActivity ds="
4861                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4862                                    + "\n  component=" + pa.mPref.mComponent);
4863                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4864                        }
4865                        if (pa.mPref.mMatch != match) {
4866                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4867                                    + Integer.toHexString(pa.mPref.mMatch));
4868                            continue;
4869                        }
4870                        // If it's not an "always" type preferred activity and that's what we're
4871                        // looking for, skip it.
4872                        if (always && !pa.mPref.mAlways) {
4873                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4874                            continue;
4875                        }
4876                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4877                                flags | MATCH_DISABLED_COMPONENTS, userId);
4878                        if (DEBUG_PREFERRED || debug) {
4879                            Slog.v(TAG, "Found preferred activity:");
4880                            if (ai != null) {
4881                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4882                            } else {
4883                                Slog.v(TAG, "  null");
4884                            }
4885                        }
4886                        if (ai == null) {
4887                            // This previously registered preferred activity
4888                            // component is no longer known.  Most likely an update
4889                            // to the app was installed and in the new version this
4890                            // component no longer exists.  Clean it up by removing
4891                            // it from the preferred activities list, and skip it.
4892                            Slog.w(TAG, "Removing dangling preferred activity: "
4893                                    + pa.mPref.mComponent);
4894                            pir.removeFilter(pa);
4895                            changed = true;
4896                            continue;
4897                        }
4898                        for (int j=0; j<N; j++) {
4899                            final ResolveInfo ri = query.get(j);
4900                            if (!ri.activityInfo.applicationInfo.packageName
4901                                    .equals(ai.applicationInfo.packageName)) {
4902                                continue;
4903                            }
4904                            if (!ri.activityInfo.name.equals(ai.name)) {
4905                                continue;
4906                            }
4907
4908                            if (removeMatches) {
4909                                pir.removeFilter(pa);
4910                                changed = true;
4911                                if (DEBUG_PREFERRED) {
4912                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4913                                }
4914                                break;
4915                            }
4916
4917                            // Okay we found a previously set preferred or last chosen app.
4918                            // If the result set is different from when this
4919                            // was created, we need to clear it and re-ask the
4920                            // user their preference, if we're looking for an "always" type entry.
4921                            if (always && !pa.mPref.sameSet(query)) {
4922                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4923                                        + intent + " type " + resolvedType);
4924                                if (DEBUG_PREFERRED) {
4925                                    Slog.v(TAG, "Removing preferred activity since set changed "
4926                                            + pa.mPref.mComponent);
4927                                }
4928                                pir.removeFilter(pa);
4929                                // Re-add the filter as a "last chosen" entry (!always)
4930                                PreferredActivity lastChosen = new PreferredActivity(
4931                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4932                                pir.addFilter(lastChosen);
4933                                changed = true;
4934                                return null;
4935                            }
4936
4937                            // Yay! Either the set matched or we're looking for the last chosen
4938                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4939                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4940                            return ri;
4941                        }
4942                    }
4943                } finally {
4944                    if (changed) {
4945                        if (DEBUG_PREFERRED) {
4946                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4947                        }
4948                        scheduleWritePackageRestrictionsLocked(userId);
4949                    }
4950                }
4951            }
4952        }
4953        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4954        return null;
4955    }
4956
4957    /*
4958     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4959     */
4960    @Override
4961    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4962            int targetUserId) {
4963        mContext.enforceCallingOrSelfPermission(
4964                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4965        List<CrossProfileIntentFilter> matches =
4966                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4967        if (matches != null) {
4968            int size = matches.size();
4969            for (int i = 0; i < size; i++) {
4970                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4971            }
4972        }
4973        if (hasWebURI(intent)) {
4974            // cross-profile app linking works only towards the parent.
4975            final UserInfo parent = getProfileParent(sourceUserId);
4976            synchronized(mPackages) {
4977                int flags = updateFlagsForResolve(0, parent.id, intent);
4978                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4979                        intent, resolvedType, flags, sourceUserId, parent.id);
4980                return xpDomainInfo != null;
4981            }
4982        }
4983        return false;
4984    }
4985
4986    private UserInfo getProfileParent(int userId) {
4987        final long identity = Binder.clearCallingIdentity();
4988        try {
4989            return sUserManager.getProfileParent(userId);
4990        } finally {
4991            Binder.restoreCallingIdentity(identity);
4992        }
4993    }
4994
4995    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4996            String resolvedType, int userId) {
4997        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4998        if (resolver != null) {
4999            return resolver.queryIntent(intent, resolvedType, false, userId);
5000        }
5001        return null;
5002    }
5003
5004    @Override
5005    public List<ResolveInfo> queryIntentActivities(Intent intent,
5006            String resolvedType, int flags, int userId) {
5007        if (!sUserManager.exists(userId)) return Collections.emptyList();
5008        flags = updateFlagsForResolve(flags, userId, intent);
5009        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
5010        ComponentName comp = intent.getComponent();
5011        if (comp == null) {
5012            if (intent.getSelector() != null) {
5013                intent = intent.getSelector();
5014                comp = intent.getComponent();
5015            }
5016        }
5017
5018        if (comp != null) {
5019            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5020            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5021            if (ai != null) {
5022                final ResolveInfo ri = new ResolveInfo();
5023                ri.activityInfo = ai;
5024                list.add(ri);
5025            }
5026            return list;
5027        }
5028
5029        // reader
5030        synchronized (mPackages) {
5031            final String pkgName = intent.getPackage();
5032            if (pkgName == null) {
5033                List<CrossProfileIntentFilter> matchingFilters =
5034                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5035                // Check for results that need to skip the current profile.
5036                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5037                        resolvedType, flags, userId);
5038                if (xpResolveInfo != null) {
5039                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5040                    result.add(xpResolveInfo);
5041                    return filterIfNotSystemUser(result, userId);
5042                }
5043
5044                // Check for results in the current profile.
5045                List<ResolveInfo> result = mActivities.queryIntent(
5046                        intent, resolvedType, flags, userId);
5047                result = filterIfNotSystemUser(result, userId);
5048
5049                // Check for cross profile results.
5050                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5051                xpResolveInfo = queryCrossProfileIntents(
5052                        matchingFilters, intent, resolvedType, flags, userId,
5053                        hasNonNegativePriorityResult);
5054                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5055                    boolean isVisibleToUser = filterIfNotSystemUser(
5056                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5057                    if (isVisibleToUser) {
5058                        result.add(xpResolveInfo);
5059                        Collections.sort(result, mResolvePrioritySorter);
5060                    }
5061                }
5062                if (hasWebURI(intent)) {
5063                    CrossProfileDomainInfo xpDomainInfo = null;
5064                    final UserInfo parent = getProfileParent(userId);
5065                    if (parent != null) {
5066                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5067                                flags, userId, parent.id);
5068                    }
5069                    if (xpDomainInfo != null) {
5070                        if (xpResolveInfo != null) {
5071                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5072                            // in the result.
5073                            result.remove(xpResolveInfo);
5074                        }
5075                        if (result.size() == 0) {
5076                            result.add(xpDomainInfo.resolveInfo);
5077                            return result;
5078                        }
5079                    } else if (result.size() <= 1) {
5080                        return result;
5081                    }
5082                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5083                            xpDomainInfo, userId);
5084                    Collections.sort(result, mResolvePrioritySorter);
5085                }
5086                return result;
5087            }
5088            final PackageParser.Package pkg = mPackages.get(pkgName);
5089            if (pkg != null) {
5090                return filterIfNotSystemUser(
5091                        mActivities.queryIntentForPackage(
5092                                intent, resolvedType, flags, pkg.activities, userId),
5093                        userId);
5094            }
5095            return new ArrayList<ResolveInfo>();
5096        }
5097    }
5098
5099    private static class CrossProfileDomainInfo {
5100        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5101        ResolveInfo resolveInfo;
5102        /* Best domain verification status of the activities found in the other profile */
5103        int bestDomainVerificationStatus;
5104    }
5105
5106    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5107            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5108        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5109                sourceUserId)) {
5110            return null;
5111        }
5112        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5113                resolvedType, flags, parentUserId);
5114
5115        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5116            return null;
5117        }
5118        CrossProfileDomainInfo result = null;
5119        int size = resultTargetUser.size();
5120        for (int i = 0; i < size; i++) {
5121            ResolveInfo riTargetUser = resultTargetUser.get(i);
5122            // Intent filter verification is only for filters that specify a host. So don't return
5123            // those that handle all web uris.
5124            if (riTargetUser.handleAllWebDataURI) {
5125                continue;
5126            }
5127            String packageName = riTargetUser.activityInfo.packageName;
5128            PackageSetting ps = mSettings.mPackages.get(packageName);
5129            if (ps == null) {
5130                continue;
5131            }
5132            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5133            int status = (int)(verificationState >> 32);
5134            if (result == null) {
5135                result = new CrossProfileDomainInfo();
5136                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5137                        sourceUserId, parentUserId);
5138                result.bestDomainVerificationStatus = status;
5139            } else {
5140                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5141                        result.bestDomainVerificationStatus);
5142            }
5143        }
5144        // Don't consider matches with status NEVER across profiles.
5145        if (result != null && result.bestDomainVerificationStatus
5146                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5147            return null;
5148        }
5149        return result;
5150    }
5151
5152    /**
5153     * Verification statuses are ordered from the worse to the best, except for
5154     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5155     */
5156    private int bestDomainVerificationStatus(int status1, int status2) {
5157        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5158            return status2;
5159        }
5160        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5161            return status1;
5162        }
5163        return (int) MathUtils.max(status1, status2);
5164    }
5165
5166    private boolean isUserEnabled(int userId) {
5167        long callingId = Binder.clearCallingIdentity();
5168        try {
5169            UserInfo userInfo = sUserManager.getUserInfo(userId);
5170            return userInfo != null && userInfo.isEnabled();
5171        } finally {
5172            Binder.restoreCallingIdentity(callingId);
5173        }
5174    }
5175
5176    /**
5177     * Filter out activities with systemUserOnly flag set, when current user is not System.
5178     *
5179     * @return filtered list
5180     */
5181    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5182        if (userId == UserHandle.USER_SYSTEM) {
5183            return resolveInfos;
5184        }
5185        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5186            ResolveInfo info = resolveInfos.get(i);
5187            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5188                resolveInfos.remove(i);
5189            }
5190        }
5191        return resolveInfos;
5192    }
5193
5194    /**
5195     * @param resolveInfos list of resolve infos in descending priority order
5196     * @return if the list contains a resolve info with non-negative priority
5197     */
5198    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5199        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5200    }
5201
5202    private static boolean hasWebURI(Intent intent) {
5203        if (intent.getData() == null) {
5204            return false;
5205        }
5206        final String scheme = intent.getScheme();
5207        if (TextUtils.isEmpty(scheme)) {
5208            return false;
5209        }
5210        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5211    }
5212
5213    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5214            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5215            int userId) {
5216        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5217
5218        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5219            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5220                    candidates.size());
5221        }
5222
5223        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5224        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5225        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5226        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5227        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5228        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5229
5230        synchronized (mPackages) {
5231            final int count = candidates.size();
5232            // First, try to use linked apps. Partition the candidates into four lists:
5233            // one for the final results, one for the "do not use ever", one for "undefined status"
5234            // and finally one for "browser app type".
5235            for (int n=0; n<count; n++) {
5236                ResolveInfo info = candidates.get(n);
5237                String packageName = info.activityInfo.packageName;
5238                PackageSetting ps = mSettings.mPackages.get(packageName);
5239                if (ps != null) {
5240                    // Add to the special match all list (Browser use case)
5241                    if (info.handleAllWebDataURI) {
5242                        matchAllList.add(info);
5243                        continue;
5244                    }
5245                    // Try to get the status from User settings first
5246                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5247                    int status = (int)(packedStatus >> 32);
5248                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5249                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5250                        if (DEBUG_DOMAIN_VERIFICATION) {
5251                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5252                                    + " : linkgen=" + linkGeneration);
5253                        }
5254                        // Use link-enabled generation as preferredOrder, i.e.
5255                        // prefer newly-enabled over earlier-enabled.
5256                        info.preferredOrder = linkGeneration;
5257                        alwaysList.add(info);
5258                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5259                        if (DEBUG_DOMAIN_VERIFICATION) {
5260                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5261                        }
5262                        neverList.add(info);
5263                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5264                        if (DEBUG_DOMAIN_VERIFICATION) {
5265                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5266                        }
5267                        alwaysAskList.add(info);
5268                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5269                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5270                        if (DEBUG_DOMAIN_VERIFICATION) {
5271                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5272                        }
5273                        undefinedList.add(info);
5274                    }
5275                }
5276            }
5277
5278            // We'll want to include browser possibilities in a few cases
5279            boolean includeBrowser = false;
5280
5281            // First try to add the "always" resolution(s) for the current user, if any
5282            if (alwaysList.size() > 0) {
5283                result.addAll(alwaysList);
5284            } else {
5285                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5286                result.addAll(undefinedList);
5287                // Maybe add one for the other profile.
5288                if (xpDomainInfo != null && (
5289                        xpDomainInfo.bestDomainVerificationStatus
5290                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5291                    result.add(xpDomainInfo.resolveInfo);
5292                }
5293                includeBrowser = true;
5294            }
5295
5296            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5297            // If there were 'always' entries their preferred order has been set, so we also
5298            // back that off to make the alternatives equivalent
5299            if (alwaysAskList.size() > 0) {
5300                for (ResolveInfo i : result) {
5301                    i.preferredOrder = 0;
5302                }
5303                result.addAll(alwaysAskList);
5304                includeBrowser = true;
5305            }
5306
5307            if (includeBrowser) {
5308                // Also add browsers (all of them or only the default one)
5309                if (DEBUG_DOMAIN_VERIFICATION) {
5310                    Slog.v(TAG, "   ...including browsers in candidate set");
5311                }
5312                if ((matchFlags & MATCH_ALL) != 0) {
5313                    result.addAll(matchAllList);
5314                } else {
5315                    // Browser/generic handling case.  If there's a default browser, go straight
5316                    // to that (but only if there is no other higher-priority match).
5317                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5318                    int maxMatchPrio = 0;
5319                    ResolveInfo defaultBrowserMatch = null;
5320                    final int numCandidates = matchAllList.size();
5321                    for (int n = 0; n < numCandidates; n++) {
5322                        ResolveInfo info = matchAllList.get(n);
5323                        // track the highest overall match priority...
5324                        if (info.priority > maxMatchPrio) {
5325                            maxMatchPrio = info.priority;
5326                        }
5327                        // ...and the highest-priority default browser match
5328                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5329                            if (defaultBrowserMatch == null
5330                                    || (defaultBrowserMatch.priority < info.priority)) {
5331                                if (debug) {
5332                                    Slog.v(TAG, "Considering default browser match " + info);
5333                                }
5334                                defaultBrowserMatch = info;
5335                            }
5336                        }
5337                    }
5338                    if (defaultBrowserMatch != null
5339                            && defaultBrowserMatch.priority >= maxMatchPrio
5340                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5341                    {
5342                        if (debug) {
5343                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5344                        }
5345                        result.add(defaultBrowserMatch);
5346                    } else {
5347                        result.addAll(matchAllList);
5348                    }
5349                }
5350
5351                // If there is nothing selected, add all candidates and remove the ones that the user
5352                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5353                if (result.size() == 0) {
5354                    result.addAll(candidates);
5355                    result.removeAll(neverList);
5356                }
5357            }
5358        }
5359        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5360            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5361                    result.size());
5362            for (ResolveInfo info : result) {
5363                Slog.v(TAG, "  + " + info.activityInfo);
5364            }
5365        }
5366        return result;
5367    }
5368
5369    // Returns a packed value as a long:
5370    //
5371    // high 'int'-sized word: link status: undefined/ask/never/always.
5372    // low 'int'-sized word: relative priority among 'always' results.
5373    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5374        long result = ps.getDomainVerificationStatusForUser(userId);
5375        // if none available, get the master status
5376        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5377            if (ps.getIntentFilterVerificationInfo() != null) {
5378                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5379            }
5380        }
5381        return result;
5382    }
5383
5384    private ResolveInfo querySkipCurrentProfileIntents(
5385            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5386            int flags, int sourceUserId) {
5387        if (matchingFilters != null) {
5388            int size = matchingFilters.size();
5389            for (int i = 0; i < size; i ++) {
5390                CrossProfileIntentFilter filter = matchingFilters.get(i);
5391                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5392                    // Checking if there are activities in the target user that can handle the
5393                    // intent.
5394                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5395                            resolvedType, flags, sourceUserId);
5396                    if (resolveInfo != null) {
5397                        return resolveInfo;
5398                    }
5399                }
5400            }
5401        }
5402        return null;
5403    }
5404
5405    // Return matching ResolveInfo in target user if any.
5406    private ResolveInfo queryCrossProfileIntents(
5407            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5408            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5409        if (matchingFilters != null) {
5410            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5411            // match the same intent. For performance reasons, it is better not to
5412            // run queryIntent twice for the same userId
5413            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5414            int size = matchingFilters.size();
5415            for (int i = 0; i < size; i++) {
5416                CrossProfileIntentFilter filter = matchingFilters.get(i);
5417                int targetUserId = filter.getTargetUserId();
5418                boolean skipCurrentProfile =
5419                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5420                boolean skipCurrentProfileIfNoMatchFound =
5421                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5422                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5423                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5424                    // Checking if there are activities in the target user that can handle the
5425                    // intent.
5426                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5427                            resolvedType, flags, sourceUserId);
5428                    if (resolveInfo != null) return resolveInfo;
5429                    alreadyTriedUserIds.put(targetUserId, true);
5430                }
5431            }
5432        }
5433        return null;
5434    }
5435
5436    /**
5437     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5438     * will forward the intent to the filter's target user.
5439     * Otherwise, returns null.
5440     */
5441    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5442            String resolvedType, int flags, int sourceUserId) {
5443        int targetUserId = filter.getTargetUserId();
5444        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5445                resolvedType, flags, targetUserId);
5446        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5447            // If all the matches in the target profile are suspended, return null.
5448            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5449                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5450                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5451                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5452                            targetUserId);
5453                }
5454            }
5455        }
5456        return null;
5457    }
5458
5459    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5460            int sourceUserId, int targetUserId) {
5461        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5462        long ident = Binder.clearCallingIdentity();
5463        boolean targetIsProfile;
5464        try {
5465            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5466        } finally {
5467            Binder.restoreCallingIdentity(ident);
5468        }
5469        String className;
5470        if (targetIsProfile) {
5471            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5472        } else {
5473            className = FORWARD_INTENT_TO_PARENT;
5474        }
5475        ComponentName forwardingActivityComponentName = new ComponentName(
5476                mAndroidApplication.packageName, className);
5477        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5478                sourceUserId);
5479        if (!targetIsProfile) {
5480            forwardingActivityInfo.showUserIcon = targetUserId;
5481            forwardingResolveInfo.noResourceId = true;
5482        }
5483        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5484        forwardingResolveInfo.priority = 0;
5485        forwardingResolveInfo.preferredOrder = 0;
5486        forwardingResolveInfo.match = 0;
5487        forwardingResolveInfo.isDefault = true;
5488        forwardingResolveInfo.filter = filter;
5489        forwardingResolveInfo.targetUserId = targetUserId;
5490        return forwardingResolveInfo;
5491    }
5492
5493    @Override
5494    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5495            Intent[] specifics, String[] specificTypes, Intent intent,
5496            String resolvedType, int flags, int userId) {
5497        if (!sUserManager.exists(userId)) return Collections.emptyList();
5498        flags = updateFlagsForResolve(flags, userId, intent);
5499        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5500                false, "query intent activity options");
5501        final String resultsAction = intent.getAction();
5502
5503        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5504                | PackageManager.GET_RESOLVED_FILTER, userId);
5505
5506        if (DEBUG_INTENT_MATCHING) {
5507            Log.v(TAG, "Query " + intent + ": " + results);
5508        }
5509
5510        int specificsPos = 0;
5511        int N;
5512
5513        // todo: note that the algorithm used here is O(N^2).  This
5514        // isn't a problem in our current environment, but if we start running
5515        // into situations where we have more than 5 or 10 matches then this
5516        // should probably be changed to something smarter...
5517
5518        // First we go through and resolve each of the specific items
5519        // that were supplied, taking care of removing any corresponding
5520        // duplicate items in the generic resolve list.
5521        if (specifics != null) {
5522            for (int i=0; i<specifics.length; i++) {
5523                final Intent sintent = specifics[i];
5524                if (sintent == null) {
5525                    continue;
5526                }
5527
5528                if (DEBUG_INTENT_MATCHING) {
5529                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5530                }
5531
5532                String action = sintent.getAction();
5533                if (resultsAction != null && resultsAction.equals(action)) {
5534                    // If this action was explicitly requested, then don't
5535                    // remove things that have it.
5536                    action = null;
5537                }
5538
5539                ResolveInfo ri = null;
5540                ActivityInfo ai = null;
5541
5542                ComponentName comp = sintent.getComponent();
5543                if (comp == null) {
5544                    ri = resolveIntent(
5545                        sintent,
5546                        specificTypes != null ? specificTypes[i] : null,
5547                            flags, userId);
5548                    if (ri == null) {
5549                        continue;
5550                    }
5551                    if (ri == mResolveInfo) {
5552                        // ACK!  Must do something better with this.
5553                    }
5554                    ai = ri.activityInfo;
5555                    comp = new ComponentName(ai.applicationInfo.packageName,
5556                            ai.name);
5557                } else {
5558                    ai = getActivityInfo(comp, flags, userId);
5559                    if (ai == null) {
5560                        continue;
5561                    }
5562                }
5563
5564                // Look for any generic query activities that are duplicates
5565                // of this specific one, and remove them from the results.
5566                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5567                N = results.size();
5568                int j;
5569                for (j=specificsPos; j<N; j++) {
5570                    ResolveInfo sri = results.get(j);
5571                    if ((sri.activityInfo.name.equals(comp.getClassName())
5572                            && sri.activityInfo.applicationInfo.packageName.equals(
5573                                    comp.getPackageName()))
5574                        || (action != null && sri.filter.matchAction(action))) {
5575                        results.remove(j);
5576                        if (DEBUG_INTENT_MATCHING) Log.v(
5577                            TAG, "Removing duplicate item from " + j
5578                            + " due to specific " + specificsPos);
5579                        if (ri == null) {
5580                            ri = sri;
5581                        }
5582                        j--;
5583                        N--;
5584                    }
5585                }
5586
5587                // Add this specific item to its proper place.
5588                if (ri == null) {
5589                    ri = new ResolveInfo();
5590                    ri.activityInfo = ai;
5591                }
5592                results.add(specificsPos, ri);
5593                ri.specificIndex = i;
5594                specificsPos++;
5595            }
5596        }
5597
5598        // Now we go through the remaining generic results and remove any
5599        // duplicate actions that are found here.
5600        N = results.size();
5601        for (int i=specificsPos; i<N-1; i++) {
5602            final ResolveInfo rii = results.get(i);
5603            if (rii.filter == null) {
5604                continue;
5605            }
5606
5607            // Iterate over all of the actions of this result's intent
5608            // filter...  typically this should be just one.
5609            final Iterator<String> it = rii.filter.actionsIterator();
5610            if (it == null) {
5611                continue;
5612            }
5613            while (it.hasNext()) {
5614                final String action = it.next();
5615                if (resultsAction != null && resultsAction.equals(action)) {
5616                    // If this action was explicitly requested, then don't
5617                    // remove things that have it.
5618                    continue;
5619                }
5620                for (int j=i+1; j<N; j++) {
5621                    final ResolveInfo rij = results.get(j);
5622                    if (rij.filter != null && rij.filter.hasAction(action)) {
5623                        results.remove(j);
5624                        if (DEBUG_INTENT_MATCHING) Log.v(
5625                            TAG, "Removing duplicate item from " + j
5626                            + " due to action " + action + " at " + i);
5627                        j--;
5628                        N--;
5629                    }
5630                }
5631            }
5632
5633            // If the caller didn't request filter information, drop it now
5634            // so we don't have to marshall/unmarshall it.
5635            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5636                rii.filter = null;
5637            }
5638        }
5639
5640        // Filter out the caller activity if so requested.
5641        if (caller != null) {
5642            N = results.size();
5643            for (int i=0; i<N; i++) {
5644                ActivityInfo ainfo = results.get(i).activityInfo;
5645                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5646                        && caller.getClassName().equals(ainfo.name)) {
5647                    results.remove(i);
5648                    break;
5649                }
5650            }
5651        }
5652
5653        // If the caller didn't request filter information,
5654        // drop them now so we don't have to
5655        // marshall/unmarshall it.
5656        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5657            N = results.size();
5658            for (int i=0; i<N; i++) {
5659                results.get(i).filter = null;
5660            }
5661        }
5662
5663        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5664        return results;
5665    }
5666
5667    @Override
5668    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5669            int userId) {
5670        if (!sUserManager.exists(userId)) return Collections.emptyList();
5671        flags = updateFlagsForResolve(flags, userId, intent);
5672        ComponentName comp = intent.getComponent();
5673        if (comp == null) {
5674            if (intent.getSelector() != null) {
5675                intent = intent.getSelector();
5676                comp = intent.getComponent();
5677            }
5678        }
5679        if (comp != null) {
5680            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5681            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5682            if (ai != null) {
5683                ResolveInfo ri = new ResolveInfo();
5684                ri.activityInfo = ai;
5685                list.add(ri);
5686            }
5687            return list;
5688        }
5689
5690        // reader
5691        synchronized (mPackages) {
5692            String pkgName = intent.getPackage();
5693            if (pkgName == null) {
5694                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5695            }
5696            final PackageParser.Package pkg = mPackages.get(pkgName);
5697            if (pkg != null) {
5698                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5699                        userId);
5700            }
5701            return null;
5702        }
5703    }
5704
5705    @Override
5706    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5707        if (!sUserManager.exists(userId)) return null;
5708        flags = updateFlagsForResolve(flags, userId, intent);
5709        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5710        if (query != null) {
5711            if (query.size() >= 1) {
5712                // If there is more than one service with the same priority,
5713                // just arbitrarily pick the first one.
5714                return query.get(0);
5715            }
5716        }
5717        return null;
5718    }
5719
5720    @Override
5721    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5722            int userId) {
5723        if (!sUserManager.exists(userId)) return Collections.emptyList();
5724        flags = updateFlagsForResolve(flags, userId, intent);
5725        ComponentName comp = intent.getComponent();
5726        if (comp == null) {
5727            if (intent.getSelector() != null) {
5728                intent = intent.getSelector();
5729                comp = intent.getComponent();
5730            }
5731        }
5732        if (comp != null) {
5733            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5734            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5735            if (si != null) {
5736                final ResolveInfo ri = new ResolveInfo();
5737                ri.serviceInfo = si;
5738                list.add(ri);
5739            }
5740            return list;
5741        }
5742
5743        // reader
5744        synchronized (mPackages) {
5745            String pkgName = intent.getPackage();
5746            if (pkgName == null) {
5747                return mServices.queryIntent(intent, resolvedType, flags, userId);
5748            }
5749            final PackageParser.Package pkg = mPackages.get(pkgName);
5750            if (pkg != null) {
5751                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5752                        userId);
5753            }
5754            return null;
5755        }
5756    }
5757
5758    @Override
5759    public List<ResolveInfo> queryIntentContentProviders(
5760            Intent intent, String resolvedType, int flags, int userId) {
5761        if (!sUserManager.exists(userId)) return Collections.emptyList();
5762        flags = updateFlagsForResolve(flags, userId, intent);
5763        ComponentName comp = intent.getComponent();
5764        if (comp == null) {
5765            if (intent.getSelector() != null) {
5766                intent = intent.getSelector();
5767                comp = intent.getComponent();
5768            }
5769        }
5770        if (comp != null) {
5771            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5772            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5773            if (pi != null) {
5774                final ResolveInfo ri = new ResolveInfo();
5775                ri.providerInfo = pi;
5776                list.add(ri);
5777            }
5778            return list;
5779        }
5780
5781        // reader
5782        synchronized (mPackages) {
5783            String pkgName = intent.getPackage();
5784            if (pkgName == null) {
5785                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5786            }
5787            final PackageParser.Package pkg = mPackages.get(pkgName);
5788            if (pkg != null) {
5789                return mProviders.queryIntentForPackage(
5790                        intent, resolvedType, flags, pkg.providers, userId);
5791            }
5792            return null;
5793        }
5794    }
5795
5796    @Override
5797    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5798        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5799        flags = updateFlagsForPackage(flags, userId, null);
5800        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5801        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5802
5803        // writer
5804        synchronized (mPackages) {
5805            ArrayList<PackageInfo> list;
5806            if (listUninstalled) {
5807                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5808                for (PackageSetting ps : mSettings.mPackages.values()) {
5809                    PackageInfo pi;
5810                    if (ps.pkg != null) {
5811                        pi = generatePackageInfo(ps.pkg, flags, userId);
5812                    } else {
5813                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5814                    }
5815                    if (pi != null) {
5816                        list.add(pi);
5817                    }
5818                }
5819            } else {
5820                list = new ArrayList<PackageInfo>(mPackages.size());
5821                for (PackageParser.Package p : mPackages.values()) {
5822                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5823                    if (pi != null) {
5824                        list.add(pi);
5825                    }
5826                }
5827            }
5828
5829            return new ParceledListSlice<PackageInfo>(list);
5830        }
5831    }
5832
5833    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5834            String[] permissions, boolean[] tmp, int flags, int userId) {
5835        int numMatch = 0;
5836        final PermissionsState permissionsState = ps.getPermissionsState();
5837        for (int i=0; i<permissions.length; i++) {
5838            final String permission = permissions[i];
5839            if (permissionsState.hasPermission(permission, userId)) {
5840                tmp[i] = true;
5841                numMatch++;
5842            } else {
5843                tmp[i] = false;
5844            }
5845        }
5846        if (numMatch == 0) {
5847            return;
5848        }
5849        PackageInfo pi;
5850        if (ps.pkg != null) {
5851            pi = generatePackageInfo(ps.pkg, flags, userId);
5852        } else {
5853            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5854        }
5855        // The above might return null in cases of uninstalled apps or install-state
5856        // skew across users/profiles.
5857        if (pi != null) {
5858            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5859                if (numMatch == permissions.length) {
5860                    pi.requestedPermissions = permissions;
5861                } else {
5862                    pi.requestedPermissions = new String[numMatch];
5863                    numMatch = 0;
5864                    for (int i=0; i<permissions.length; i++) {
5865                        if (tmp[i]) {
5866                            pi.requestedPermissions[numMatch] = permissions[i];
5867                            numMatch++;
5868                        }
5869                    }
5870                }
5871            }
5872            list.add(pi);
5873        }
5874    }
5875
5876    @Override
5877    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5878            String[] permissions, int flags, int userId) {
5879        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5880        flags = updateFlagsForPackage(flags, userId, permissions);
5881        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5882
5883        // writer
5884        synchronized (mPackages) {
5885            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5886            boolean[] tmpBools = new boolean[permissions.length];
5887            if (listUninstalled) {
5888                for (PackageSetting ps : mSettings.mPackages.values()) {
5889                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5890                }
5891            } else {
5892                for (PackageParser.Package pkg : mPackages.values()) {
5893                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5894                    if (ps != null) {
5895                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5896                                userId);
5897                    }
5898                }
5899            }
5900
5901            return new ParceledListSlice<PackageInfo>(list);
5902        }
5903    }
5904
5905    @Override
5906    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5907        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5908        flags = updateFlagsForApplication(flags, userId, null);
5909        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5910
5911        // writer
5912        synchronized (mPackages) {
5913            ArrayList<ApplicationInfo> list;
5914            if (listUninstalled) {
5915                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5916                for (PackageSetting ps : mSettings.mPackages.values()) {
5917                    ApplicationInfo ai;
5918                    if (ps.pkg != null) {
5919                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5920                                ps.readUserState(userId), userId);
5921                    } else {
5922                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5923                    }
5924                    if (ai != null) {
5925                        list.add(ai);
5926                    }
5927                }
5928            } else {
5929                list = new ArrayList<ApplicationInfo>(mPackages.size());
5930                for (PackageParser.Package p : mPackages.values()) {
5931                    if (p.mExtras != null) {
5932                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5933                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5934                        if (ai != null) {
5935                            list.add(ai);
5936                        }
5937                    }
5938                }
5939            }
5940
5941            return new ParceledListSlice<ApplicationInfo>(list);
5942        }
5943    }
5944
5945    @Override
5946    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5947        if (DISABLE_EPHEMERAL_APPS) {
5948            return null;
5949        }
5950
5951        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5952                "getEphemeralApplications");
5953        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5954                "getEphemeralApplications");
5955        synchronized (mPackages) {
5956            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5957                    .getEphemeralApplicationsLPw(userId);
5958            if (ephemeralApps != null) {
5959                return new ParceledListSlice<>(ephemeralApps);
5960            }
5961        }
5962        return null;
5963    }
5964
5965    @Override
5966    public boolean isEphemeralApplication(String packageName, int userId) {
5967        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5968                "isEphemeral");
5969        if (DISABLE_EPHEMERAL_APPS) {
5970            return false;
5971        }
5972
5973        if (!isCallerSameApp(packageName)) {
5974            return false;
5975        }
5976        synchronized (mPackages) {
5977            PackageParser.Package pkg = mPackages.get(packageName);
5978            if (pkg != null) {
5979                return pkg.applicationInfo.isEphemeralApp();
5980            }
5981        }
5982        return false;
5983    }
5984
5985    @Override
5986    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5987        if (DISABLE_EPHEMERAL_APPS) {
5988            return null;
5989        }
5990
5991        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5992                "getCookie");
5993        if (!isCallerSameApp(packageName)) {
5994            return null;
5995        }
5996        synchronized (mPackages) {
5997            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5998                    packageName, userId);
5999        }
6000    }
6001
6002    @Override
6003    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6004        if (DISABLE_EPHEMERAL_APPS) {
6005            return true;
6006        }
6007
6008        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6009                "setCookie");
6010        if (!isCallerSameApp(packageName)) {
6011            return false;
6012        }
6013        synchronized (mPackages) {
6014            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6015                    packageName, cookie, userId);
6016        }
6017    }
6018
6019    @Override
6020    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6021        if (DISABLE_EPHEMERAL_APPS) {
6022            return null;
6023        }
6024
6025        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6026                "getEphemeralApplicationIcon");
6027        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6028                "getEphemeralApplicationIcon");
6029        synchronized (mPackages) {
6030            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6031                    packageName, userId);
6032        }
6033    }
6034
6035    private boolean isCallerSameApp(String packageName) {
6036        PackageParser.Package pkg = mPackages.get(packageName);
6037        return pkg != null
6038                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6039    }
6040
6041    public List<ApplicationInfo> getPersistentApplications(int flags) {
6042        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6043
6044        // reader
6045        synchronized (mPackages) {
6046            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6047            final int userId = UserHandle.getCallingUserId();
6048            while (i.hasNext()) {
6049                final PackageParser.Package p = i.next();
6050                if (p.applicationInfo != null
6051                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6052                        && (!mSafeMode || isSystemApp(p))) {
6053                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6054                    if (ps != null) {
6055                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6056                                ps.readUserState(userId), userId);
6057                        if (ai != null) {
6058                            finalList.add(ai);
6059                        }
6060                    }
6061                }
6062            }
6063        }
6064
6065        return finalList;
6066    }
6067
6068    @Override
6069    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6070        if (!sUserManager.exists(userId)) return null;
6071        flags = updateFlagsForComponent(flags, userId, name);
6072        // reader
6073        synchronized (mPackages) {
6074            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6075            PackageSetting ps = provider != null
6076                    ? mSettings.mPackages.get(provider.owner.packageName)
6077                    : null;
6078            return ps != null
6079                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6080                    ? PackageParser.generateProviderInfo(provider, flags,
6081                            ps.readUserState(userId), userId)
6082                    : null;
6083        }
6084    }
6085
6086    /**
6087     * @deprecated
6088     */
6089    @Deprecated
6090    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6091        // reader
6092        synchronized (mPackages) {
6093            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6094                    .entrySet().iterator();
6095            final int userId = UserHandle.getCallingUserId();
6096            while (i.hasNext()) {
6097                Map.Entry<String, PackageParser.Provider> entry = i.next();
6098                PackageParser.Provider p = entry.getValue();
6099                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6100
6101                if (ps != null && p.syncable
6102                        && (!mSafeMode || (p.info.applicationInfo.flags
6103                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6104                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6105                            ps.readUserState(userId), userId);
6106                    if (info != null) {
6107                        outNames.add(entry.getKey());
6108                        outInfo.add(info);
6109                    }
6110                }
6111            }
6112        }
6113    }
6114
6115    @Override
6116    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6117            int uid, int flags) {
6118        final int userId = processName != null ? UserHandle.getUserId(uid)
6119                : UserHandle.getCallingUserId();
6120        if (!sUserManager.exists(userId)) return null;
6121        flags = updateFlagsForComponent(flags, userId, processName);
6122
6123        ArrayList<ProviderInfo> finalList = null;
6124        // reader
6125        synchronized (mPackages) {
6126            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6127            while (i.hasNext()) {
6128                final PackageParser.Provider p = i.next();
6129                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6130                if (ps != null && p.info.authority != null
6131                        && (processName == null
6132                                || (p.info.processName.equals(processName)
6133                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6134                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6135                    if (finalList == null) {
6136                        finalList = new ArrayList<ProviderInfo>(3);
6137                    }
6138                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6139                            ps.readUserState(userId), userId);
6140                    if (info != null) {
6141                        finalList.add(info);
6142                    }
6143                }
6144            }
6145        }
6146
6147        if (finalList != null) {
6148            Collections.sort(finalList, mProviderInitOrderSorter);
6149            return new ParceledListSlice<ProviderInfo>(finalList);
6150        }
6151
6152        return null;
6153    }
6154
6155    @Override
6156    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6157        // reader
6158        synchronized (mPackages) {
6159            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6160            return PackageParser.generateInstrumentationInfo(i, flags);
6161        }
6162    }
6163
6164    @Override
6165    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6166            int flags) {
6167        ArrayList<InstrumentationInfo> finalList =
6168            new ArrayList<InstrumentationInfo>();
6169
6170        // reader
6171        synchronized (mPackages) {
6172            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6173            while (i.hasNext()) {
6174                final PackageParser.Instrumentation p = i.next();
6175                if (targetPackage == null
6176                        || targetPackage.equals(p.info.targetPackage)) {
6177                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6178                            flags);
6179                    if (ii != null) {
6180                        finalList.add(ii);
6181                    }
6182                }
6183            }
6184        }
6185
6186        return finalList;
6187    }
6188
6189    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6190        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6191        if (overlays == null) {
6192            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6193            return;
6194        }
6195        for (PackageParser.Package opkg : overlays.values()) {
6196            // Not much to do if idmap fails: we already logged the error
6197            // and we certainly don't want to abort installation of pkg simply
6198            // because an overlay didn't fit properly. For these reasons,
6199            // ignore the return value of createIdmapForPackagePairLI.
6200            createIdmapForPackagePairLI(pkg, opkg);
6201        }
6202    }
6203
6204    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6205            PackageParser.Package opkg) {
6206        if (!opkg.mTrustedOverlay) {
6207            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6208                    opkg.baseCodePath + ": overlay not trusted");
6209            return false;
6210        }
6211        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6212        if (overlaySet == null) {
6213            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6214                    opkg.baseCodePath + " but target package has no known overlays");
6215            return false;
6216        }
6217        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6218        // TODO: generate idmap for split APKs
6219        try {
6220            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6221        } catch (InstallerException e) {
6222            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6223                    + opkg.baseCodePath);
6224            return false;
6225        }
6226        PackageParser.Package[] overlayArray =
6227            overlaySet.values().toArray(new PackageParser.Package[0]);
6228        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6229            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6230                return p1.mOverlayPriority - p2.mOverlayPriority;
6231            }
6232        };
6233        Arrays.sort(overlayArray, cmp);
6234
6235        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6236        int i = 0;
6237        for (PackageParser.Package p : overlayArray) {
6238            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6239        }
6240        return true;
6241    }
6242
6243    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6244        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6245        try {
6246            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6247        } finally {
6248            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6249        }
6250    }
6251
6252    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6253        final File[] files = dir.listFiles();
6254        if (ArrayUtils.isEmpty(files)) {
6255            Log.d(TAG, "No files in app dir " + dir);
6256            return;
6257        }
6258
6259        if (DEBUG_PACKAGE_SCANNING) {
6260            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6261                    + " flags=0x" + Integer.toHexString(parseFlags));
6262        }
6263
6264        for (File file : files) {
6265            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6266                    && !PackageInstallerService.isStageName(file.getName());
6267            if (!isPackage) {
6268                // Ignore entries which are not packages
6269                continue;
6270            }
6271            try {
6272                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6273                        scanFlags, currentTime, null);
6274            } catch (PackageManagerException e) {
6275                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6276
6277                // Delete invalid userdata apps
6278                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6279                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6280                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6281                    removeCodePathLI(file);
6282                }
6283            }
6284        }
6285    }
6286
6287    private static File getSettingsProblemFile() {
6288        File dataDir = Environment.getDataDirectory();
6289        File systemDir = new File(dataDir, "system");
6290        File fname = new File(systemDir, "uiderrors.txt");
6291        return fname;
6292    }
6293
6294    static void reportSettingsProblem(int priority, String msg) {
6295        logCriticalInfo(priority, msg);
6296    }
6297
6298    static void logCriticalInfo(int priority, String msg) {
6299        Slog.println(priority, TAG, msg);
6300        EventLogTags.writePmCriticalInfo(msg);
6301        try {
6302            File fname = getSettingsProblemFile();
6303            FileOutputStream out = new FileOutputStream(fname, true);
6304            PrintWriter pw = new FastPrintWriter(out);
6305            SimpleDateFormat formatter = new SimpleDateFormat();
6306            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6307            pw.println(dateString + ": " + msg);
6308            pw.close();
6309            FileUtils.setPermissions(
6310                    fname.toString(),
6311                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6312                    -1, -1);
6313        } catch (java.io.IOException e) {
6314        }
6315    }
6316
6317    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6318            int parseFlags) throws PackageManagerException {
6319        if (ps != null
6320                && ps.codePath.equals(srcFile)
6321                && ps.timeStamp == srcFile.lastModified()
6322                && !isCompatSignatureUpdateNeeded(pkg)
6323                && !isRecoverSignatureUpdateNeeded(pkg)) {
6324            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6325            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6326            ArraySet<PublicKey> signingKs;
6327            synchronized (mPackages) {
6328                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6329            }
6330            if (ps.signatures.mSignatures != null
6331                    && ps.signatures.mSignatures.length != 0
6332                    && signingKs != null) {
6333                // Optimization: reuse the existing cached certificates
6334                // if the package appears to be unchanged.
6335                pkg.mSignatures = ps.signatures.mSignatures;
6336                pkg.mSigningKeys = signingKs;
6337                return;
6338            }
6339
6340            Slog.w(TAG, "PackageSetting for " + ps.name
6341                    + " is missing signatures.  Collecting certs again to recover them.");
6342        } else {
6343            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6344        }
6345
6346        try {
6347            PackageParser.collectCertificates(pkg, parseFlags);
6348        } catch (PackageParserException e) {
6349            throw PackageManagerException.from(e);
6350        }
6351    }
6352
6353    /**
6354     *  Traces a package scan.
6355     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6356     */
6357    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6358            long currentTime, UserHandle user) throws PackageManagerException {
6359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6360        try {
6361            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6362        } finally {
6363            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6364        }
6365    }
6366
6367    /**
6368     *  Scans a package and returns the newly parsed package.
6369     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6370     */
6371    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6372            long currentTime, UserHandle user) throws PackageManagerException {
6373        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6374        parseFlags |= mDefParseFlags;
6375        PackageParser pp = new PackageParser();
6376        pp.setSeparateProcesses(mSeparateProcesses);
6377        pp.setOnlyCoreApps(mOnlyCore);
6378        pp.setDisplayMetrics(mMetrics);
6379
6380        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6381            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6382        }
6383
6384        final PackageParser.Package pkg;
6385        try {
6386            pkg = pp.parsePackage(scanFile, parseFlags);
6387        } catch (PackageParserException e) {
6388            throw PackageManagerException.from(e);
6389        }
6390
6391        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6392    }
6393
6394    /**
6395     *  Scans a package and returns the newly parsed package.
6396     *  @throws PackageManagerException on a parse error.
6397     */
6398    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6399            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6400            throws PackageManagerException {
6401        // If the package has children and this is the first dive in the function
6402        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6403        // packages (parent and children) would be successfully scanned before the
6404        // actual scan since scanning mutates internal state and we want to atomically
6405        // install the package and its children.
6406        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6407            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6408                scanFlags |= SCAN_CHECK_ONLY;
6409            }
6410        } else {
6411            scanFlags &= ~SCAN_CHECK_ONLY;
6412        }
6413
6414        // Scan the parent
6415        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6416                scanFlags, currentTime, user);
6417
6418        // Scan the children
6419        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6420        for (int i = 0; i < childCount; i++) {
6421            PackageParser.Package childPackage = pkg.childPackages.get(i);
6422            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6423                    currentTime, user);
6424        }
6425
6426
6427        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6428            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6429        }
6430
6431        return scannedPkg;
6432    }
6433
6434    /**
6435     *  Scans a package and returns the newly parsed package.
6436     *  @throws PackageManagerException on a parse error.
6437     */
6438    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6439            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6440            throws PackageManagerException {
6441        PackageSetting ps = null;
6442        PackageSetting updatedPkg;
6443        // reader
6444        synchronized (mPackages) {
6445            // Look to see if we already know about this package.
6446            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6447            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6448                // This package has been renamed to its original name.  Let's
6449                // use that.
6450                ps = mSettings.peekPackageLPr(oldName);
6451            }
6452            // If there was no original package, see one for the real package name.
6453            if (ps == null) {
6454                ps = mSettings.peekPackageLPr(pkg.packageName);
6455            }
6456            // Check to see if this package could be hiding/updating a system
6457            // package.  Must look for it either under the original or real
6458            // package name depending on our state.
6459            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6460            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6461
6462            // If this is a package we don't know about on the system partition, we
6463            // may need to remove disabled child packages on the system partition
6464            // or may need to not add child packages if the parent apk is updated
6465            // on the data partition and no longer defines this child package.
6466            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6467                // If this is a parent package for an updated system app and this system
6468                // app got an OTA update which no longer defines some of the child packages
6469                // we have to prune them from the disabled system packages.
6470                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6471                if (disabledPs != null) {
6472                    final int scannedChildCount = (pkg.childPackages != null)
6473                            ? pkg.childPackages.size() : 0;
6474                    final int disabledChildCount = disabledPs.childPackageNames != null
6475                            ? disabledPs.childPackageNames.size() : 0;
6476                    for (int i = 0; i < disabledChildCount; i++) {
6477                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6478                        boolean disabledPackageAvailable = false;
6479                        for (int j = 0; j < scannedChildCount; j++) {
6480                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6481                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6482                                disabledPackageAvailable = true;
6483                                break;
6484                            }
6485                         }
6486                         if (!disabledPackageAvailable) {
6487                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6488                         }
6489                    }
6490                }
6491            }
6492        }
6493
6494        boolean updatedPkgBetter = false;
6495        // First check if this is a system package that may involve an update
6496        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6497            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6498            // it needs to drop FLAG_PRIVILEGED.
6499            if (locationIsPrivileged(scanFile)) {
6500                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6501            } else {
6502                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6503            }
6504
6505            if (ps != null && !ps.codePath.equals(scanFile)) {
6506                // The path has changed from what was last scanned...  check the
6507                // version of the new path against what we have stored to determine
6508                // what to do.
6509                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6510                if (pkg.mVersionCode <= ps.versionCode) {
6511                    // The system package has been updated and the code path does not match
6512                    // Ignore entry. Skip it.
6513                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6514                            + " ignored: updated version " + ps.versionCode
6515                            + " better than this " + pkg.mVersionCode);
6516                    if (!updatedPkg.codePath.equals(scanFile)) {
6517                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6518                                + ps.name + " changing from " + updatedPkg.codePathString
6519                                + " to " + scanFile);
6520                        updatedPkg.codePath = scanFile;
6521                        updatedPkg.codePathString = scanFile.toString();
6522                        updatedPkg.resourcePath = scanFile;
6523                        updatedPkg.resourcePathString = scanFile.toString();
6524                    }
6525                    updatedPkg.pkg = pkg;
6526                    updatedPkg.versionCode = pkg.mVersionCode;
6527
6528                    // Update the disabled system child packages to point to the package too.
6529                    final int childCount = updatedPkg.childPackageNames != null
6530                            ? updatedPkg.childPackageNames.size() : 0;
6531                    for (int i = 0; i < childCount; i++) {
6532                        String childPackageName = updatedPkg.childPackageNames.get(i);
6533                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6534                                childPackageName);
6535                        if (updatedChildPkg != null) {
6536                            updatedChildPkg.pkg = pkg;
6537                            updatedChildPkg.versionCode = pkg.mVersionCode;
6538                        }
6539                    }
6540
6541                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6542                            + scanFile + " ignored: updated version " + ps.versionCode
6543                            + " better than this " + pkg.mVersionCode);
6544                } else {
6545                    // The current app on the system partition is better than
6546                    // what we have updated to on the data partition; switch
6547                    // back to the system partition version.
6548                    // At this point, its safely assumed that package installation for
6549                    // apps in system partition will go through. If not there won't be a working
6550                    // version of the app
6551                    // writer
6552                    synchronized (mPackages) {
6553                        // Just remove the loaded entries from package lists.
6554                        mPackages.remove(ps.name);
6555                    }
6556
6557                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6558                            + " reverting from " + ps.codePathString
6559                            + ": new version " + pkg.mVersionCode
6560                            + " better than installed " + ps.versionCode);
6561
6562                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6563                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6564                    synchronized (mInstallLock) {
6565                        args.cleanUpResourcesLI();
6566                    }
6567                    synchronized (mPackages) {
6568                        mSettings.enableSystemPackageLPw(ps.name);
6569                    }
6570                    updatedPkgBetter = true;
6571                }
6572            }
6573        }
6574
6575        if (updatedPkg != null) {
6576            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6577            // initially
6578            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6579
6580            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6581            // flag set initially
6582            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6583                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6584            }
6585        }
6586
6587        // Verify certificates against what was last scanned
6588        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6589
6590        /*
6591         * A new system app appeared, but we already had a non-system one of the
6592         * same name installed earlier.
6593         */
6594        boolean shouldHideSystemApp = false;
6595        if (updatedPkg == null && ps != null
6596                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6597            /*
6598             * Check to make sure the signatures match first. If they don't,
6599             * wipe the installed application and its data.
6600             */
6601            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6602                    != PackageManager.SIGNATURE_MATCH) {
6603                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6604                        + " signatures don't match existing userdata copy; removing");
6605                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6606                ps = null;
6607            } else {
6608                /*
6609                 * If the newly-added system app is an older version than the
6610                 * already installed version, hide it. It will be scanned later
6611                 * and re-added like an update.
6612                 */
6613                if (pkg.mVersionCode <= ps.versionCode) {
6614                    shouldHideSystemApp = true;
6615                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6616                            + " but new version " + pkg.mVersionCode + " better than installed "
6617                            + ps.versionCode + "; hiding system");
6618                } else {
6619                    /*
6620                     * The newly found system app is a newer version that the
6621                     * one previously installed. Simply remove the
6622                     * already-installed application and replace it with our own
6623                     * while keeping the application data.
6624                     */
6625                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6626                            + " reverting from " + ps.codePathString + ": new version "
6627                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6628                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6629                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6630                    synchronized (mInstallLock) {
6631                        args.cleanUpResourcesLI();
6632                    }
6633                }
6634            }
6635        }
6636
6637        // The apk is forward locked (not public) if its code and resources
6638        // are kept in different files. (except for app in either system or
6639        // vendor path).
6640        // TODO grab this value from PackageSettings
6641        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6642            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6643                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6644            }
6645        }
6646
6647        // TODO: extend to support forward-locked splits
6648        String resourcePath = null;
6649        String baseResourcePath = null;
6650        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6651            if (ps != null && ps.resourcePathString != null) {
6652                resourcePath = ps.resourcePathString;
6653                baseResourcePath = ps.resourcePathString;
6654            } else {
6655                // Should not happen at all. Just log an error.
6656                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6657            }
6658        } else {
6659            resourcePath = pkg.codePath;
6660            baseResourcePath = pkg.baseCodePath;
6661        }
6662
6663        // Set application objects path explicitly.
6664        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6665        pkg.setApplicationInfoCodePath(pkg.codePath);
6666        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6667        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6668        pkg.setApplicationInfoResourcePath(resourcePath);
6669        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6670        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6671
6672        // Note that we invoke the following method only if we are about to unpack an application
6673        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6674                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6675
6676        /*
6677         * If the system app should be overridden by a previously installed
6678         * data, hide the system app now and let the /data/app scan pick it up
6679         * again.
6680         */
6681        if (shouldHideSystemApp) {
6682            synchronized (mPackages) {
6683                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6684            }
6685        }
6686
6687        return scannedPkg;
6688    }
6689
6690    private static String fixProcessName(String defProcessName,
6691            String processName, int uid) {
6692        if (processName == null) {
6693            return defProcessName;
6694        }
6695        return processName;
6696    }
6697
6698    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6699            throws PackageManagerException {
6700        if (pkgSetting.signatures.mSignatures != null) {
6701            // Already existing package. Make sure signatures match
6702            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6703                    == PackageManager.SIGNATURE_MATCH;
6704            if (!match) {
6705                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6706                        == PackageManager.SIGNATURE_MATCH;
6707            }
6708            if (!match) {
6709                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6710                        == PackageManager.SIGNATURE_MATCH;
6711            }
6712            if (!match) {
6713                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6714                        + pkg.packageName + " signatures do not match the "
6715                        + "previously installed version; ignoring!");
6716            }
6717        }
6718
6719        // Check for shared user signatures
6720        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6721            // Already existing package. Make sure signatures match
6722            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6723                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6724            if (!match) {
6725                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6726                        == PackageManager.SIGNATURE_MATCH;
6727            }
6728            if (!match) {
6729                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6730                        == PackageManager.SIGNATURE_MATCH;
6731            }
6732            if (!match) {
6733                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6734                        "Package " + pkg.packageName
6735                        + " has no signatures that match those in shared user "
6736                        + pkgSetting.sharedUser.name + "; ignoring!");
6737            }
6738        }
6739    }
6740
6741    /**
6742     * Enforces that only the system UID or root's UID can call a method exposed
6743     * via Binder.
6744     *
6745     * @param message used as message if SecurityException is thrown
6746     * @throws SecurityException if the caller is not system or root
6747     */
6748    private static final void enforceSystemOrRoot(String message) {
6749        final int uid = Binder.getCallingUid();
6750        if (uid != Process.SYSTEM_UID && uid != 0) {
6751            throw new SecurityException(message);
6752        }
6753    }
6754
6755    @Override
6756    public void performFstrimIfNeeded() {
6757        enforceSystemOrRoot("Only the system can request fstrim");
6758
6759        // Before everything else, see whether we need to fstrim.
6760        try {
6761            IMountService ms = PackageHelper.getMountService();
6762            if (ms != null) {
6763                final boolean isUpgrade = isUpgrade();
6764                boolean doTrim = isUpgrade;
6765                if (doTrim) {
6766                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6767                } else {
6768                    final long interval = android.provider.Settings.Global.getLong(
6769                            mContext.getContentResolver(),
6770                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6771                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6772                    if (interval > 0) {
6773                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6774                        if (timeSinceLast > interval) {
6775                            doTrim = true;
6776                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6777                                    + "; running immediately");
6778                        }
6779                    }
6780                }
6781                if (doTrim) {
6782                    if (!isFirstBoot()) {
6783                        try {
6784                            ActivityManagerNative.getDefault().showBootMessage(
6785                                    mContext.getResources().getString(
6786                                            R.string.android_upgrading_fstrim), true);
6787                        } catch (RemoteException e) {
6788                        }
6789                    }
6790                    ms.runMaintenance();
6791                }
6792            } else {
6793                Slog.e(TAG, "Mount service unavailable!");
6794            }
6795        } catch (RemoteException e) {
6796            // Can't happen; MountService is local
6797        }
6798    }
6799
6800    @Override
6801    public void extractPackagesIfNeeded() {
6802        enforceSystemOrRoot("Only the system can request package extraction");
6803
6804        // Extract pacakges only if profile-guided compilation is enabled because
6805        // otherwise BackgroundDexOptService will not dexopt them later.
6806        if (!mUseJitProfiles || !isUpgrade()) {
6807            return;
6808        }
6809
6810        List<PackageParser.Package> pkgs;
6811        synchronized (mPackages) {
6812            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6813        }
6814
6815        int curr = 0;
6816        int total = pkgs.size();
6817        for (PackageParser.Package pkg : pkgs) {
6818            curr++;
6819
6820            if (DEBUG_DEXOPT) {
6821                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6822            }
6823
6824            if (!isFirstBoot()) {
6825                try {
6826                    ActivityManagerNative.getDefault().showBootMessage(
6827                            mContext.getResources().getString(R.string.android_upgrading_apk,
6828                                    curr, total), true);
6829                } catch (RemoteException e) {
6830                }
6831            }
6832
6833            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6834                performDexOpt(pkg.packageName, null /* instructionSet */,
6835                         false /* useProfiles */, true /* extractOnly */, false /* force */);
6836            }
6837        }
6838    }
6839
6840    @Override
6841    public void notifyPackageUse(String packageName) {
6842        synchronized (mPackages) {
6843            PackageParser.Package p = mPackages.get(packageName);
6844            if (p == null) {
6845                return;
6846            }
6847            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6848        }
6849    }
6850
6851    // TODO: this is not used nor needed. Delete it.
6852    @Override
6853    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6854        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6855                false /* extractOnly */, false /* force */);
6856    }
6857
6858    @Override
6859    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6860            boolean extractOnly, boolean force) {
6861        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6862    }
6863
6864    private boolean performDexOptTraced(String packageName, String instructionSet,
6865                boolean useProfiles, boolean extractOnly, boolean force) {
6866        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6867        try {
6868            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6869                    force);
6870        } finally {
6871            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6872        }
6873    }
6874
6875    private boolean performDexOptInternal(String packageName, String instructionSet,
6876                boolean useProfiles, boolean extractOnly, boolean force) {
6877        PackageParser.Package p;
6878        final String targetInstructionSet;
6879        synchronized (mPackages) {
6880            p = mPackages.get(packageName);
6881            if (p == null) {
6882                return false;
6883            }
6884            mPackageUsage.write(false);
6885
6886            targetInstructionSet = instructionSet != null ? instructionSet :
6887                    getPrimaryInstructionSet(p.applicationInfo);
6888            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6889                // Skip only if we do not use profiles since they might trigger a recompilation.
6890                return false;
6891            }
6892        }
6893        long callingId = Binder.clearCallingIdentity();
6894        try {
6895            synchronized (mInstallLock) {
6896                final String[] instructionSets = new String[] { targetInstructionSet };
6897                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6898                        useProfiles, extractOnly, force);
6899                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6900            }
6901        } finally {
6902            Binder.restoreCallingIdentity(callingId);
6903        }
6904    }
6905
6906    public ArraySet<String> getOptimizablePackages() {
6907        ArraySet<String> pkgs = new ArraySet<String>();
6908        synchronized (mPackages) {
6909            for (PackageParser.Package p : mPackages.values()) {
6910                if (PackageDexOptimizer.canOptimizePackage(p)) {
6911                    pkgs.add(p.packageName);
6912                }
6913            }
6914        }
6915        return pkgs;
6916    }
6917
6918    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6919            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6920        // Select the dex optimizer based on the force parameter.
6921        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6922        //       allocate an object here.
6923        PackageDexOptimizer pdo = force
6924                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6925                : mPackageDexOptimizer;
6926
6927        // Optimize all dependencies first. Note: we ignore the return value and march on
6928        // on errors.
6929        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6930        if (!deps.isEmpty()) {
6931            for (PackageParser.Package depPackage : deps) {
6932                // TODO: Analyze and investigate if we (should) profile libraries.
6933                // Currently this will do a full compilation of the library.
6934                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6935                        false /* extractOnly */);
6936            }
6937        }
6938
6939        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6940    }
6941
6942    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6943        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6944            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6945            Set<String> collectedNames = new HashSet<>();
6946            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6947
6948            retValue.remove(p);
6949
6950            return retValue;
6951        } else {
6952            return Collections.emptyList();
6953        }
6954    }
6955
6956    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6957            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6958        if (!collectedNames.contains(p.packageName)) {
6959            collectedNames.add(p.packageName);
6960            collected.add(p);
6961
6962            if (p.usesLibraries != null) {
6963                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6964            }
6965            if (p.usesOptionalLibraries != null) {
6966                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6967                        collectedNames);
6968            }
6969        }
6970    }
6971
6972    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6973            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6974        for (String libName : libs) {
6975            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6976            if (libPkg != null) {
6977                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6978            }
6979        }
6980    }
6981
6982    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6983        synchronized (mPackages) {
6984            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6985            if (lib != null && lib.apk != null) {
6986                return mPackages.get(lib.apk);
6987            }
6988        }
6989        return null;
6990    }
6991
6992    public void shutdown() {
6993        mPackageUsage.write(true);
6994    }
6995
6996    @Override
6997    public void forceDexOpt(String packageName) {
6998        enforceSystemOrRoot("forceDexOpt");
6999
7000        PackageParser.Package pkg;
7001        synchronized (mPackages) {
7002            pkg = mPackages.get(packageName);
7003            if (pkg == null) {
7004                throw new IllegalArgumentException("Unknown package: " + packageName);
7005            }
7006        }
7007
7008        synchronized (mInstallLock) {
7009            final String[] instructionSets = new String[] {
7010                    getPrimaryInstructionSet(pkg.applicationInfo) };
7011
7012            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7013
7014            // Whoever is calling forceDexOpt wants a fully compiled package.
7015            // Don't use profiles since that may cause compilation to be skipped.
7016            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7017                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7018
7019            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7020            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7021                throw new IllegalStateException("Failed to dexopt: " + res);
7022            }
7023        }
7024    }
7025
7026    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7027        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7028            Slog.w(TAG, "Unable to update from " + oldPkg.name
7029                    + " to " + newPkg.packageName
7030                    + ": old package not in system partition");
7031            return false;
7032        } else if (mPackages.get(oldPkg.name) != null) {
7033            Slog.w(TAG, "Unable to update from " + oldPkg.name
7034                    + " to " + newPkg.packageName
7035                    + ": old package still exists");
7036            return false;
7037        }
7038        return true;
7039    }
7040
7041    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7042        // TODO: triage flags as part of 26466827
7043        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7044
7045        boolean res = true;
7046        final int[] users = sUserManager.getUserIds();
7047        for (int user : users) {
7048            try {
7049                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7050            } catch (InstallerException e) {
7051                Slog.w(TAG, "Failed to delete data directory", e);
7052                res = false;
7053            }
7054        }
7055        return res;
7056    }
7057
7058    void removeCodePathLI(File codePath) {
7059        if (codePath.isDirectory()) {
7060            try {
7061                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7062            } catch (InstallerException e) {
7063                Slog.w(TAG, "Failed to remove code path", e);
7064            }
7065        } else {
7066            codePath.delete();
7067        }
7068    }
7069
7070    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7071        try {
7072            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7073        } catch (InstallerException e) {
7074            Slog.w(TAG, "Failed to destroy app data", e);
7075        }
7076    }
7077
7078    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7079            int appId, String seinfo) {
7080        try {
7081            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7082        } catch (InstallerException e) {
7083            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7084        }
7085    }
7086
7087    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7088        final PackageParser.Package pkg;
7089        synchronized (mPackages) {
7090            pkg = mPackages.get(packageName);
7091        }
7092        if (pkg == null) {
7093            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7094            return;
7095        }
7096        deleteCodeCacheDirsLI(pkg);
7097    }
7098
7099    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7100        // TODO: triage flags as part of 26466827
7101        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7102
7103        int[] users = sUserManager.getUserIds();
7104        int res = 0;
7105        for (int user : users) {
7106            // Remove the parent code cache
7107            try {
7108                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7109                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7110            } catch (InstallerException e) {
7111                Slog.w(TAG, "Failed to delete code cache directory", e);
7112            }
7113            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7114            for (int i = 0; i < childCount; i++) {
7115                PackageParser.Package childPkg = pkg.childPackages.get(i);
7116                // Remove the child code cache
7117                try {
7118                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7119                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7120                } catch (InstallerException e) {
7121                    Slog.w(TAG, "Failed to delete code cache directory", e);
7122                }
7123            }
7124        }
7125    }
7126
7127    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7128            long lastUpdateTime) {
7129        // Set parent install/update time
7130        PackageSetting ps = (PackageSetting) pkg.mExtras;
7131        if (ps != null) {
7132            ps.firstInstallTime = firstInstallTime;
7133            ps.lastUpdateTime = lastUpdateTime;
7134        }
7135        // Set children install/update time
7136        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7137        for (int i = 0; i < childCount; i++) {
7138            PackageParser.Package childPkg = pkg.childPackages.get(i);
7139            ps = (PackageSetting) childPkg.mExtras;
7140            if (ps != null) {
7141                ps.firstInstallTime = firstInstallTime;
7142                ps.lastUpdateTime = lastUpdateTime;
7143            }
7144        }
7145    }
7146
7147    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7148            PackageParser.Package changingLib) {
7149        if (file.path != null) {
7150            usesLibraryFiles.add(file.path);
7151            return;
7152        }
7153        PackageParser.Package p = mPackages.get(file.apk);
7154        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7155            // If we are doing this while in the middle of updating a library apk,
7156            // then we need to make sure to use that new apk for determining the
7157            // dependencies here.  (We haven't yet finished committing the new apk
7158            // to the package manager state.)
7159            if (p == null || p.packageName.equals(changingLib.packageName)) {
7160                p = changingLib;
7161            }
7162        }
7163        if (p != null) {
7164            usesLibraryFiles.addAll(p.getAllCodePaths());
7165        }
7166    }
7167
7168    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7169            PackageParser.Package changingLib) throws PackageManagerException {
7170        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7171            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7172            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7173            for (int i=0; i<N; i++) {
7174                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7175                if (file == null) {
7176                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7177                            "Package " + pkg.packageName + " requires unavailable shared library "
7178                            + pkg.usesLibraries.get(i) + "; failing!");
7179                }
7180                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7181            }
7182            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7183            for (int i=0; i<N; i++) {
7184                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7185                if (file == null) {
7186                    Slog.w(TAG, "Package " + pkg.packageName
7187                            + " desires unavailable shared library "
7188                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7189                } else {
7190                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7191                }
7192            }
7193            N = usesLibraryFiles.size();
7194            if (N > 0) {
7195                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7196            } else {
7197                pkg.usesLibraryFiles = null;
7198            }
7199        }
7200    }
7201
7202    private static boolean hasString(List<String> list, List<String> which) {
7203        if (list == null) {
7204            return false;
7205        }
7206        for (int i=list.size()-1; i>=0; i--) {
7207            for (int j=which.size()-1; j>=0; j--) {
7208                if (which.get(j).equals(list.get(i))) {
7209                    return true;
7210                }
7211            }
7212        }
7213        return false;
7214    }
7215
7216    private void updateAllSharedLibrariesLPw() {
7217        for (PackageParser.Package pkg : mPackages.values()) {
7218            try {
7219                updateSharedLibrariesLPw(pkg, null);
7220            } catch (PackageManagerException e) {
7221                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7222            }
7223        }
7224    }
7225
7226    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7227            PackageParser.Package changingPkg) {
7228        ArrayList<PackageParser.Package> res = null;
7229        for (PackageParser.Package pkg : mPackages.values()) {
7230            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7231                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7232                if (res == null) {
7233                    res = new ArrayList<PackageParser.Package>();
7234                }
7235                res.add(pkg);
7236                try {
7237                    updateSharedLibrariesLPw(pkg, changingPkg);
7238                } catch (PackageManagerException e) {
7239                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7240                }
7241            }
7242        }
7243        return res;
7244    }
7245
7246    /**
7247     * Derive the value of the {@code cpuAbiOverride} based on the provided
7248     * value and an optional stored value from the package settings.
7249     */
7250    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7251        String cpuAbiOverride = null;
7252
7253        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7254            cpuAbiOverride = null;
7255        } else if (abiOverride != null) {
7256            cpuAbiOverride = abiOverride;
7257        } else if (settings != null) {
7258            cpuAbiOverride = settings.cpuAbiOverrideString;
7259        }
7260
7261        return cpuAbiOverride;
7262    }
7263
7264    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7265            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7266        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7267        // If the package has children and this is the first dive in the function
7268        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7269        // whether all packages (parent and children) would be successfully scanned
7270        // before the actual scan since scanning mutates internal state and we want
7271        // to atomically install the package and its children.
7272        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7273            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7274                scanFlags |= SCAN_CHECK_ONLY;
7275            }
7276        } else {
7277            scanFlags &= ~SCAN_CHECK_ONLY;
7278        }
7279
7280        final PackageParser.Package scannedPkg;
7281        try {
7282            // Scan the parent
7283            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7284            // Scan the children
7285            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7286            for (int i = 0; i < childCount; i++) {
7287                PackageParser.Package childPkg = pkg.childPackages.get(i);
7288                scanPackageLI(childPkg, parseFlags,
7289                        scanFlags, currentTime, user);
7290            }
7291        } finally {
7292            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7293        }
7294
7295        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7296            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7297        }
7298
7299        return scannedPkg;
7300    }
7301
7302    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7303            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7304        boolean success = false;
7305        try {
7306            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7307                    currentTime, user);
7308            success = true;
7309            return res;
7310        } finally {
7311            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7312                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7313            }
7314        }
7315    }
7316
7317    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7318            int scanFlags, long currentTime, UserHandle user)
7319            throws PackageManagerException {
7320        final File scanFile = new File(pkg.codePath);
7321        if (pkg.applicationInfo.getCodePath() == null ||
7322                pkg.applicationInfo.getResourcePath() == null) {
7323            // Bail out. The resource and code paths haven't been set.
7324            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7325                    "Code and resource paths haven't been set correctly");
7326        }
7327
7328        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7329            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7330        } else {
7331            // Only allow system apps to be flagged as core apps.
7332            pkg.coreApp = false;
7333        }
7334
7335        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7336            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7337        }
7338
7339        if (mCustomResolverComponentName != null &&
7340                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7341            setUpCustomResolverActivity(pkg);
7342        }
7343
7344        if (pkg.packageName.equals("android")) {
7345            synchronized (mPackages) {
7346                if (mAndroidApplication != null) {
7347                    Slog.w(TAG, "*************************************************");
7348                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7349                    Slog.w(TAG, " file=" + scanFile);
7350                    Slog.w(TAG, "*************************************************");
7351                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7352                            "Core android package being redefined.  Skipping.");
7353                }
7354
7355                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7356                    // Set up information for our fall-back user intent resolution activity.
7357                    mPlatformPackage = pkg;
7358                    pkg.mVersionCode = mSdkVersion;
7359                    mAndroidApplication = pkg.applicationInfo;
7360
7361                    if (!mResolverReplaced) {
7362                        mResolveActivity.applicationInfo = mAndroidApplication;
7363                        mResolveActivity.name = ResolverActivity.class.getName();
7364                        mResolveActivity.packageName = mAndroidApplication.packageName;
7365                        mResolveActivity.processName = "system:ui";
7366                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7367                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7368                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7369                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7370                        mResolveActivity.exported = true;
7371                        mResolveActivity.enabled = true;
7372                        mResolveInfo.activityInfo = mResolveActivity;
7373                        mResolveInfo.priority = 0;
7374                        mResolveInfo.preferredOrder = 0;
7375                        mResolveInfo.match = 0;
7376                        mResolveComponentName = new ComponentName(
7377                                mAndroidApplication.packageName, mResolveActivity.name);
7378                    }
7379                }
7380            }
7381        }
7382
7383        if (DEBUG_PACKAGE_SCANNING) {
7384            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7385                Log.d(TAG, "Scanning package " + pkg.packageName);
7386        }
7387
7388        synchronized (mPackages) {
7389            if (mPackages.containsKey(pkg.packageName)
7390                    || mSharedLibraries.containsKey(pkg.packageName)) {
7391                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7392                        "Application package " + pkg.packageName
7393                                + " already installed.  Skipping duplicate.");
7394            }
7395
7396            // If we're only installing presumed-existing packages, require that the
7397            // scanned APK is both already known and at the path previously established
7398            // for it.  Previously unknown packages we pick up normally, but if we have an
7399            // a priori expectation about this package's install presence, enforce it.
7400            // With a singular exception for new system packages. When an OTA contains
7401            // a new system package, we allow the codepath to change from a system location
7402            // to the user-installed location. If we don't allow this change, any newer,
7403            // user-installed version of the application will be ignored.
7404            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7405                if (mExpectingBetter.containsKey(pkg.packageName)) {
7406                    logCriticalInfo(Log.WARN,
7407                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7408                } else {
7409                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7410                    if (known != null) {
7411                        if (DEBUG_PACKAGE_SCANNING) {
7412                            Log.d(TAG, "Examining " + pkg.codePath
7413                                    + " and requiring known paths " + known.codePathString
7414                                    + " & " + known.resourcePathString);
7415                        }
7416                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7417                                || !pkg.applicationInfo.getResourcePath().equals(
7418                                known.resourcePathString)) {
7419                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7420                                    "Application package " + pkg.packageName
7421                                            + " found at " + pkg.applicationInfo.getCodePath()
7422                                            + " but expected at " + known.codePathString
7423                                            + "; ignoring.");
7424                        }
7425                    }
7426                }
7427            }
7428        }
7429
7430        // Initialize package source and resource directories
7431        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7432        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7433
7434        SharedUserSetting suid = null;
7435        PackageSetting pkgSetting = null;
7436
7437        if (!isSystemApp(pkg)) {
7438            // Only system apps can use these features.
7439            pkg.mOriginalPackages = null;
7440            pkg.mRealPackage = null;
7441            pkg.mAdoptPermissions = null;
7442        }
7443
7444        // Getting the package setting may have a side-effect, so if we
7445        // are only checking if scan would succeed, stash a copy of the
7446        // old setting to restore at the end.
7447        PackageSetting nonMutatedPs = null;
7448
7449        // writer
7450        synchronized (mPackages) {
7451            if (pkg.mSharedUserId != null) {
7452                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7453                if (suid == null) {
7454                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7455                            "Creating application package " + pkg.packageName
7456                            + " for shared user failed");
7457                }
7458                if (DEBUG_PACKAGE_SCANNING) {
7459                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7460                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7461                                + "): packages=" + suid.packages);
7462                }
7463            }
7464
7465            // Check if we are renaming from an original package name.
7466            PackageSetting origPackage = null;
7467            String realName = null;
7468            if (pkg.mOriginalPackages != null) {
7469                // This package may need to be renamed to a previously
7470                // installed name.  Let's check on that...
7471                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7472                if (pkg.mOriginalPackages.contains(renamed)) {
7473                    // This package had originally been installed as the
7474                    // original name, and we have already taken care of
7475                    // transitioning to the new one.  Just update the new
7476                    // one to continue using the old name.
7477                    realName = pkg.mRealPackage;
7478                    if (!pkg.packageName.equals(renamed)) {
7479                        // Callers into this function may have already taken
7480                        // care of renaming the package; only do it here if
7481                        // it is not already done.
7482                        pkg.setPackageName(renamed);
7483                    }
7484
7485                } else {
7486                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7487                        if ((origPackage = mSettings.peekPackageLPr(
7488                                pkg.mOriginalPackages.get(i))) != null) {
7489                            // We do have the package already installed under its
7490                            // original name...  should we use it?
7491                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7492                                // New package is not compatible with original.
7493                                origPackage = null;
7494                                continue;
7495                            } else if (origPackage.sharedUser != null) {
7496                                // Make sure uid is compatible between packages.
7497                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7498                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7499                                            + " to " + pkg.packageName + ": old uid "
7500                                            + origPackage.sharedUser.name
7501                                            + " differs from " + pkg.mSharedUserId);
7502                                    origPackage = null;
7503                                    continue;
7504                                }
7505                            } else {
7506                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7507                                        + pkg.packageName + " to old name " + origPackage.name);
7508                            }
7509                            break;
7510                        }
7511                    }
7512                }
7513            }
7514
7515            if (mTransferedPackages.contains(pkg.packageName)) {
7516                Slog.w(TAG, "Package " + pkg.packageName
7517                        + " was transferred to another, but its .apk remains");
7518            }
7519
7520            // See comments in nonMutatedPs declaration
7521            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7522                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7523                if (foundPs != null) {
7524                    nonMutatedPs = new PackageSetting(foundPs);
7525                }
7526            }
7527
7528            // Just create the setting, don't add it yet. For already existing packages
7529            // the PkgSetting exists already and doesn't have to be created.
7530            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7531                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7532                    pkg.applicationInfo.primaryCpuAbi,
7533                    pkg.applicationInfo.secondaryCpuAbi,
7534                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7535                    user, false);
7536            if (pkgSetting == null) {
7537                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7538                        "Creating application package " + pkg.packageName + " failed");
7539            }
7540
7541            if (pkgSetting.origPackage != null) {
7542                // If we are first transitioning from an original package,
7543                // fix up the new package's name now.  We need to do this after
7544                // looking up the package under its new name, so getPackageLP
7545                // can take care of fiddling things correctly.
7546                pkg.setPackageName(origPackage.name);
7547
7548                // File a report about this.
7549                String msg = "New package " + pkgSetting.realName
7550                        + " renamed to replace old package " + pkgSetting.name;
7551                reportSettingsProblem(Log.WARN, msg);
7552
7553                // Make a note of it.
7554                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7555                    mTransferedPackages.add(origPackage.name);
7556                }
7557
7558                // No longer need to retain this.
7559                pkgSetting.origPackage = null;
7560            }
7561
7562            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7563                // Make a note of it.
7564                mTransferedPackages.add(pkg.packageName);
7565            }
7566
7567            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7568                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7569            }
7570
7571            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7572                // Check all shared libraries and map to their actual file path.
7573                // We only do this here for apps not on a system dir, because those
7574                // are the only ones that can fail an install due to this.  We
7575                // will take care of the system apps by updating all of their
7576                // library paths after the scan is done.
7577                updateSharedLibrariesLPw(pkg, null);
7578            }
7579
7580            if (mFoundPolicyFile) {
7581                SELinuxMMAC.assignSeinfoValue(pkg);
7582            }
7583
7584            pkg.applicationInfo.uid = pkgSetting.appId;
7585            pkg.mExtras = pkgSetting;
7586            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7587                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7588                    // We just determined the app is signed correctly, so bring
7589                    // over the latest parsed certs.
7590                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7591                } else {
7592                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7593                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7594                                "Package " + pkg.packageName + " upgrade keys do not match the "
7595                                + "previously installed version");
7596                    } else {
7597                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7598                        String msg = "System package " + pkg.packageName
7599                            + " signature changed; retaining data.";
7600                        reportSettingsProblem(Log.WARN, msg);
7601                    }
7602                }
7603            } else {
7604                try {
7605                    verifySignaturesLP(pkgSetting, pkg);
7606                    // We just determined the app is signed correctly, so bring
7607                    // over the latest parsed certs.
7608                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7609                } catch (PackageManagerException e) {
7610                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7611                        throw e;
7612                    }
7613                    // The signature has changed, but this package is in the system
7614                    // image...  let's recover!
7615                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7616                    // However...  if this package is part of a shared user, but it
7617                    // doesn't match the signature of the shared user, let's fail.
7618                    // What this means is that you can't change the signatures
7619                    // associated with an overall shared user, which doesn't seem all
7620                    // that unreasonable.
7621                    if (pkgSetting.sharedUser != null) {
7622                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7623                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7624                            throw new PackageManagerException(
7625                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7626                                            "Signature mismatch for shared user: "
7627                                            + pkgSetting.sharedUser);
7628                        }
7629                    }
7630                    // File a report about this.
7631                    String msg = "System package " + pkg.packageName
7632                        + " signature changed; retaining data.";
7633                    reportSettingsProblem(Log.WARN, msg);
7634                }
7635            }
7636            // Verify that this new package doesn't have any content providers
7637            // that conflict with existing packages.  Only do this if the
7638            // package isn't already installed, since we don't want to break
7639            // things that are installed.
7640            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7641                final int N = pkg.providers.size();
7642                int i;
7643                for (i=0; i<N; i++) {
7644                    PackageParser.Provider p = pkg.providers.get(i);
7645                    if (p.info.authority != null) {
7646                        String names[] = p.info.authority.split(";");
7647                        for (int j = 0; j < names.length; j++) {
7648                            if (mProvidersByAuthority.containsKey(names[j])) {
7649                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7650                                final String otherPackageName =
7651                                        ((other != null && other.getComponentName() != null) ?
7652                                                other.getComponentName().getPackageName() : "?");
7653                                throw new PackageManagerException(
7654                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7655                                                "Can't install because provider name " + names[j]
7656                                                + " (in package " + pkg.applicationInfo.packageName
7657                                                + ") is already used by " + otherPackageName);
7658                            }
7659                        }
7660                    }
7661                }
7662            }
7663
7664            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7665                // This package wants to adopt ownership of permissions from
7666                // another package.
7667                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7668                    final String origName = pkg.mAdoptPermissions.get(i);
7669                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7670                    if (orig != null) {
7671                        if (verifyPackageUpdateLPr(orig, pkg)) {
7672                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7673                                    + pkg.packageName);
7674                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7675                        }
7676                    }
7677                }
7678            }
7679        }
7680
7681        final String pkgName = pkg.packageName;
7682
7683        final long scanFileTime = scanFile.lastModified();
7684        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7685        pkg.applicationInfo.processName = fixProcessName(
7686                pkg.applicationInfo.packageName,
7687                pkg.applicationInfo.processName,
7688                pkg.applicationInfo.uid);
7689
7690        if (pkg != mPlatformPackage) {
7691            // Get all of our default paths setup
7692            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7693        }
7694
7695        final String path = scanFile.getPath();
7696        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7697
7698        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7699            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7700
7701            // Some system apps still use directory structure for native libraries
7702            // in which case we might end up not detecting abi solely based on apk
7703            // structure. Try to detect abi based on directory structure.
7704            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7705                    pkg.applicationInfo.primaryCpuAbi == null) {
7706                setBundledAppAbisAndRoots(pkg, pkgSetting);
7707                setNativeLibraryPaths(pkg);
7708            }
7709
7710        } else {
7711            if ((scanFlags & SCAN_MOVE) != 0) {
7712                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7713                // but we already have this packages package info in the PackageSetting. We just
7714                // use that and derive the native library path based on the new codepath.
7715                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7716                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7717            }
7718
7719            // Set native library paths again. For moves, the path will be updated based on the
7720            // ABIs we've determined above. For non-moves, the path will be updated based on the
7721            // ABIs we determined during compilation, but the path will depend on the final
7722            // package path (after the rename away from the stage path).
7723            setNativeLibraryPaths(pkg);
7724        }
7725
7726        // This is a special case for the "system" package, where the ABI is
7727        // dictated by the zygote configuration (and init.rc). We should keep track
7728        // of this ABI so that we can deal with "normal" applications that run under
7729        // the same UID correctly.
7730        if (mPlatformPackage == pkg) {
7731            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7732                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7733        }
7734
7735        // If there's a mismatch between the abi-override in the package setting
7736        // and the abiOverride specified for the install. Warn about this because we
7737        // would've already compiled the app without taking the package setting into
7738        // account.
7739        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7740            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7741                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7742                        " for package " + pkg.packageName);
7743            }
7744        }
7745
7746        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7747        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7748        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7749
7750        // Copy the derived override back to the parsed package, so that we can
7751        // update the package settings accordingly.
7752        pkg.cpuAbiOverride = cpuAbiOverride;
7753
7754        if (DEBUG_ABI_SELECTION) {
7755            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7756                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7757                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7758        }
7759
7760        // Push the derived path down into PackageSettings so we know what to
7761        // clean up at uninstall time.
7762        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7763
7764        if (DEBUG_ABI_SELECTION) {
7765            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7766                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7767                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7768        }
7769
7770        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7771            // We don't do this here during boot because we can do it all
7772            // at once after scanning all existing packages.
7773            //
7774            // We also do this *before* we perform dexopt on this package, so that
7775            // we can avoid redundant dexopts, and also to make sure we've got the
7776            // code and package path correct.
7777            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7778                    pkg, true /* boot complete */);
7779        }
7780
7781        if (mFactoryTest && pkg.requestedPermissions.contains(
7782                android.Manifest.permission.FACTORY_TEST)) {
7783            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7784        }
7785
7786        ArrayList<PackageParser.Package> clientLibPkgs = null;
7787
7788        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7789            if (nonMutatedPs != null) {
7790                synchronized (mPackages) {
7791                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7792                }
7793            }
7794            return pkg;
7795        }
7796
7797        // Only privileged apps and updated privileged apps can add child packages.
7798        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7799            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7800                throw new PackageManagerException("Only privileged apps and updated "
7801                        + "privileged apps can add child packages. Ignoring package "
7802                        + pkg.packageName);
7803            }
7804            final int childCount = pkg.childPackages.size();
7805            for (int i = 0; i < childCount; i++) {
7806                PackageParser.Package childPkg = pkg.childPackages.get(i);
7807                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7808                        childPkg.packageName)) {
7809                    throw new PackageManagerException("Cannot override a child package of "
7810                            + "another disabled system app. Ignoring package " + pkg.packageName);
7811                }
7812            }
7813        }
7814
7815        // writer
7816        synchronized (mPackages) {
7817            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7818                // Only system apps can add new shared libraries.
7819                if (pkg.libraryNames != null) {
7820                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7821                        String name = pkg.libraryNames.get(i);
7822                        boolean allowed = false;
7823                        if (pkg.isUpdatedSystemApp()) {
7824                            // New library entries can only be added through the
7825                            // system image.  This is important to get rid of a lot
7826                            // of nasty edge cases: for example if we allowed a non-
7827                            // system update of the app to add a library, then uninstalling
7828                            // the update would make the library go away, and assumptions
7829                            // we made such as through app install filtering would now
7830                            // have allowed apps on the device which aren't compatible
7831                            // with it.  Better to just have the restriction here, be
7832                            // conservative, and create many fewer cases that can negatively
7833                            // impact the user experience.
7834                            final PackageSetting sysPs = mSettings
7835                                    .getDisabledSystemPkgLPr(pkg.packageName);
7836                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7837                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7838                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7839                                        allowed = true;
7840                                        break;
7841                                    }
7842                                }
7843                            }
7844                        } else {
7845                            allowed = true;
7846                        }
7847                        if (allowed) {
7848                            if (!mSharedLibraries.containsKey(name)) {
7849                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7850                            } else if (!name.equals(pkg.packageName)) {
7851                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7852                                        + name + " already exists; skipping");
7853                            }
7854                        } else {
7855                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7856                                    + name + " that is not declared on system image; skipping");
7857                        }
7858                    }
7859                    if ((scanFlags & SCAN_BOOTING) == 0) {
7860                        // If we are not booting, we need to update any applications
7861                        // that are clients of our shared library.  If we are booting,
7862                        // this will all be done once the scan is complete.
7863                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7864                    }
7865                }
7866            }
7867        }
7868
7869        // Request the ActivityManager to kill the process(only for existing packages)
7870        // so that we do not end up in a confused state while the user is still using the older
7871        // version of the application while the new one gets installed.
7872        if ((scanFlags & SCAN_REPLACING) != 0) {
7873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7874
7875            killApplication(pkg.applicationInfo.packageName,
7876                        pkg.applicationInfo.uid, "replace pkg");
7877
7878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7879        }
7880
7881        // Also need to kill any apps that are dependent on the library.
7882        if (clientLibPkgs != null) {
7883            for (int i=0; i<clientLibPkgs.size(); i++) {
7884                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7885                killApplication(clientPkg.applicationInfo.packageName,
7886                        clientPkg.applicationInfo.uid, "update lib");
7887            }
7888        }
7889
7890        // Make sure we're not adding any bogus keyset info
7891        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7892        ksms.assertScannedPackageValid(pkg);
7893
7894        // writer
7895        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7896
7897        boolean createIdmapFailed = false;
7898        synchronized (mPackages) {
7899            // We don't expect installation to fail beyond this point
7900
7901            // Add the new setting to mSettings
7902            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7903            // Add the new setting to mPackages
7904            mPackages.put(pkg.applicationInfo.packageName, pkg);
7905            // Make sure we don't accidentally delete its data.
7906            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7907            while (iter.hasNext()) {
7908                PackageCleanItem item = iter.next();
7909                if (pkgName.equals(item.packageName)) {
7910                    iter.remove();
7911                }
7912            }
7913
7914            // Take care of first install / last update times.
7915            if (currentTime != 0) {
7916                if (pkgSetting.firstInstallTime == 0) {
7917                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7918                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7919                    pkgSetting.lastUpdateTime = currentTime;
7920                }
7921            } else if (pkgSetting.firstInstallTime == 0) {
7922                // We need *something*.  Take time time stamp of the file.
7923                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7924            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7925                if (scanFileTime != pkgSetting.timeStamp) {
7926                    // A package on the system image has changed; consider this
7927                    // to be an update.
7928                    pkgSetting.lastUpdateTime = scanFileTime;
7929                }
7930            }
7931
7932            // Add the package's KeySets to the global KeySetManagerService
7933            ksms.addScannedPackageLPw(pkg);
7934
7935            int N = pkg.providers.size();
7936            StringBuilder r = null;
7937            int i;
7938            for (i=0; i<N; i++) {
7939                PackageParser.Provider p = pkg.providers.get(i);
7940                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7941                        p.info.processName, pkg.applicationInfo.uid);
7942                mProviders.addProvider(p);
7943                p.syncable = p.info.isSyncable;
7944                if (p.info.authority != null) {
7945                    String names[] = p.info.authority.split(";");
7946                    p.info.authority = null;
7947                    for (int j = 0; j < names.length; j++) {
7948                        if (j == 1 && p.syncable) {
7949                            // We only want the first authority for a provider to possibly be
7950                            // syncable, so if we already added this provider using a different
7951                            // authority clear the syncable flag. We copy the provider before
7952                            // changing it because the mProviders object contains a reference
7953                            // to a provider that we don't want to change.
7954                            // Only do this for the second authority since the resulting provider
7955                            // object can be the same for all future authorities for this provider.
7956                            p = new PackageParser.Provider(p);
7957                            p.syncable = false;
7958                        }
7959                        if (!mProvidersByAuthority.containsKey(names[j])) {
7960                            mProvidersByAuthority.put(names[j], p);
7961                            if (p.info.authority == null) {
7962                                p.info.authority = names[j];
7963                            } else {
7964                                p.info.authority = p.info.authority + ";" + names[j];
7965                            }
7966                            if (DEBUG_PACKAGE_SCANNING) {
7967                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7968                                    Log.d(TAG, "Registered content provider: " + names[j]
7969                                            + ", className = " + p.info.name + ", isSyncable = "
7970                                            + p.info.isSyncable);
7971                            }
7972                        } else {
7973                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7974                            Slog.w(TAG, "Skipping provider name " + names[j] +
7975                                    " (in package " + pkg.applicationInfo.packageName +
7976                                    "): name already used by "
7977                                    + ((other != null && other.getComponentName() != null)
7978                                            ? other.getComponentName().getPackageName() : "?"));
7979                        }
7980                    }
7981                }
7982                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7983                    if (r == null) {
7984                        r = new StringBuilder(256);
7985                    } else {
7986                        r.append(' ');
7987                    }
7988                    r.append(p.info.name);
7989                }
7990            }
7991            if (r != null) {
7992                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7993            }
7994
7995            N = pkg.services.size();
7996            r = null;
7997            for (i=0; i<N; i++) {
7998                PackageParser.Service s = pkg.services.get(i);
7999                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8000                        s.info.processName, pkg.applicationInfo.uid);
8001                mServices.addService(s);
8002                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8003                    if (r == null) {
8004                        r = new StringBuilder(256);
8005                    } else {
8006                        r.append(' ');
8007                    }
8008                    r.append(s.info.name);
8009                }
8010            }
8011            if (r != null) {
8012                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8013            }
8014
8015            N = pkg.receivers.size();
8016            r = null;
8017            for (i=0; i<N; i++) {
8018                PackageParser.Activity a = pkg.receivers.get(i);
8019                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8020                        a.info.processName, pkg.applicationInfo.uid);
8021                mReceivers.addActivity(a, "receiver");
8022                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8023                    if (r == null) {
8024                        r = new StringBuilder(256);
8025                    } else {
8026                        r.append(' ');
8027                    }
8028                    r.append(a.info.name);
8029                }
8030            }
8031            if (r != null) {
8032                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8033            }
8034
8035            N = pkg.activities.size();
8036            r = null;
8037            for (i=0; i<N; i++) {
8038                PackageParser.Activity a = pkg.activities.get(i);
8039                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8040                        a.info.processName, pkg.applicationInfo.uid);
8041                mActivities.addActivity(a, "activity");
8042                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8043                    if (r == null) {
8044                        r = new StringBuilder(256);
8045                    } else {
8046                        r.append(' ');
8047                    }
8048                    r.append(a.info.name);
8049                }
8050            }
8051            if (r != null) {
8052                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8053            }
8054
8055            N = pkg.permissionGroups.size();
8056            r = null;
8057            for (i=0; i<N; i++) {
8058                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8059                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8060                if (cur == null) {
8061                    mPermissionGroups.put(pg.info.name, pg);
8062                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8063                        if (r == null) {
8064                            r = new StringBuilder(256);
8065                        } else {
8066                            r.append(' ');
8067                        }
8068                        r.append(pg.info.name);
8069                    }
8070                } else {
8071                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8072                            + pg.info.packageName + " ignored: original from "
8073                            + cur.info.packageName);
8074                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8075                        if (r == null) {
8076                            r = new StringBuilder(256);
8077                        } else {
8078                            r.append(' ');
8079                        }
8080                        r.append("DUP:");
8081                        r.append(pg.info.name);
8082                    }
8083                }
8084            }
8085            if (r != null) {
8086                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8087            }
8088
8089            N = pkg.permissions.size();
8090            r = null;
8091            for (i=0; i<N; i++) {
8092                PackageParser.Permission p = pkg.permissions.get(i);
8093
8094                // Assume by default that we did not install this permission into the system.
8095                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8096
8097                // Now that permission groups have a special meaning, we ignore permission
8098                // groups for legacy apps to prevent unexpected behavior. In particular,
8099                // permissions for one app being granted to someone just becase they happen
8100                // to be in a group defined by another app (before this had no implications).
8101                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8102                    p.group = mPermissionGroups.get(p.info.group);
8103                    // Warn for a permission in an unknown group.
8104                    if (p.info.group != null && p.group == null) {
8105                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8106                                + p.info.packageName + " in an unknown group " + p.info.group);
8107                    }
8108                }
8109
8110                ArrayMap<String, BasePermission> permissionMap =
8111                        p.tree ? mSettings.mPermissionTrees
8112                                : mSettings.mPermissions;
8113                BasePermission bp = permissionMap.get(p.info.name);
8114
8115                // Allow system apps to redefine non-system permissions
8116                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8117                    final boolean currentOwnerIsSystem = (bp.perm != null
8118                            && isSystemApp(bp.perm.owner));
8119                    if (isSystemApp(p.owner)) {
8120                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8121                            // It's a built-in permission and no owner, take ownership now
8122                            bp.packageSetting = pkgSetting;
8123                            bp.perm = p;
8124                            bp.uid = pkg.applicationInfo.uid;
8125                            bp.sourcePackage = p.info.packageName;
8126                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8127                        } else if (!currentOwnerIsSystem) {
8128                            String msg = "New decl " + p.owner + " of permission  "
8129                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8130                            reportSettingsProblem(Log.WARN, msg);
8131                            bp = null;
8132                        }
8133                    }
8134                }
8135
8136                if (bp == null) {
8137                    bp = new BasePermission(p.info.name, p.info.packageName,
8138                            BasePermission.TYPE_NORMAL);
8139                    permissionMap.put(p.info.name, bp);
8140                }
8141
8142                if (bp.perm == null) {
8143                    if (bp.sourcePackage == null
8144                            || bp.sourcePackage.equals(p.info.packageName)) {
8145                        BasePermission tree = findPermissionTreeLP(p.info.name);
8146                        if (tree == null
8147                                || tree.sourcePackage.equals(p.info.packageName)) {
8148                            bp.packageSetting = pkgSetting;
8149                            bp.perm = p;
8150                            bp.uid = pkg.applicationInfo.uid;
8151                            bp.sourcePackage = p.info.packageName;
8152                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8153                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8154                                if (r == null) {
8155                                    r = new StringBuilder(256);
8156                                } else {
8157                                    r.append(' ');
8158                                }
8159                                r.append(p.info.name);
8160                            }
8161                        } else {
8162                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8163                                    + p.info.packageName + " ignored: base tree "
8164                                    + tree.name + " is from package "
8165                                    + tree.sourcePackage);
8166                        }
8167                    } else {
8168                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8169                                + p.info.packageName + " ignored: original from "
8170                                + bp.sourcePackage);
8171                    }
8172                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8173                    if (r == null) {
8174                        r = new StringBuilder(256);
8175                    } else {
8176                        r.append(' ');
8177                    }
8178                    r.append("DUP:");
8179                    r.append(p.info.name);
8180                }
8181                if (bp.perm == p) {
8182                    bp.protectionLevel = p.info.protectionLevel;
8183                }
8184            }
8185
8186            if (r != null) {
8187                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8188            }
8189
8190            N = pkg.instrumentation.size();
8191            r = null;
8192            for (i=0; i<N; i++) {
8193                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8194                a.info.packageName = pkg.applicationInfo.packageName;
8195                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8196                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8197                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8198                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8199                a.info.dataDir = pkg.applicationInfo.dataDir;
8200                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8201                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8202
8203                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8204                // need other information about the application, like the ABI and what not ?
8205                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8206                mInstrumentation.put(a.getComponentName(), a);
8207                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8208                    if (r == null) {
8209                        r = new StringBuilder(256);
8210                    } else {
8211                        r.append(' ');
8212                    }
8213                    r.append(a.info.name);
8214                }
8215            }
8216            if (r != null) {
8217                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8218            }
8219
8220            if (pkg.protectedBroadcasts != null) {
8221                N = pkg.protectedBroadcasts.size();
8222                for (i=0; i<N; i++) {
8223                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8224                }
8225            }
8226
8227            pkgSetting.setTimeStamp(scanFileTime);
8228
8229            // Create idmap files for pairs of (packages, overlay packages).
8230            // Note: "android", ie framework-res.apk, is handled by native layers.
8231            if (pkg.mOverlayTarget != null) {
8232                // This is an overlay package.
8233                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8234                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8235                        mOverlays.put(pkg.mOverlayTarget,
8236                                new ArrayMap<String, PackageParser.Package>());
8237                    }
8238                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8239                    map.put(pkg.packageName, pkg);
8240                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8241                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8242                        createIdmapFailed = true;
8243                    }
8244                }
8245            } else if (mOverlays.containsKey(pkg.packageName) &&
8246                    !pkg.packageName.equals("android")) {
8247                // This is a regular package, with one or more known overlay packages.
8248                createIdmapsForPackageLI(pkg);
8249            }
8250        }
8251
8252        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8253
8254        if (createIdmapFailed) {
8255            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8256                    "scanPackageLI failed to createIdmap");
8257        }
8258        return pkg;
8259    }
8260
8261    /**
8262     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8263     * is derived purely on the basis of the contents of {@code scanFile} and
8264     * {@code cpuAbiOverride}.
8265     *
8266     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8267     */
8268    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8269                                 String cpuAbiOverride, boolean extractLibs)
8270            throws PackageManagerException {
8271        // TODO: We can probably be smarter about this stuff. For installed apps,
8272        // we can calculate this information at install time once and for all. For
8273        // system apps, we can probably assume that this information doesn't change
8274        // after the first boot scan. As things stand, we do lots of unnecessary work.
8275
8276        // Give ourselves some initial paths; we'll come back for another
8277        // pass once we've determined ABI below.
8278        setNativeLibraryPaths(pkg);
8279
8280        // We would never need to extract libs for forward-locked and external packages,
8281        // since the container service will do it for us. We shouldn't attempt to
8282        // extract libs from system app when it was not updated.
8283        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8284                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8285            extractLibs = false;
8286        }
8287
8288        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8289        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8290
8291        NativeLibraryHelper.Handle handle = null;
8292        try {
8293            handle = NativeLibraryHelper.Handle.create(pkg);
8294            // TODO(multiArch): This can be null for apps that didn't go through the
8295            // usual installation process. We can calculate it again, like we
8296            // do during install time.
8297            //
8298            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8299            // unnecessary.
8300            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8301
8302            // Null out the abis so that they can be recalculated.
8303            pkg.applicationInfo.primaryCpuAbi = null;
8304            pkg.applicationInfo.secondaryCpuAbi = null;
8305            if (isMultiArch(pkg.applicationInfo)) {
8306                // Warn if we've set an abiOverride for multi-lib packages..
8307                // By definition, we need to copy both 32 and 64 bit libraries for
8308                // such packages.
8309                if (pkg.cpuAbiOverride != null
8310                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8311                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8312                }
8313
8314                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8315                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8316                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8317                    if (extractLibs) {
8318                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8319                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8320                                useIsaSpecificSubdirs);
8321                    } else {
8322                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8323                    }
8324                }
8325
8326                maybeThrowExceptionForMultiArchCopy(
8327                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8328
8329                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8330                    if (extractLibs) {
8331                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8332                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8333                                useIsaSpecificSubdirs);
8334                    } else {
8335                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8336                    }
8337                }
8338
8339                maybeThrowExceptionForMultiArchCopy(
8340                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8341
8342                if (abi64 >= 0) {
8343                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8344                }
8345
8346                if (abi32 >= 0) {
8347                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8348                    if (abi64 >= 0) {
8349                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8350                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8351                            pkg.applicationInfo.primaryCpuAbi = abi;
8352                        } else {
8353                            pkg.applicationInfo.secondaryCpuAbi = abi;
8354                        }
8355                    } else {
8356                        pkg.applicationInfo.primaryCpuAbi = abi;
8357                    }
8358                }
8359
8360            } else {
8361                String[] abiList = (cpuAbiOverride != null) ?
8362                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8363
8364                // Enable gross and lame hacks for apps that are built with old
8365                // SDK tools. We must scan their APKs for renderscript bitcode and
8366                // not launch them if it's present. Don't bother checking on devices
8367                // that don't have 64 bit support.
8368                boolean needsRenderScriptOverride = false;
8369                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8370                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8371                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8372                    needsRenderScriptOverride = true;
8373                }
8374
8375                final int copyRet;
8376                if (extractLibs) {
8377                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8378                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8379                } else {
8380                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8381                }
8382
8383                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8384                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8385                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8386                }
8387
8388                if (copyRet >= 0) {
8389                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8390                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8391                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8392                } else if (needsRenderScriptOverride) {
8393                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8394                }
8395            }
8396        } catch (IOException ioe) {
8397            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8398        } finally {
8399            IoUtils.closeQuietly(handle);
8400        }
8401
8402        // Now that we've calculated the ABIs and determined if it's an internal app,
8403        // we will go ahead and populate the nativeLibraryPath.
8404        setNativeLibraryPaths(pkg);
8405    }
8406
8407    /**
8408     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8409     * i.e, so that all packages can be run inside a single process if required.
8410     *
8411     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8412     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8413     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8414     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8415     * updating a package that belongs to a shared user.
8416     *
8417     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8418     * adds unnecessary complexity.
8419     */
8420    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8421            PackageParser.Package scannedPackage, boolean bootComplete) {
8422        String requiredInstructionSet = null;
8423        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8424            requiredInstructionSet = VMRuntime.getInstructionSet(
8425                     scannedPackage.applicationInfo.primaryCpuAbi);
8426        }
8427
8428        PackageSetting requirer = null;
8429        for (PackageSetting ps : packagesForUser) {
8430            // If packagesForUser contains scannedPackage, we skip it. This will happen
8431            // when scannedPackage is an update of an existing package. Without this check,
8432            // we will never be able to change the ABI of any package belonging to a shared
8433            // user, even if it's compatible with other packages.
8434            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8435                if (ps.primaryCpuAbiString == null) {
8436                    continue;
8437                }
8438
8439                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8440                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8441                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8442                    // this but there's not much we can do.
8443                    String errorMessage = "Instruction set mismatch, "
8444                            + ((requirer == null) ? "[caller]" : requirer)
8445                            + " requires " + requiredInstructionSet + " whereas " + ps
8446                            + " requires " + instructionSet;
8447                    Slog.w(TAG, errorMessage);
8448                }
8449
8450                if (requiredInstructionSet == null) {
8451                    requiredInstructionSet = instructionSet;
8452                    requirer = ps;
8453                }
8454            }
8455        }
8456
8457        if (requiredInstructionSet != null) {
8458            String adjustedAbi;
8459            if (requirer != null) {
8460                // requirer != null implies that either scannedPackage was null or that scannedPackage
8461                // did not require an ABI, in which case we have to adjust scannedPackage to match
8462                // the ABI of the set (which is the same as requirer's ABI)
8463                adjustedAbi = requirer.primaryCpuAbiString;
8464                if (scannedPackage != null) {
8465                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8466                }
8467            } else {
8468                // requirer == null implies that we're updating all ABIs in the set to
8469                // match scannedPackage.
8470                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8471            }
8472
8473            for (PackageSetting ps : packagesForUser) {
8474                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8475                    if (ps.primaryCpuAbiString != null) {
8476                        continue;
8477                    }
8478
8479                    ps.primaryCpuAbiString = adjustedAbi;
8480                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8481                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8482                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8483                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8484                                + " (requirer="
8485                                + (requirer == null ? "null" : requirer.pkg.packageName)
8486                                + ", scannedPackage="
8487                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8488                                + ")");
8489                        try {
8490                            mInstaller.rmdex(ps.codePathString,
8491                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8492                        } catch (InstallerException ignored) {
8493                        }
8494                    }
8495                }
8496            }
8497        }
8498    }
8499
8500    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8501        synchronized (mPackages) {
8502            mResolverReplaced = true;
8503            // Set up information for custom user intent resolution activity.
8504            mResolveActivity.applicationInfo = pkg.applicationInfo;
8505            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8506            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8507            mResolveActivity.processName = pkg.applicationInfo.packageName;
8508            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8509            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8510                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8511            mResolveActivity.theme = 0;
8512            mResolveActivity.exported = true;
8513            mResolveActivity.enabled = true;
8514            mResolveInfo.activityInfo = mResolveActivity;
8515            mResolveInfo.priority = 0;
8516            mResolveInfo.preferredOrder = 0;
8517            mResolveInfo.match = 0;
8518            mResolveComponentName = mCustomResolverComponentName;
8519            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8520                    mResolveComponentName);
8521        }
8522    }
8523
8524    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8525        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8526
8527        // Set up information for ephemeral installer activity
8528        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8529        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8530        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8531        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8532        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8533        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8534                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8535        mEphemeralInstallerActivity.theme = 0;
8536        mEphemeralInstallerActivity.exported = true;
8537        mEphemeralInstallerActivity.enabled = true;
8538        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8539        mEphemeralInstallerInfo.priority = 0;
8540        mEphemeralInstallerInfo.preferredOrder = 0;
8541        mEphemeralInstallerInfo.match = 0;
8542
8543        if (DEBUG_EPHEMERAL) {
8544            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8545        }
8546    }
8547
8548    private static String calculateBundledApkRoot(final String codePathString) {
8549        final File codePath = new File(codePathString);
8550        final File codeRoot;
8551        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8552            codeRoot = Environment.getRootDirectory();
8553        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8554            codeRoot = Environment.getOemDirectory();
8555        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8556            codeRoot = Environment.getVendorDirectory();
8557        } else {
8558            // Unrecognized code path; take its top real segment as the apk root:
8559            // e.g. /something/app/blah.apk => /something
8560            try {
8561                File f = codePath.getCanonicalFile();
8562                File parent = f.getParentFile();    // non-null because codePath is a file
8563                File tmp;
8564                while ((tmp = parent.getParentFile()) != null) {
8565                    f = parent;
8566                    parent = tmp;
8567                }
8568                codeRoot = f;
8569                Slog.w(TAG, "Unrecognized code path "
8570                        + codePath + " - using " + codeRoot);
8571            } catch (IOException e) {
8572                // Can't canonicalize the code path -- shenanigans?
8573                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8574                return Environment.getRootDirectory().getPath();
8575            }
8576        }
8577        return codeRoot.getPath();
8578    }
8579
8580    /**
8581     * Derive and set the location of native libraries for the given package,
8582     * which varies depending on where and how the package was installed.
8583     */
8584    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8585        final ApplicationInfo info = pkg.applicationInfo;
8586        final String codePath = pkg.codePath;
8587        final File codeFile = new File(codePath);
8588        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8589        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8590
8591        info.nativeLibraryRootDir = null;
8592        info.nativeLibraryRootRequiresIsa = false;
8593        info.nativeLibraryDir = null;
8594        info.secondaryNativeLibraryDir = null;
8595
8596        if (isApkFile(codeFile)) {
8597            // Monolithic install
8598            if (bundledApp) {
8599                // If "/system/lib64/apkname" exists, assume that is the per-package
8600                // native library directory to use; otherwise use "/system/lib/apkname".
8601                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8602                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8603                        getPrimaryInstructionSet(info));
8604
8605                // This is a bundled system app so choose the path based on the ABI.
8606                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8607                // is just the default path.
8608                final String apkName = deriveCodePathName(codePath);
8609                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8610                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8611                        apkName).getAbsolutePath();
8612
8613                if (info.secondaryCpuAbi != null) {
8614                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8615                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8616                            secondaryLibDir, apkName).getAbsolutePath();
8617                }
8618            } else if (asecApp) {
8619                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8620                        .getAbsolutePath();
8621            } else {
8622                final String apkName = deriveCodePathName(codePath);
8623                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8624                        .getAbsolutePath();
8625            }
8626
8627            info.nativeLibraryRootRequiresIsa = false;
8628            info.nativeLibraryDir = info.nativeLibraryRootDir;
8629        } else {
8630            // Cluster install
8631            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8632            info.nativeLibraryRootRequiresIsa = true;
8633
8634            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8635                    getPrimaryInstructionSet(info)).getAbsolutePath();
8636
8637            if (info.secondaryCpuAbi != null) {
8638                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8639                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8640            }
8641        }
8642    }
8643
8644    /**
8645     * Calculate the abis and roots for a bundled app. These can uniquely
8646     * be determined from the contents of the system partition, i.e whether
8647     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8648     * of this information, and instead assume that the system was built
8649     * sensibly.
8650     */
8651    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8652                                           PackageSetting pkgSetting) {
8653        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8654
8655        // If "/system/lib64/apkname" exists, assume that is the per-package
8656        // native library directory to use; otherwise use "/system/lib/apkname".
8657        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8658        setBundledAppAbi(pkg, apkRoot, apkName);
8659        // pkgSetting might be null during rescan following uninstall of updates
8660        // to a bundled app, so accommodate that possibility.  The settings in
8661        // that case will be established later from the parsed package.
8662        //
8663        // If the settings aren't null, sync them up with what we've just derived.
8664        // note that apkRoot isn't stored in the package settings.
8665        if (pkgSetting != null) {
8666            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8667            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8668        }
8669    }
8670
8671    /**
8672     * Deduces the ABI of a bundled app and sets the relevant fields on the
8673     * parsed pkg object.
8674     *
8675     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8676     *        under which system libraries are installed.
8677     * @param apkName the name of the installed package.
8678     */
8679    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8680        final File codeFile = new File(pkg.codePath);
8681
8682        final boolean has64BitLibs;
8683        final boolean has32BitLibs;
8684        if (isApkFile(codeFile)) {
8685            // Monolithic install
8686            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8687            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8688        } else {
8689            // Cluster install
8690            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8691            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8692                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8693                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8694                has64BitLibs = (new File(rootDir, isa)).exists();
8695            } else {
8696                has64BitLibs = false;
8697            }
8698            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8699                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8700                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8701                has32BitLibs = (new File(rootDir, isa)).exists();
8702            } else {
8703                has32BitLibs = false;
8704            }
8705        }
8706
8707        if (has64BitLibs && !has32BitLibs) {
8708            // The package has 64 bit libs, but not 32 bit libs. Its primary
8709            // ABI should be 64 bit. We can safely assume here that the bundled
8710            // native libraries correspond to the most preferred ABI in the list.
8711
8712            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8713            pkg.applicationInfo.secondaryCpuAbi = null;
8714        } else if (has32BitLibs && !has64BitLibs) {
8715            // The package has 32 bit libs but not 64 bit libs. Its primary
8716            // ABI should be 32 bit.
8717
8718            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8719            pkg.applicationInfo.secondaryCpuAbi = null;
8720        } else if (has32BitLibs && has64BitLibs) {
8721            // The application has both 64 and 32 bit bundled libraries. We check
8722            // here that the app declares multiArch support, and warn if it doesn't.
8723            //
8724            // We will be lenient here and record both ABIs. The primary will be the
8725            // ABI that's higher on the list, i.e, a device that's configured to prefer
8726            // 64 bit apps will see a 64 bit primary ABI,
8727
8728            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8729                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8730            }
8731
8732            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8733                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8734                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8735            } else {
8736                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8737                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8738            }
8739        } else {
8740            pkg.applicationInfo.primaryCpuAbi = null;
8741            pkg.applicationInfo.secondaryCpuAbi = null;
8742        }
8743    }
8744
8745    private void killPackage(PackageParser.Package pkg, String reason) {
8746        // Kill the parent package
8747        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8748        // Kill the child packages
8749        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8750        for (int i = 0; i < childCount; i++) {
8751            PackageParser.Package childPkg = pkg.childPackages.get(i);
8752            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8753        }
8754    }
8755
8756    private void killApplication(String pkgName, int appId, String reason) {
8757        // Request the ActivityManager to kill the process(only for existing packages)
8758        // so that we do not end up in a confused state while the user is still using the older
8759        // version of the application while the new one gets installed.
8760        IActivityManager am = ActivityManagerNative.getDefault();
8761        if (am != null) {
8762            try {
8763                am.killApplicationWithAppId(pkgName, appId, reason);
8764            } catch (RemoteException e) {
8765            }
8766        }
8767    }
8768
8769    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8770        // Remove the parent package setting
8771        PackageSetting ps = (PackageSetting) pkg.mExtras;
8772        if (ps != null) {
8773            removePackageLI(ps, chatty);
8774        }
8775        // Remove the child package setting
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            ps = (PackageSetting) childPkg.mExtras;
8780            if (ps != null) {
8781                removePackageLI(ps, chatty);
8782            }
8783        }
8784    }
8785
8786    void removePackageLI(PackageSetting ps, boolean chatty) {
8787        if (DEBUG_INSTALL) {
8788            if (chatty)
8789                Log.d(TAG, "Removing package " + ps.name);
8790        }
8791
8792        // writer
8793        synchronized (mPackages) {
8794            mPackages.remove(ps.name);
8795            final PackageParser.Package pkg = ps.pkg;
8796            if (pkg != null) {
8797                cleanPackageDataStructuresLILPw(pkg, chatty);
8798            }
8799        }
8800    }
8801
8802    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8803        if (DEBUG_INSTALL) {
8804            if (chatty)
8805                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8806        }
8807
8808        // writer
8809        synchronized (mPackages) {
8810            // Remove the parent package
8811            mPackages.remove(pkg.applicationInfo.packageName);
8812            cleanPackageDataStructuresLILPw(pkg, chatty);
8813
8814            // Remove the child packages
8815            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8816            for (int i = 0; i < childCount; i++) {
8817                PackageParser.Package childPkg = pkg.childPackages.get(i);
8818                mPackages.remove(childPkg.applicationInfo.packageName);
8819                cleanPackageDataStructuresLILPw(childPkg, chatty);
8820            }
8821        }
8822    }
8823
8824    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8825        int N = pkg.providers.size();
8826        StringBuilder r = null;
8827        int i;
8828        for (i=0; i<N; i++) {
8829            PackageParser.Provider p = pkg.providers.get(i);
8830            mProviders.removeProvider(p);
8831            if (p.info.authority == null) {
8832
8833                /* There was another ContentProvider with this authority when
8834                 * this app was installed so this authority is null,
8835                 * Ignore it as we don't have to unregister the provider.
8836                 */
8837                continue;
8838            }
8839            String names[] = p.info.authority.split(";");
8840            for (int j = 0; j < names.length; j++) {
8841                if (mProvidersByAuthority.get(names[j]) == p) {
8842                    mProvidersByAuthority.remove(names[j]);
8843                    if (DEBUG_REMOVE) {
8844                        if (chatty)
8845                            Log.d(TAG, "Unregistered content provider: " + names[j]
8846                                    + ", className = " + p.info.name + ", isSyncable = "
8847                                    + p.info.isSyncable);
8848                    }
8849                }
8850            }
8851            if (DEBUG_REMOVE && chatty) {
8852                if (r == null) {
8853                    r = new StringBuilder(256);
8854                } else {
8855                    r.append(' ');
8856                }
8857                r.append(p.info.name);
8858            }
8859        }
8860        if (r != null) {
8861            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8862        }
8863
8864        N = pkg.services.size();
8865        r = null;
8866        for (i=0; i<N; i++) {
8867            PackageParser.Service s = pkg.services.get(i);
8868            mServices.removeService(s);
8869            if (chatty) {
8870                if (r == null) {
8871                    r = new StringBuilder(256);
8872                } else {
8873                    r.append(' ');
8874                }
8875                r.append(s.info.name);
8876            }
8877        }
8878        if (r != null) {
8879            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8880        }
8881
8882        N = pkg.receivers.size();
8883        r = null;
8884        for (i=0; i<N; i++) {
8885            PackageParser.Activity a = pkg.receivers.get(i);
8886            mReceivers.removeActivity(a, "receiver");
8887            if (DEBUG_REMOVE && chatty) {
8888                if (r == null) {
8889                    r = new StringBuilder(256);
8890                } else {
8891                    r.append(' ');
8892                }
8893                r.append(a.info.name);
8894            }
8895        }
8896        if (r != null) {
8897            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8898        }
8899
8900        N = pkg.activities.size();
8901        r = null;
8902        for (i=0; i<N; i++) {
8903            PackageParser.Activity a = pkg.activities.get(i);
8904            mActivities.removeActivity(a, "activity");
8905            if (DEBUG_REMOVE && chatty) {
8906                if (r == null) {
8907                    r = new StringBuilder(256);
8908                } else {
8909                    r.append(' ');
8910                }
8911                r.append(a.info.name);
8912            }
8913        }
8914        if (r != null) {
8915            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8916        }
8917
8918        N = pkg.permissions.size();
8919        r = null;
8920        for (i=0; i<N; i++) {
8921            PackageParser.Permission p = pkg.permissions.get(i);
8922            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8923            if (bp == null) {
8924                bp = mSettings.mPermissionTrees.get(p.info.name);
8925            }
8926            if (bp != null && bp.perm == p) {
8927                bp.perm = null;
8928                if (DEBUG_REMOVE && chatty) {
8929                    if (r == null) {
8930                        r = new StringBuilder(256);
8931                    } else {
8932                        r.append(' ');
8933                    }
8934                    r.append(p.info.name);
8935                }
8936            }
8937            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8938                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8939                if (appOpPkgs != null) {
8940                    appOpPkgs.remove(pkg.packageName);
8941                }
8942            }
8943        }
8944        if (r != null) {
8945            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8946        }
8947
8948        N = pkg.requestedPermissions.size();
8949        r = null;
8950        for (i=0; i<N; i++) {
8951            String perm = pkg.requestedPermissions.get(i);
8952            BasePermission bp = mSettings.mPermissions.get(perm);
8953            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8954                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8955                if (appOpPkgs != null) {
8956                    appOpPkgs.remove(pkg.packageName);
8957                    if (appOpPkgs.isEmpty()) {
8958                        mAppOpPermissionPackages.remove(perm);
8959                    }
8960                }
8961            }
8962        }
8963        if (r != null) {
8964            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8965        }
8966
8967        N = pkg.instrumentation.size();
8968        r = null;
8969        for (i=0; i<N; i++) {
8970            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8971            mInstrumentation.remove(a.getComponentName());
8972            if (DEBUG_REMOVE && chatty) {
8973                if (r == null) {
8974                    r = new StringBuilder(256);
8975                } else {
8976                    r.append(' ');
8977                }
8978                r.append(a.info.name);
8979            }
8980        }
8981        if (r != null) {
8982            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8983        }
8984
8985        r = null;
8986        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8987            // Only system apps can hold shared libraries.
8988            if (pkg.libraryNames != null) {
8989                for (i=0; i<pkg.libraryNames.size(); i++) {
8990                    String name = pkg.libraryNames.get(i);
8991                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8992                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8993                        mSharedLibraries.remove(name);
8994                        if (DEBUG_REMOVE && chatty) {
8995                            if (r == null) {
8996                                r = new StringBuilder(256);
8997                            } else {
8998                                r.append(' ');
8999                            }
9000                            r.append(name);
9001                        }
9002                    }
9003                }
9004            }
9005        }
9006        if (r != null) {
9007            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9008        }
9009    }
9010
9011    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9012        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9013            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9014                return true;
9015            }
9016        }
9017        return false;
9018    }
9019
9020    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9021    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9022    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9023
9024    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9025        // Update the parent permissions
9026        updatePermissionsLPw(pkg.packageName, pkg, flags);
9027        // Update the child permissions
9028        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9029        for (int i = 0; i < childCount; i++) {
9030            PackageParser.Package childPkg = pkg.childPackages.get(i);
9031            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9032        }
9033    }
9034
9035    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9036            int flags) {
9037        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9038        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9039    }
9040
9041    private void updatePermissionsLPw(String changingPkg,
9042            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9043        // Make sure there are no dangling permission trees.
9044        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9045        while (it.hasNext()) {
9046            final BasePermission bp = it.next();
9047            if (bp.packageSetting == null) {
9048                // We may not yet have parsed the package, so just see if
9049                // we still know about its settings.
9050                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9051            }
9052            if (bp.packageSetting == null) {
9053                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9054                        + " from package " + bp.sourcePackage);
9055                it.remove();
9056            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9057                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9058                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9059                            + " from package " + bp.sourcePackage);
9060                    flags |= UPDATE_PERMISSIONS_ALL;
9061                    it.remove();
9062                }
9063            }
9064        }
9065
9066        // Make sure all dynamic permissions have been assigned to a package,
9067        // and make sure there are no dangling permissions.
9068        it = mSettings.mPermissions.values().iterator();
9069        while (it.hasNext()) {
9070            final BasePermission bp = it.next();
9071            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9072                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9073                        + bp.name + " pkg=" + bp.sourcePackage
9074                        + " info=" + bp.pendingInfo);
9075                if (bp.packageSetting == null && bp.pendingInfo != null) {
9076                    final BasePermission tree = findPermissionTreeLP(bp.name);
9077                    if (tree != null && tree.perm != null) {
9078                        bp.packageSetting = tree.packageSetting;
9079                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9080                                new PermissionInfo(bp.pendingInfo));
9081                        bp.perm.info.packageName = tree.perm.info.packageName;
9082                        bp.perm.info.name = bp.name;
9083                        bp.uid = tree.uid;
9084                    }
9085                }
9086            }
9087            if (bp.packageSetting == null) {
9088                // We may not yet have parsed the package, so just see if
9089                // we still know about its settings.
9090                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9091            }
9092            if (bp.packageSetting == null) {
9093                Slog.w(TAG, "Removing dangling permission: " + bp.name
9094                        + " from package " + bp.sourcePackage);
9095                it.remove();
9096            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9097                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9098                    Slog.i(TAG, "Removing old permission: " + bp.name
9099                            + " from package " + bp.sourcePackage);
9100                    flags |= UPDATE_PERMISSIONS_ALL;
9101                    it.remove();
9102                }
9103            }
9104        }
9105
9106        // Now update the permissions for all packages, in particular
9107        // replace the granted permissions of the system packages.
9108        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9109            for (PackageParser.Package pkg : mPackages.values()) {
9110                if (pkg != pkgInfo) {
9111                    // Only replace for packages on requested volume
9112                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9113                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9114                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9115                    grantPermissionsLPw(pkg, replace, changingPkg);
9116                }
9117            }
9118        }
9119
9120        if (pkgInfo != null) {
9121            // Only replace for packages on requested volume
9122            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9123            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9124                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9125            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9126        }
9127    }
9128
9129    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9130            String packageOfInterest) {
9131        // IMPORTANT: There are two types of permissions: install and runtime.
9132        // Install time permissions are granted when the app is installed to
9133        // all device users and users added in the future. Runtime permissions
9134        // are granted at runtime explicitly to specific users. Normal and signature
9135        // protected permissions are install time permissions. Dangerous permissions
9136        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9137        // otherwise they are runtime permissions. This function does not manage
9138        // runtime permissions except for the case an app targeting Lollipop MR1
9139        // being upgraded to target a newer SDK, in which case dangerous permissions
9140        // are transformed from install time to runtime ones.
9141
9142        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9143        if (ps == null) {
9144            return;
9145        }
9146
9147        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9148
9149        PermissionsState permissionsState = ps.getPermissionsState();
9150        PermissionsState origPermissions = permissionsState;
9151
9152        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9153
9154        boolean runtimePermissionsRevoked = false;
9155        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9156
9157        boolean changedInstallPermission = false;
9158
9159        if (replace) {
9160            ps.installPermissionsFixed = false;
9161            if (!ps.isSharedUser()) {
9162                origPermissions = new PermissionsState(permissionsState);
9163                permissionsState.reset();
9164            } else {
9165                // We need to know only about runtime permission changes since the
9166                // calling code always writes the install permissions state but
9167                // the runtime ones are written only if changed. The only cases of
9168                // changed runtime permissions here are promotion of an install to
9169                // runtime and revocation of a runtime from a shared user.
9170                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9171                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9172                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9173                    runtimePermissionsRevoked = true;
9174                }
9175            }
9176        }
9177
9178        permissionsState.setGlobalGids(mGlobalGids);
9179
9180        final int N = pkg.requestedPermissions.size();
9181        for (int i=0; i<N; i++) {
9182            final String name = pkg.requestedPermissions.get(i);
9183            final BasePermission bp = mSettings.mPermissions.get(name);
9184
9185            if (DEBUG_INSTALL) {
9186                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9187            }
9188
9189            if (bp == null || bp.packageSetting == null) {
9190                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9191                    Slog.w(TAG, "Unknown permission " + name
9192                            + " in package " + pkg.packageName);
9193                }
9194                continue;
9195            }
9196
9197            final String perm = bp.name;
9198            boolean allowedSig = false;
9199            int grant = GRANT_DENIED;
9200
9201            // Keep track of app op permissions.
9202            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9203                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9204                if (pkgs == null) {
9205                    pkgs = new ArraySet<>();
9206                    mAppOpPermissionPackages.put(bp.name, pkgs);
9207                }
9208                pkgs.add(pkg.packageName);
9209            }
9210
9211            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9212            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9213                    >= Build.VERSION_CODES.M;
9214            switch (level) {
9215                case PermissionInfo.PROTECTION_NORMAL: {
9216                    // For all apps normal permissions are install time ones.
9217                    grant = GRANT_INSTALL;
9218                } break;
9219
9220                case PermissionInfo.PROTECTION_DANGEROUS: {
9221                    // If a permission review is required for legacy apps we represent
9222                    // their permissions as always granted runtime ones since we need
9223                    // to keep the review required permission flag per user while an
9224                    // install permission's state is shared across all users.
9225                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9226                        // For legacy apps dangerous permissions are install time ones.
9227                        grant = GRANT_INSTALL;
9228                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9229                        // For legacy apps that became modern, install becomes runtime.
9230                        grant = GRANT_UPGRADE;
9231                    } else if (mPromoteSystemApps
9232                            && isSystemApp(ps)
9233                            && mExistingSystemPackages.contains(ps.name)) {
9234                        // For legacy system apps, install becomes runtime.
9235                        // We cannot check hasInstallPermission() for system apps since those
9236                        // permissions were granted implicitly and not persisted pre-M.
9237                        grant = GRANT_UPGRADE;
9238                    } else {
9239                        // For modern apps keep runtime permissions unchanged.
9240                        grant = GRANT_RUNTIME;
9241                    }
9242                } break;
9243
9244                case PermissionInfo.PROTECTION_SIGNATURE: {
9245                    // For all apps signature permissions are install time ones.
9246                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9247                    if (allowedSig) {
9248                        grant = GRANT_INSTALL;
9249                    }
9250                } break;
9251            }
9252
9253            if (DEBUG_INSTALL) {
9254                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9255            }
9256
9257            if (grant != GRANT_DENIED) {
9258                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9259                    // If this is an existing, non-system package, then
9260                    // we can't add any new permissions to it.
9261                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9262                        // Except...  if this is a permission that was added
9263                        // to the platform (note: need to only do this when
9264                        // updating the platform).
9265                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9266                            grant = GRANT_DENIED;
9267                        }
9268                    }
9269                }
9270
9271                switch (grant) {
9272                    case GRANT_INSTALL: {
9273                        // Revoke this as runtime permission to handle the case of
9274                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9275                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9276                            if (origPermissions.getRuntimePermissionState(
9277                                    bp.name, userId) != null) {
9278                                // Revoke the runtime permission and clear the flags.
9279                                origPermissions.revokeRuntimePermission(bp, userId);
9280                                origPermissions.updatePermissionFlags(bp, userId,
9281                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9282                                // If we revoked a permission permission, we have to write.
9283                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9284                                        changedRuntimePermissionUserIds, userId);
9285                            }
9286                        }
9287                        // Grant an install permission.
9288                        if (permissionsState.grantInstallPermission(bp) !=
9289                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9290                            changedInstallPermission = true;
9291                        }
9292                    } break;
9293
9294                    case GRANT_RUNTIME: {
9295                        // Grant previously granted runtime permissions.
9296                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9297                            PermissionState permissionState = origPermissions
9298                                    .getRuntimePermissionState(bp.name, userId);
9299                            int flags = permissionState != null
9300                                    ? permissionState.getFlags() : 0;
9301                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9302                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9303                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9304                                    // If we cannot put the permission as it was, we have to write.
9305                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9306                                            changedRuntimePermissionUserIds, userId);
9307                                }
9308                                // If the app supports runtime permissions no need for a review.
9309                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9310                                        && appSupportsRuntimePermissions
9311                                        && (flags & PackageManager
9312                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9313                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9314                                    // Since we changed the flags, we have to write.
9315                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9316                                            changedRuntimePermissionUserIds, userId);
9317                                }
9318                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9319                                    && !appSupportsRuntimePermissions) {
9320                                // For legacy apps that need a permission review, every new
9321                                // runtime permission is granted but it is pending a review.
9322                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9323                                    permissionsState.grantRuntimePermission(bp, userId);
9324                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9325                                    // We changed the permission and flags, hence have to write.
9326                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9327                                            changedRuntimePermissionUserIds, userId);
9328                                }
9329                            }
9330                            // Propagate the permission flags.
9331                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9332                        }
9333                    } break;
9334
9335                    case GRANT_UPGRADE: {
9336                        // Grant runtime permissions for a previously held install permission.
9337                        PermissionState permissionState = origPermissions
9338                                .getInstallPermissionState(bp.name);
9339                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9340
9341                        if (origPermissions.revokeInstallPermission(bp)
9342                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9343                            // We will be transferring the permission flags, so clear them.
9344                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9345                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9346                            changedInstallPermission = true;
9347                        }
9348
9349                        // If the permission is not to be promoted to runtime we ignore it and
9350                        // also its other flags as they are not applicable to install permissions.
9351                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9352                            for (int userId : currentUserIds) {
9353                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9354                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9355                                    // Transfer the permission flags.
9356                                    permissionsState.updatePermissionFlags(bp, userId,
9357                                            flags, flags);
9358                                    // If we granted the permission, we have to write.
9359                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9360                                            changedRuntimePermissionUserIds, userId);
9361                                }
9362                            }
9363                        }
9364                    } break;
9365
9366                    default: {
9367                        if (packageOfInterest == null
9368                                || packageOfInterest.equals(pkg.packageName)) {
9369                            Slog.w(TAG, "Not granting permission " + perm
9370                                    + " to package " + pkg.packageName
9371                                    + " because it was previously installed without");
9372                        }
9373                    } break;
9374                }
9375            } else {
9376                if (permissionsState.revokeInstallPermission(bp) !=
9377                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9378                    // Also drop the permission flags.
9379                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9380                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9381                    changedInstallPermission = true;
9382                    Slog.i(TAG, "Un-granting permission " + perm
9383                            + " from package " + pkg.packageName
9384                            + " (protectionLevel=" + bp.protectionLevel
9385                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9386                            + ")");
9387                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9388                    // Don't print warning for app op permissions, since it is fine for them
9389                    // not to be granted, there is a UI for the user to decide.
9390                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9391                        Slog.w(TAG, "Not granting permission " + perm
9392                                + " to package " + pkg.packageName
9393                                + " (protectionLevel=" + bp.protectionLevel
9394                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9395                                + ")");
9396                    }
9397                }
9398            }
9399        }
9400
9401        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9402                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9403            // This is the first that we have heard about this package, so the
9404            // permissions we have now selected are fixed until explicitly
9405            // changed.
9406            ps.installPermissionsFixed = true;
9407        }
9408
9409        // Persist the runtime permissions state for users with changes. If permissions
9410        // were revoked because no app in the shared user declares them we have to
9411        // write synchronously to avoid losing runtime permissions state.
9412        for (int userId : changedRuntimePermissionUserIds) {
9413            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9414        }
9415
9416        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9417    }
9418
9419    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9420        boolean allowed = false;
9421        final int NP = PackageParser.NEW_PERMISSIONS.length;
9422        for (int ip=0; ip<NP; ip++) {
9423            final PackageParser.NewPermissionInfo npi
9424                    = PackageParser.NEW_PERMISSIONS[ip];
9425            if (npi.name.equals(perm)
9426                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9427                allowed = true;
9428                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9429                        + pkg.packageName);
9430                break;
9431            }
9432        }
9433        return allowed;
9434    }
9435
9436    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9437            BasePermission bp, PermissionsState origPermissions) {
9438        boolean allowed;
9439        allowed = (compareSignatures(
9440                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9441                        == PackageManager.SIGNATURE_MATCH)
9442                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9443                        == PackageManager.SIGNATURE_MATCH);
9444        if (!allowed && (bp.protectionLevel
9445                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9446            if (isSystemApp(pkg)) {
9447                // For updated system applications, a system permission
9448                // is granted only if it had been defined by the original application.
9449                if (pkg.isUpdatedSystemApp()) {
9450                    final PackageSetting sysPs = mSettings
9451                            .getDisabledSystemPkgLPr(pkg.packageName);
9452                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9453                        // If the original was granted this permission, we take
9454                        // that grant decision as read and propagate it to the
9455                        // update.
9456                        if (sysPs.isPrivileged()) {
9457                            allowed = true;
9458                        }
9459                    } else {
9460                        // The system apk may have been updated with an older
9461                        // version of the one on the data partition, but which
9462                        // granted a new system permission that it didn't have
9463                        // before.  In this case we do want to allow the app to
9464                        // now get the new permission if the ancestral apk is
9465                        // privileged to get it.
9466                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9467                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9468                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9469                                    allowed = true;
9470                                    break;
9471                                }
9472                            }
9473                        }
9474                        // Also if a privileged parent package on the system image or any of
9475                        // its children requested a privileged permission, the updated child
9476                        // packages can also get the permission.
9477                        if (pkg.parentPackage != null) {
9478                            final PackageSetting disabledSysParentPs = mSettings
9479                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9480                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9481                                    && disabledSysParentPs.isPrivileged()) {
9482                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9483                                    allowed = true;
9484                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9485                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9486                                    for (int i = 0; i < count; i++) {
9487                                        PackageParser.Package disabledSysChildPkg =
9488                                                disabledSysParentPs.pkg.childPackages.get(i);
9489                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9490                                                perm)) {
9491                                            allowed = true;
9492                                            break;
9493                                        }
9494                                    }
9495                                }
9496                            }
9497                        }
9498                    }
9499                } else {
9500                    allowed = isPrivilegedApp(pkg);
9501                }
9502            }
9503        }
9504        if (!allowed) {
9505            if (!allowed && (bp.protectionLevel
9506                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9507                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9508                // If this was a previously normal/dangerous permission that got moved
9509                // to a system permission as part of the runtime permission redesign, then
9510                // we still want to blindly grant it to old apps.
9511                allowed = true;
9512            }
9513            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9514                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9515                // If this permission is to be granted to the system installer and
9516                // this app is an installer, then it gets the permission.
9517                allowed = true;
9518            }
9519            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9520                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9521                // If this permission is to be granted to the system verifier and
9522                // this app is a verifier, then it gets the permission.
9523                allowed = true;
9524            }
9525            if (!allowed && (bp.protectionLevel
9526                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9527                    && isSystemApp(pkg)) {
9528                // Any pre-installed system app is allowed to get this permission.
9529                allowed = true;
9530            }
9531            if (!allowed && (bp.protectionLevel
9532                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9533                // For development permissions, a development permission
9534                // is granted only if it was already granted.
9535                allowed = origPermissions.hasInstallPermission(perm);
9536            }
9537        }
9538        return allowed;
9539    }
9540
9541    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9542        final int permCount = pkg.requestedPermissions.size();
9543        for (int j = 0; j < permCount; j++) {
9544            String requestedPermission = pkg.requestedPermissions.get(j);
9545            if (permission.equals(requestedPermission)) {
9546                return true;
9547            }
9548        }
9549        return false;
9550    }
9551
9552    final class ActivityIntentResolver
9553            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9554        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9555                boolean defaultOnly, int userId) {
9556            if (!sUserManager.exists(userId)) return null;
9557            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9558            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9559        }
9560
9561        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9562                int userId) {
9563            if (!sUserManager.exists(userId)) return null;
9564            mFlags = flags;
9565            return super.queryIntent(intent, resolvedType,
9566                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9567        }
9568
9569        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9570                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9571            if (!sUserManager.exists(userId)) return null;
9572            if (packageActivities == null) {
9573                return null;
9574            }
9575            mFlags = flags;
9576            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9577            final int N = packageActivities.size();
9578            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9579                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9580
9581            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9582            for (int i = 0; i < N; ++i) {
9583                intentFilters = packageActivities.get(i).intents;
9584                if (intentFilters != null && intentFilters.size() > 0) {
9585                    PackageParser.ActivityIntentInfo[] array =
9586                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9587                    intentFilters.toArray(array);
9588                    listCut.add(array);
9589                }
9590            }
9591            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9592        }
9593
9594        public final void addActivity(PackageParser.Activity a, String type) {
9595            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9596            mActivities.put(a.getComponentName(), a);
9597            if (DEBUG_SHOW_INFO)
9598                Log.v(
9599                TAG, "  " + type + " " +
9600                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9601            if (DEBUG_SHOW_INFO)
9602                Log.v(TAG, "    Class=" + a.info.name);
9603            final int NI = a.intents.size();
9604            for (int j=0; j<NI; j++) {
9605                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9606                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9607                    intent.setPriority(0);
9608                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9609                            + a.className + " with priority > 0, forcing to 0");
9610                }
9611                if (DEBUG_SHOW_INFO) {
9612                    Log.v(TAG, "    IntentFilter:");
9613                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9614                }
9615                if (!intent.debugCheck()) {
9616                    Log.w(TAG, "==> For Activity " + a.info.name);
9617                }
9618                addFilter(intent);
9619            }
9620        }
9621
9622        public final void removeActivity(PackageParser.Activity a, String type) {
9623            mActivities.remove(a.getComponentName());
9624            if (DEBUG_SHOW_INFO) {
9625                Log.v(TAG, "  " + type + " "
9626                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9627                                : a.info.name) + ":");
9628                Log.v(TAG, "    Class=" + a.info.name);
9629            }
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 (DEBUG_SHOW_INFO) {
9634                    Log.v(TAG, "    IntentFilter:");
9635                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9636                }
9637                removeFilter(intent);
9638            }
9639        }
9640
9641        @Override
9642        protected boolean allowFilterResult(
9643                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9644            ActivityInfo filterAi = filter.activity.info;
9645            for (int i=dest.size()-1; i>=0; i--) {
9646                ActivityInfo destAi = dest.get(i).activityInfo;
9647                if (destAi.name == filterAi.name
9648                        && destAi.packageName == filterAi.packageName) {
9649                    return false;
9650                }
9651            }
9652            return true;
9653        }
9654
9655        @Override
9656        protected ActivityIntentInfo[] newArray(int size) {
9657            return new ActivityIntentInfo[size];
9658        }
9659
9660        @Override
9661        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9662            if (!sUserManager.exists(userId)) return true;
9663            PackageParser.Package p = filter.activity.owner;
9664            if (p != null) {
9665                PackageSetting ps = (PackageSetting)p.mExtras;
9666                if (ps != null) {
9667                    // System apps are never considered stopped for purposes of
9668                    // filtering, because there may be no way for the user to
9669                    // actually re-launch them.
9670                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9671                            && ps.getStopped(userId);
9672                }
9673            }
9674            return false;
9675        }
9676
9677        @Override
9678        protected boolean isPackageForFilter(String packageName,
9679                PackageParser.ActivityIntentInfo info) {
9680            return packageName.equals(info.activity.owner.packageName);
9681        }
9682
9683        @Override
9684        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9685                int match, int userId) {
9686            if (!sUserManager.exists(userId)) return null;
9687            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9688                return null;
9689            }
9690            final PackageParser.Activity activity = info.activity;
9691            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9692            if (ps == null) {
9693                return null;
9694            }
9695            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9696                    ps.readUserState(userId), userId);
9697            if (ai == null) {
9698                return null;
9699            }
9700            final ResolveInfo res = new ResolveInfo();
9701            res.activityInfo = ai;
9702            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9703                res.filter = info;
9704            }
9705            if (info != null) {
9706                res.handleAllWebDataURI = info.handleAllWebDataURI();
9707            }
9708            res.priority = info.getPriority();
9709            res.preferredOrder = activity.owner.mPreferredOrder;
9710            //System.out.println("Result: " + res.activityInfo.className +
9711            //                   " = " + res.priority);
9712            res.match = match;
9713            res.isDefault = info.hasDefault;
9714            res.labelRes = info.labelRes;
9715            res.nonLocalizedLabel = info.nonLocalizedLabel;
9716            if (userNeedsBadging(userId)) {
9717                res.noResourceId = true;
9718            } else {
9719                res.icon = info.icon;
9720            }
9721            res.iconResourceId = info.icon;
9722            res.system = res.activityInfo.applicationInfo.isSystemApp();
9723            return res;
9724        }
9725
9726        @Override
9727        protected void sortResults(List<ResolveInfo> results) {
9728            Collections.sort(results, mResolvePrioritySorter);
9729        }
9730
9731        @Override
9732        protected void dumpFilter(PrintWriter out, String prefix,
9733                PackageParser.ActivityIntentInfo filter) {
9734            out.print(prefix); out.print(
9735                    Integer.toHexString(System.identityHashCode(filter.activity)));
9736                    out.print(' ');
9737                    filter.activity.printComponentShortName(out);
9738                    out.print(" filter ");
9739                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9740        }
9741
9742        @Override
9743        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9744            return filter.activity;
9745        }
9746
9747        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9748            PackageParser.Activity activity = (PackageParser.Activity)label;
9749            out.print(prefix); out.print(
9750                    Integer.toHexString(System.identityHashCode(activity)));
9751                    out.print(' ');
9752                    activity.printComponentShortName(out);
9753            if (count > 1) {
9754                out.print(" ("); out.print(count); out.print(" filters)");
9755            }
9756            out.println();
9757        }
9758
9759//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9760//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9761//            final List<ResolveInfo> retList = Lists.newArrayList();
9762//            while (i.hasNext()) {
9763//                final ResolveInfo resolveInfo = i.next();
9764//                if (isEnabledLP(resolveInfo.activityInfo)) {
9765//                    retList.add(resolveInfo);
9766//                }
9767//            }
9768//            return retList;
9769//        }
9770
9771        // Keys are String (activity class name), values are Activity.
9772        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9773                = new ArrayMap<ComponentName, PackageParser.Activity>();
9774        private int mFlags;
9775    }
9776
9777    private final class ServiceIntentResolver
9778            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9779        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9780                boolean defaultOnly, int userId) {
9781            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9782            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9783        }
9784
9785        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9786                int userId) {
9787            if (!sUserManager.exists(userId)) return null;
9788            mFlags = flags;
9789            return super.queryIntent(intent, resolvedType,
9790                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9791        }
9792
9793        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9794                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9795            if (!sUserManager.exists(userId)) return null;
9796            if (packageServices == null) {
9797                return null;
9798            }
9799            mFlags = flags;
9800            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9801            final int N = packageServices.size();
9802            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9803                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9804
9805            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9806            for (int i = 0; i < N; ++i) {
9807                intentFilters = packageServices.get(i).intents;
9808                if (intentFilters != null && intentFilters.size() > 0) {
9809                    PackageParser.ServiceIntentInfo[] array =
9810                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9811                    intentFilters.toArray(array);
9812                    listCut.add(array);
9813                }
9814            }
9815            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9816        }
9817
9818        public final void addService(PackageParser.Service s) {
9819            mServices.put(s.getComponentName(), s);
9820            if (DEBUG_SHOW_INFO) {
9821                Log.v(TAG, "  "
9822                        + (s.info.nonLocalizedLabel != null
9823                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9824                Log.v(TAG, "    Class=" + s.info.name);
9825            }
9826            final int NI = s.intents.size();
9827            int j;
9828            for (j=0; j<NI; j++) {
9829                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9830                if (DEBUG_SHOW_INFO) {
9831                    Log.v(TAG, "    IntentFilter:");
9832                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9833                }
9834                if (!intent.debugCheck()) {
9835                    Log.w(TAG, "==> For Service " + s.info.name);
9836                }
9837                addFilter(intent);
9838            }
9839        }
9840
9841        public final void removeService(PackageParser.Service s) {
9842            mServices.remove(s.getComponentName());
9843            if (DEBUG_SHOW_INFO) {
9844                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9845                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9846                Log.v(TAG, "    Class=" + s.info.name);
9847            }
9848            final int NI = s.intents.size();
9849            int j;
9850            for (j=0; j<NI; j++) {
9851                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9852                if (DEBUG_SHOW_INFO) {
9853                    Log.v(TAG, "    IntentFilter:");
9854                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9855                }
9856                removeFilter(intent);
9857            }
9858        }
9859
9860        @Override
9861        protected boolean allowFilterResult(
9862                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9863            ServiceInfo filterSi = filter.service.info;
9864            for (int i=dest.size()-1; i>=0; i--) {
9865                ServiceInfo destAi = dest.get(i).serviceInfo;
9866                if (destAi.name == filterSi.name
9867                        && destAi.packageName == filterSi.packageName) {
9868                    return false;
9869                }
9870            }
9871            return true;
9872        }
9873
9874        @Override
9875        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9876            return new PackageParser.ServiceIntentInfo[size];
9877        }
9878
9879        @Override
9880        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9881            if (!sUserManager.exists(userId)) return true;
9882            PackageParser.Package p = filter.service.owner;
9883            if (p != null) {
9884                PackageSetting ps = (PackageSetting)p.mExtras;
9885                if (ps != null) {
9886                    // System apps are never considered stopped for purposes of
9887                    // filtering, because there may be no way for the user to
9888                    // actually re-launch them.
9889                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9890                            && ps.getStopped(userId);
9891                }
9892            }
9893            return false;
9894        }
9895
9896        @Override
9897        protected boolean isPackageForFilter(String packageName,
9898                PackageParser.ServiceIntentInfo info) {
9899            return packageName.equals(info.service.owner.packageName);
9900        }
9901
9902        @Override
9903        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9904                int match, int userId) {
9905            if (!sUserManager.exists(userId)) return null;
9906            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9907            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9908                return null;
9909            }
9910            final PackageParser.Service service = info.service;
9911            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9912            if (ps == null) {
9913                return null;
9914            }
9915            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9916                    ps.readUserState(userId), userId);
9917            if (si == null) {
9918                return null;
9919            }
9920            final ResolveInfo res = new ResolveInfo();
9921            res.serviceInfo = si;
9922            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9923                res.filter = filter;
9924            }
9925            res.priority = info.getPriority();
9926            res.preferredOrder = service.owner.mPreferredOrder;
9927            res.match = match;
9928            res.isDefault = info.hasDefault;
9929            res.labelRes = info.labelRes;
9930            res.nonLocalizedLabel = info.nonLocalizedLabel;
9931            res.icon = info.icon;
9932            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9933            return res;
9934        }
9935
9936        @Override
9937        protected void sortResults(List<ResolveInfo> results) {
9938            Collections.sort(results, mResolvePrioritySorter);
9939        }
9940
9941        @Override
9942        protected void dumpFilter(PrintWriter out, String prefix,
9943                PackageParser.ServiceIntentInfo filter) {
9944            out.print(prefix); out.print(
9945                    Integer.toHexString(System.identityHashCode(filter.service)));
9946                    out.print(' ');
9947                    filter.service.printComponentShortName(out);
9948                    out.print(" filter ");
9949                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9950        }
9951
9952        @Override
9953        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9954            return filter.service;
9955        }
9956
9957        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9958            PackageParser.Service service = (PackageParser.Service)label;
9959            out.print(prefix); out.print(
9960                    Integer.toHexString(System.identityHashCode(service)));
9961                    out.print(' ');
9962                    service.printComponentShortName(out);
9963            if (count > 1) {
9964                out.print(" ("); out.print(count); out.print(" filters)");
9965            }
9966            out.println();
9967        }
9968
9969//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9970//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9971//            final List<ResolveInfo> retList = Lists.newArrayList();
9972//            while (i.hasNext()) {
9973//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9974//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9975//                    retList.add(resolveInfo);
9976//                }
9977//            }
9978//            return retList;
9979//        }
9980
9981        // Keys are String (activity class name), values are Activity.
9982        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9983                = new ArrayMap<ComponentName, PackageParser.Service>();
9984        private int mFlags;
9985    };
9986
9987    private final class ProviderIntentResolver
9988            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9989        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9990                boolean defaultOnly, int userId) {
9991            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9992            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9993        }
9994
9995        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9996                int userId) {
9997            if (!sUserManager.exists(userId))
9998                return null;
9999            mFlags = flags;
10000            return super.queryIntent(intent, resolvedType,
10001                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10002        }
10003
10004        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10005                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10006            if (!sUserManager.exists(userId))
10007                return null;
10008            if (packageProviders == null) {
10009                return null;
10010            }
10011            mFlags = flags;
10012            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10013            final int N = packageProviders.size();
10014            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10015                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10016
10017            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10018            for (int i = 0; i < N; ++i) {
10019                intentFilters = packageProviders.get(i).intents;
10020                if (intentFilters != null && intentFilters.size() > 0) {
10021                    PackageParser.ProviderIntentInfo[] array =
10022                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10023                    intentFilters.toArray(array);
10024                    listCut.add(array);
10025                }
10026            }
10027            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10028        }
10029
10030        public final void addProvider(PackageParser.Provider p) {
10031            if (mProviders.containsKey(p.getComponentName())) {
10032                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10033                return;
10034            }
10035
10036            mProviders.put(p.getComponentName(), p);
10037            if (DEBUG_SHOW_INFO) {
10038                Log.v(TAG, "  "
10039                        + (p.info.nonLocalizedLabel != null
10040                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10041                Log.v(TAG, "    Class=" + p.info.name);
10042            }
10043            final int NI = p.intents.size();
10044            int j;
10045            for (j = 0; j < NI; j++) {
10046                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10047                if (DEBUG_SHOW_INFO) {
10048                    Log.v(TAG, "    IntentFilter:");
10049                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10050                }
10051                if (!intent.debugCheck()) {
10052                    Log.w(TAG, "==> For Provider " + p.info.name);
10053                }
10054                addFilter(intent);
10055            }
10056        }
10057
10058        public final void removeProvider(PackageParser.Provider p) {
10059            mProviders.remove(p.getComponentName());
10060            if (DEBUG_SHOW_INFO) {
10061                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10062                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10063                Log.v(TAG, "    Class=" + p.info.name);
10064            }
10065            final int NI = p.intents.size();
10066            int j;
10067            for (j = 0; j < NI; j++) {
10068                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10069                if (DEBUG_SHOW_INFO) {
10070                    Log.v(TAG, "    IntentFilter:");
10071                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10072                }
10073                removeFilter(intent);
10074            }
10075        }
10076
10077        @Override
10078        protected boolean allowFilterResult(
10079                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10080            ProviderInfo filterPi = filter.provider.info;
10081            for (int i = dest.size() - 1; i >= 0; i--) {
10082                ProviderInfo destPi = dest.get(i).providerInfo;
10083                if (destPi.name == filterPi.name
10084                        && destPi.packageName == filterPi.packageName) {
10085                    return false;
10086                }
10087            }
10088            return true;
10089        }
10090
10091        @Override
10092        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10093            return new PackageParser.ProviderIntentInfo[size];
10094        }
10095
10096        @Override
10097        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10098            if (!sUserManager.exists(userId))
10099                return true;
10100            PackageParser.Package p = filter.provider.owner;
10101            if (p != null) {
10102                PackageSetting ps = (PackageSetting) p.mExtras;
10103                if (ps != null) {
10104                    // System apps are never considered stopped for purposes of
10105                    // filtering, because there may be no way for the user to
10106                    // actually re-launch them.
10107                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10108                            && ps.getStopped(userId);
10109                }
10110            }
10111            return false;
10112        }
10113
10114        @Override
10115        protected boolean isPackageForFilter(String packageName,
10116                PackageParser.ProviderIntentInfo info) {
10117            return packageName.equals(info.provider.owner.packageName);
10118        }
10119
10120        @Override
10121        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10122                int match, int userId) {
10123            if (!sUserManager.exists(userId))
10124                return null;
10125            final PackageParser.ProviderIntentInfo info = filter;
10126            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10127                return null;
10128            }
10129            final PackageParser.Provider provider = info.provider;
10130            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10131            if (ps == null) {
10132                return null;
10133            }
10134            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10135                    ps.readUserState(userId), userId);
10136            if (pi == null) {
10137                return null;
10138            }
10139            final ResolveInfo res = new ResolveInfo();
10140            res.providerInfo = pi;
10141            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10142                res.filter = filter;
10143            }
10144            res.priority = info.getPriority();
10145            res.preferredOrder = provider.owner.mPreferredOrder;
10146            res.match = match;
10147            res.isDefault = info.hasDefault;
10148            res.labelRes = info.labelRes;
10149            res.nonLocalizedLabel = info.nonLocalizedLabel;
10150            res.icon = info.icon;
10151            res.system = res.providerInfo.applicationInfo.isSystemApp();
10152            return res;
10153        }
10154
10155        @Override
10156        protected void sortResults(List<ResolveInfo> results) {
10157            Collections.sort(results, mResolvePrioritySorter);
10158        }
10159
10160        @Override
10161        protected void dumpFilter(PrintWriter out, String prefix,
10162                PackageParser.ProviderIntentInfo filter) {
10163            out.print(prefix);
10164            out.print(
10165                    Integer.toHexString(System.identityHashCode(filter.provider)));
10166            out.print(' ');
10167            filter.provider.printComponentShortName(out);
10168            out.print(" filter ");
10169            out.println(Integer.toHexString(System.identityHashCode(filter)));
10170        }
10171
10172        @Override
10173        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10174            return filter.provider;
10175        }
10176
10177        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10178            PackageParser.Provider provider = (PackageParser.Provider)label;
10179            out.print(prefix); out.print(
10180                    Integer.toHexString(System.identityHashCode(provider)));
10181                    out.print(' ');
10182                    provider.printComponentShortName(out);
10183            if (count > 1) {
10184                out.print(" ("); out.print(count); out.print(" filters)");
10185            }
10186            out.println();
10187        }
10188
10189        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10190                = new ArrayMap<ComponentName, PackageParser.Provider>();
10191        private int mFlags;
10192    }
10193
10194    private static final class EphemeralIntentResolver
10195            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10196        @Override
10197        protected EphemeralResolveIntentInfo[] newArray(int size) {
10198            return new EphemeralResolveIntentInfo[size];
10199        }
10200
10201        @Override
10202        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10203            return true;
10204        }
10205
10206        @Override
10207        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10208                int userId) {
10209            if (!sUserManager.exists(userId)) {
10210                return null;
10211            }
10212            return info.getEphemeralResolveInfo();
10213        }
10214    }
10215
10216    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10217            new Comparator<ResolveInfo>() {
10218        public int compare(ResolveInfo r1, ResolveInfo r2) {
10219            int v1 = r1.priority;
10220            int v2 = r2.priority;
10221            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10222            if (v1 != v2) {
10223                return (v1 > v2) ? -1 : 1;
10224            }
10225            v1 = r1.preferredOrder;
10226            v2 = r2.preferredOrder;
10227            if (v1 != v2) {
10228                return (v1 > v2) ? -1 : 1;
10229            }
10230            if (r1.isDefault != r2.isDefault) {
10231                return r1.isDefault ? -1 : 1;
10232            }
10233            v1 = r1.match;
10234            v2 = r2.match;
10235            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10236            if (v1 != v2) {
10237                return (v1 > v2) ? -1 : 1;
10238            }
10239            if (r1.system != r2.system) {
10240                return r1.system ? -1 : 1;
10241            }
10242            if (r1.activityInfo != null) {
10243                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10244            }
10245            if (r1.serviceInfo != null) {
10246                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10247            }
10248            if (r1.providerInfo != null) {
10249                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10250            }
10251            return 0;
10252        }
10253    };
10254
10255    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10256            new Comparator<ProviderInfo>() {
10257        public int compare(ProviderInfo p1, ProviderInfo p2) {
10258            final int v1 = p1.initOrder;
10259            final int v2 = p2.initOrder;
10260            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10261        }
10262    };
10263
10264    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10265            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10266            final int[] userIds) {
10267        mHandler.post(new Runnable() {
10268            @Override
10269            public void run() {
10270                try {
10271                    final IActivityManager am = ActivityManagerNative.getDefault();
10272                    if (am == null) return;
10273                    final int[] resolvedUserIds;
10274                    if (userIds == null) {
10275                        resolvedUserIds = am.getRunningUserIds();
10276                    } else {
10277                        resolvedUserIds = userIds;
10278                    }
10279                    for (int id : resolvedUserIds) {
10280                        final Intent intent = new Intent(action,
10281                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10282                        if (extras != null) {
10283                            intent.putExtras(extras);
10284                        }
10285                        if (targetPkg != null) {
10286                            intent.setPackage(targetPkg);
10287                        }
10288                        // Modify the UID when posting to other users
10289                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10290                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10291                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10292                            intent.putExtra(Intent.EXTRA_UID, uid);
10293                        }
10294                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10295                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10296                        if (DEBUG_BROADCASTS) {
10297                            RuntimeException here = new RuntimeException("here");
10298                            here.fillInStackTrace();
10299                            Slog.d(TAG, "Sending to user " + id + ": "
10300                                    + intent.toShortString(false, true, false, false)
10301                                    + " " + intent.getExtras(), here);
10302                        }
10303                        am.broadcastIntent(null, intent, null, finishedReceiver,
10304                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10305                                null, finishedReceiver != null, false, id);
10306                    }
10307                } catch (RemoteException ex) {
10308                }
10309            }
10310        });
10311    }
10312
10313    /**
10314     * Check if the external storage media is available. This is true if there
10315     * is a mounted external storage medium or if the external storage is
10316     * emulated.
10317     */
10318    private boolean isExternalMediaAvailable() {
10319        return mMediaMounted || Environment.isExternalStorageEmulated();
10320    }
10321
10322    @Override
10323    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10324        // writer
10325        synchronized (mPackages) {
10326            if (!isExternalMediaAvailable()) {
10327                // If the external storage is no longer mounted at this point,
10328                // the caller may not have been able to delete all of this
10329                // packages files and can not delete any more.  Bail.
10330                return null;
10331            }
10332            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10333            if (lastPackage != null) {
10334                pkgs.remove(lastPackage);
10335            }
10336            if (pkgs.size() > 0) {
10337                return pkgs.get(0);
10338            }
10339        }
10340        return null;
10341    }
10342
10343    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10344        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10345                userId, andCode ? 1 : 0, packageName);
10346        if (mSystemReady) {
10347            msg.sendToTarget();
10348        } else {
10349            if (mPostSystemReadyMessages == null) {
10350                mPostSystemReadyMessages = new ArrayList<>();
10351            }
10352            mPostSystemReadyMessages.add(msg);
10353        }
10354    }
10355
10356    void startCleaningPackages() {
10357        // reader
10358        synchronized (mPackages) {
10359            if (!isExternalMediaAvailable()) {
10360                return;
10361            }
10362            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10363                return;
10364            }
10365        }
10366        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10367        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10368        IActivityManager am = ActivityManagerNative.getDefault();
10369        if (am != null) {
10370            try {
10371                am.startService(null, intent, null, mContext.getOpPackageName(),
10372                        UserHandle.USER_SYSTEM);
10373            } catch (RemoteException e) {
10374            }
10375        }
10376    }
10377
10378    @Override
10379    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10380            int installFlags, String installerPackageName, int userId) {
10381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10382
10383        final int callingUid = Binder.getCallingUid();
10384        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10385
10386        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10387            try {
10388                if (observer != null) {
10389                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10390                }
10391            } catch (RemoteException re) {
10392            }
10393            return;
10394        }
10395
10396        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10397            installFlags |= PackageManager.INSTALL_FROM_ADB;
10398
10399        } else {
10400            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10401            // about installerPackageName.
10402
10403            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10404            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10405        }
10406
10407        UserHandle user;
10408        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10409            user = UserHandle.ALL;
10410        } else {
10411            user = new UserHandle(userId);
10412        }
10413
10414        // Only system components can circumvent runtime permissions when installing.
10415        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10416                && mContext.checkCallingOrSelfPermission(Manifest.permission
10417                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10418            throw new SecurityException("You need the "
10419                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10420                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10421        }
10422
10423        final File originFile = new File(originPath);
10424        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10425
10426        final Message msg = mHandler.obtainMessage(INIT_COPY);
10427        final VerificationInfo verificationInfo = new VerificationInfo(
10428                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10429        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10430                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10431                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10432        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10433        msg.obj = params;
10434
10435        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10436                System.identityHashCode(msg.obj));
10437        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10438                System.identityHashCode(msg.obj));
10439
10440        mHandler.sendMessage(msg);
10441    }
10442
10443    void installStage(String packageName, File stagedDir, String stagedCid,
10444            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10445            String installerPackageName, int installerUid, UserHandle user) {
10446        if (DEBUG_EPHEMERAL) {
10447            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10448                Slog.d(TAG, "Ephemeral install of " + packageName);
10449            }
10450        }
10451        final VerificationInfo verificationInfo = new VerificationInfo(
10452                sessionParams.originatingUri, sessionParams.referrerUri,
10453                sessionParams.originatingUid, installerUid);
10454
10455        final OriginInfo origin;
10456        if (stagedDir != null) {
10457            origin = OriginInfo.fromStagedFile(stagedDir);
10458        } else {
10459            origin = OriginInfo.fromStagedContainer(stagedCid);
10460        }
10461
10462        final Message msg = mHandler.obtainMessage(INIT_COPY);
10463        final InstallParams params = new InstallParams(origin, null, observer,
10464                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10465                verificationInfo, user, sessionParams.abiOverride,
10466                sessionParams.grantedRuntimePermissions);
10467        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10468        msg.obj = params;
10469
10470        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10471                System.identityHashCode(msg.obj));
10472        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10473                System.identityHashCode(msg.obj));
10474
10475        mHandler.sendMessage(msg);
10476    }
10477
10478    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10479            int userId) {
10480        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10481        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10482    }
10483
10484    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10485            int appId, int userId) {
10486        Bundle extras = new Bundle(1);
10487        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10488
10489        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10490                packageName, extras, 0, null, null, new int[] {userId});
10491        try {
10492            IActivityManager am = ActivityManagerNative.getDefault();
10493            if (isSystem && am.isUserRunning(userId, 0)) {
10494                // The just-installed/enabled app is bundled on the system, so presumed
10495                // to be able to run automatically without needing an explicit launch.
10496                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10497                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10498                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10499                        .setPackage(packageName);
10500                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10501                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10502            }
10503        } catch (RemoteException e) {
10504            // shouldn't happen
10505            Slog.w(TAG, "Unable to bootstrap installed package", e);
10506        }
10507    }
10508
10509    @Override
10510    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10511            int userId) {
10512        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10513        PackageSetting pkgSetting;
10514        final int uid = Binder.getCallingUid();
10515        enforceCrossUserPermission(uid, userId, true, true,
10516                "setApplicationHiddenSetting for user " + userId);
10517
10518        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10519            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10520            return false;
10521        }
10522
10523        long callingId = Binder.clearCallingIdentity();
10524        try {
10525            boolean sendAdded = false;
10526            boolean sendRemoved = false;
10527            // writer
10528            synchronized (mPackages) {
10529                pkgSetting = mSettings.mPackages.get(packageName);
10530                if (pkgSetting == null) {
10531                    return false;
10532                }
10533                if (pkgSetting.getHidden(userId) != hidden) {
10534                    pkgSetting.setHidden(hidden, userId);
10535                    mSettings.writePackageRestrictionsLPr(userId);
10536                    if (hidden) {
10537                        sendRemoved = true;
10538                    } else {
10539                        sendAdded = true;
10540                    }
10541                }
10542            }
10543            if (sendAdded) {
10544                sendPackageAddedForUser(packageName, pkgSetting, userId);
10545                return true;
10546            }
10547            if (sendRemoved) {
10548                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10549                        "hiding pkg");
10550                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10551                return true;
10552            }
10553        } finally {
10554            Binder.restoreCallingIdentity(callingId);
10555        }
10556        return false;
10557    }
10558
10559    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10560            int userId) {
10561        final PackageRemovedInfo info = new PackageRemovedInfo();
10562        info.removedPackage = packageName;
10563        info.removedUsers = new int[] {userId};
10564        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10565        info.sendPackageRemovedBroadcasts();
10566    }
10567
10568    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10569        if (pkgList.length > 0) {
10570            Bundle extras = new Bundle(1);
10571            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10572
10573            sendPackageBroadcast(
10574                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10575                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10576                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10577                    new int[] {userId});
10578        }
10579    }
10580
10581    /**
10582     * Returns true if application is not found or there was an error. Otherwise it returns
10583     * the hidden state of the package for the given user.
10584     */
10585    @Override
10586    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10587        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10588        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10589                false, "getApplicationHidden for user " + userId);
10590        PackageSetting pkgSetting;
10591        long callingId = Binder.clearCallingIdentity();
10592        try {
10593            // writer
10594            synchronized (mPackages) {
10595                pkgSetting = mSettings.mPackages.get(packageName);
10596                if (pkgSetting == null) {
10597                    return true;
10598                }
10599                return pkgSetting.getHidden(userId);
10600            }
10601        } finally {
10602            Binder.restoreCallingIdentity(callingId);
10603        }
10604    }
10605
10606    /**
10607     * @hide
10608     */
10609    @Override
10610    public int installExistingPackageAsUser(String packageName, int userId) {
10611        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10612                null);
10613        PackageSetting pkgSetting;
10614        final int uid = Binder.getCallingUid();
10615        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10616                + userId);
10617        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10618            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10619        }
10620
10621        long callingId = Binder.clearCallingIdentity();
10622        try {
10623            boolean installed = false;
10624
10625            // writer
10626            synchronized (mPackages) {
10627                pkgSetting = mSettings.mPackages.get(packageName);
10628                if (pkgSetting == null) {
10629                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10630                }
10631                if (!pkgSetting.getInstalled(userId)) {
10632                    pkgSetting.setInstalled(true, userId);
10633                    pkgSetting.setHidden(false, userId);
10634                    mSettings.writePackageRestrictionsLPr(userId);
10635                    installed = true;
10636                }
10637            }
10638
10639            if (installed) {
10640                if (pkgSetting.pkg != null) {
10641                    prepareAppDataAfterInstall(pkgSetting.pkg);
10642                }
10643                sendPackageAddedForUser(packageName, pkgSetting, userId);
10644            }
10645        } finally {
10646            Binder.restoreCallingIdentity(callingId);
10647        }
10648
10649        return PackageManager.INSTALL_SUCCEEDED;
10650    }
10651
10652    boolean isUserRestricted(int userId, String restrictionKey) {
10653        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10654        if (restrictions.getBoolean(restrictionKey, false)) {
10655            Log.w(TAG, "User is restricted: " + restrictionKey);
10656            return true;
10657        }
10658        return false;
10659    }
10660
10661    @Override
10662    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10663            int userId) {
10664        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10665        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10666                "setPackagesSuspended for user " + userId);
10667
10668        if (ArrayUtils.isEmpty(packageNames)) {
10669            return packageNames;
10670        }
10671
10672        // List of package names for whom the suspended state has changed.
10673        List<String> changedPackages = new ArrayList<>(packageNames.length);
10674        // List of package names for whom the suspended state is not set as requested in this
10675        // method.
10676        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10677        for (int i = 0; i < packageNames.length; i++) {
10678            String packageName = packageNames[i];
10679            long callingId = Binder.clearCallingIdentity();
10680            try {
10681                boolean changed = false;
10682                final int appId;
10683                synchronized (mPackages) {
10684                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10685                    if (pkgSetting == null) {
10686                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10687                                + "\". Skipping suspending/un-suspending.");
10688                        unactionedPackages.add(packageName);
10689                        continue;
10690                    }
10691                    appId = pkgSetting.appId;
10692                    if (pkgSetting.getSuspended(userId) != suspended) {
10693                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10694                            unactionedPackages.add(packageName);
10695                            continue;
10696                        }
10697                        pkgSetting.setSuspended(suspended, userId);
10698                        mSettings.writePackageRestrictionsLPr(userId);
10699                        changed = true;
10700                        changedPackages.add(packageName);
10701                    }
10702                }
10703
10704                if (changed && suspended) {
10705                    killApplication(packageName, UserHandle.getUid(userId, appId),
10706                            "suspending package");
10707                }
10708            } finally {
10709                Binder.restoreCallingIdentity(callingId);
10710            }
10711        }
10712
10713        if (!changedPackages.isEmpty()) {
10714            sendPackagesSuspendedForUser(changedPackages.toArray(
10715                    new String[changedPackages.size()]), userId, suspended);
10716        }
10717
10718        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10719    }
10720
10721    @Override
10722    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10724                false, "isPackageSuspendedForUser for user " + userId);
10725        synchronized (mPackages) {
10726            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10727            return pkgSetting != null && pkgSetting.getSuspended(userId);
10728        }
10729    }
10730
10731    // TODO: investigate and add more restrictions for suspending crucial packages.
10732    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10733        if (isPackageDeviceAdmin(packageName, userId)) {
10734            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10735                    + "\": has active device admin");
10736            return false;
10737        }
10738
10739        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10740        if (packageName.equals(activeLauncherPackageName)) {
10741            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10742                    + "\" because it is set as the active launcher");
10743            return false;
10744        }
10745
10746        final PackageParser.Package pkg = mPackages.get(packageName);
10747        if (pkg != null && isPrivilegedApp(pkg)) {
10748            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10749                    + "\" because it is a privileged app");
10750            return false;
10751        }
10752
10753        return true;
10754    }
10755
10756    private String getActiveLauncherPackageName(int userId) {
10757        Intent intent = new Intent(Intent.ACTION_MAIN);
10758        intent.addCategory(Intent.CATEGORY_HOME);
10759        ResolveInfo resolveInfo = resolveIntent(
10760                intent,
10761                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10762                PackageManager.MATCH_DEFAULT_ONLY,
10763                userId);
10764
10765        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10766    }
10767
10768    @Override
10769    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10770        mContext.enforceCallingOrSelfPermission(
10771                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10772                "Only package verification agents can verify applications");
10773
10774        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10775        final PackageVerificationResponse response = new PackageVerificationResponse(
10776                verificationCode, Binder.getCallingUid());
10777        msg.arg1 = id;
10778        msg.obj = response;
10779        mHandler.sendMessage(msg);
10780    }
10781
10782    @Override
10783    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10784            long millisecondsToDelay) {
10785        mContext.enforceCallingOrSelfPermission(
10786                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10787                "Only package verification agents can extend verification timeouts");
10788
10789        final PackageVerificationState state = mPendingVerification.get(id);
10790        final PackageVerificationResponse response = new PackageVerificationResponse(
10791                verificationCodeAtTimeout, Binder.getCallingUid());
10792
10793        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10794            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10795        }
10796        if (millisecondsToDelay < 0) {
10797            millisecondsToDelay = 0;
10798        }
10799        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10800                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10801            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10802        }
10803
10804        if ((state != null) && !state.timeoutExtended()) {
10805            state.extendTimeout();
10806
10807            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10808            msg.arg1 = id;
10809            msg.obj = response;
10810            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10811        }
10812    }
10813
10814    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10815            int verificationCode, UserHandle user) {
10816        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10817        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10818        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10819        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10820        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10821
10822        mContext.sendBroadcastAsUser(intent, user,
10823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10824    }
10825
10826    private ComponentName matchComponentForVerifier(String packageName,
10827            List<ResolveInfo> receivers) {
10828        ActivityInfo targetReceiver = null;
10829
10830        final int NR = receivers.size();
10831        for (int i = 0; i < NR; i++) {
10832            final ResolveInfo info = receivers.get(i);
10833            if (info.activityInfo == null) {
10834                continue;
10835            }
10836
10837            if (packageName.equals(info.activityInfo.packageName)) {
10838                targetReceiver = info.activityInfo;
10839                break;
10840            }
10841        }
10842
10843        if (targetReceiver == null) {
10844            return null;
10845        }
10846
10847        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10848    }
10849
10850    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10851            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10852        if (pkgInfo.verifiers.length == 0) {
10853            return null;
10854        }
10855
10856        final int N = pkgInfo.verifiers.length;
10857        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10858        for (int i = 0; i < N; i++) {
10859            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10860
10861            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10862                    receivers);
10863            if (comp == null) {
10864                continue;
10865            }
10866
10867            final int verifierUid = getUidForVerifier(verifierInfo);
10868            if (verifierUid == -1) {
10869                continue;
10870            }
10871
10872            if (DEBUG_VERIFY) {
10873                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10874                        + " with the correct signature");
10875            }
10876            sufficientVerifiers.add(comp);
10877            verificationState.addSufficientVerifier(verifierUid);
10878        }
10879
10880        return sufficientVerifiers;
10881    }
10882
10883    private int getUidForVerifier(VerifierInfo verifierInfo) {
10884        synchronized (mPackages) {
10885            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10886            if (pkg == null) {
10887                return -1;
10888            } else if (pkg.mSignatures.length != 1) {
10889                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10890                        + " has more than one signature; ignoring");
10891                return -1;
10892            }
10893
10894            /*
10895             * If the public key of the package's signature does not match
10896             * our expected public key, then this is a different package and
10897             * we should skip.
10898             */
10899
10900            final byte[] expectedPublicKey;
10901            try {
10902                final Signature verifierSig = pkg.mSignatures[0];
10903                final PublicKey publicKey = verifierSig.getPublicKey();
10904                expectedPublicKey = publicKey.getEncoded();
10905            } catch (CertificateException e) {
10906                return -1;
10907            }
10908
10909            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10910
10911            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10912                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10913                        + " does not have the expected public key; ignoring");
10914                return -1;
10915            }
10916
10917            return pkg.applicationInfo.uid;
10918        }
10919    }
10920
10921    @Override
10922    public void finishPackageInstall(int token) {
10923        enforceSystemOrRoot("Only the system is allowed to finish installs");
10924
10925        if (DEBUG_INSTALL) {
10926            Slog.v(TAG, "BM finishing package install for " + token);
10927        }
10928        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10929
10930        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10931        mHandler.sendMessage(msg);
10932    }
10933
10934    /**
10935     * Get the verification agent timeout.
10936     *
10937     * @return verification timeout in milliseconds
10938     */
10939    private long getVerificationTimeout() {
10940        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10941                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10942                DEFAULT_VERIFICATION_TIMEOUT);
10943    }
10944
10945    /**
10946     * Get the default verification agent response code.
10947     *
10948     * @return default verification response code
10949     */
10950    private int getDefaultVerificationResponse() {
10951        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10952                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10953                DEFAULT_VERIFICATION_RESPONSE);
10954    }
10955
10956    /**
10957     * Check whether or not package verification has been enabled.
10958     *
10959     * @return true if verification should be performed
10960     */
10961    private boolean isVerificationEnabled(int userId, int installFlags) {
10962        if (!DEFAULT_VERIFY_ENABLE) {
10963            return false;
10964        }
10965        // Ephemeral apps don't get the full verification treatment
10966        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10967            if (DEBUG_EPHEMERAL) {
10968                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10969            }
10970            return false;
10971        }
10972
10973        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10974
10975        // Check if installing from ADB
10976        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10977            // Do not run verification in a test harness environment
10978            if (ActivityManager.isRunningInTestHarness()) {
10979                return false;
10980            }
10981            if (ensureVerifyAppsEnabled) {
10982                return true;
10983            }
10984            // Check if the developer does not want package verification for ADB installs
10985            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10986                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10987                return false;
10988            }
10989        }
10990
10991        if (ensureVerifyAppsEnabled) {
10992            return true;
10993        }
10994
10995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10996                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10997    }
10998
10999    @Override
11000    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11001            throws RemoteException {
11002        mContext.enforceCallingOrSelfPermission(
11003                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11004                "Only intentfilter verification agents can verify applications");
11005
11006        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11007        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11008                Binder.getCallingUid(), verificationCode, failedDomains);
11009        msg.arg1 = id;
11010        msg.obj = response;
11011        mHandler.sendMessage(msg);
11012    }
11013
11014    @Override
11015    public int getIntentVerificationStatus(String packageName, int userId) {
11016        synchronized (mPackages) {
11017            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11018        }
11019    }
11020
11021    @Override
11022    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11023        mContext.enforceCallingOrSelfPermission(
11024                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11025
11026        boolean result = false;
11027        synchronized (mPackages) {
11028            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11029        }
11030        if (result) {
11031            scheduleWritePackageRestrictionsLocked(userId);
11032        }
11033        return result;
11034    }
11035
11036    @Override
11037    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11038        synchronized (mPackages) {
11039            return mSettings.getIntentFilterVerificationsLPr(packageName);
11040        }
11041    }
11042
11043    @Override
11044    public List<IntentFilter> getAllIntentFilters(String packageName) {
11045        if (TextUtils.isEmpty(packageName)) {
11046            return Collections.<IntentFilter>emptyList();
11047        }
11048        synchronized (mPackages) {
11049            PackageParser.Package pkg = mPackages.get(packageName);
11050            if (pkg == null || pkg.activities == null) {
11051                return Collections.<IntentFilter>emptyList();
11052            }
11053            final int count = pkg.activities.size();
11054            ArrayList<IntentFilter> result = new ArrayList<>();
11055            for (int n=0; n<count; n++) {
11056                PackageParser.Activity activity = pkg.activities.get(n);
11057                if (activity.intents != null && activity.intents.size() > 0) {
11058                    result.addAll(activity.intents);
11059                }
11060            }
11061            return result;
11062        }
11063    }
11064
11065    @Override
11066    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11067        mContext.enforceCallingOrSelfPermission(
11068                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11069
11070        synchronized (mPackages) {
11071            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11072            if (packageName != null) {
11073                result |= updateIntentVerificationStatus(packageName,
11074                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11075                        userId);
11076                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11077                        packageName, userId);
11078            }
11079            return result;
11080        }
11081    }
11082
11083    @Override
11084    public String getDefaultBrowserPackageName(int userId) {
11085        synchronized (mPackages) {
11086            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11087        }
11088    }
11089
11090    /**
11091     * Get the "allow unknown sources" setting.
11092     *
11093     * @return the current "allow unknown sources" setting
11094     */
11095    private int getUnknownSourcesSettings() {
11096        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11097                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11098                -1);
11099    }
11100
11101    @Override
11102    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11103        final int uid = Binder.getCallingUid();
11104        // writer
11105        synchronized (mPackages) {
11106            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11107            if (targetPackageSetting == null) {
11108                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11109            }
11110
11111            PackageSetting installerPackageSetting;
11112            if (installerPackageName != null) {
11113                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11114                if (installerPackageSetting == null) {
11115                    throw new IllegalArgumentException("Unknown installer package: "
11116                            + installerPackageName);
11117                }
11118            } else {
11119                installerPackageSetting = null;
11120            }
11121
11122            Signature[] callerSignature;
11123            Object obj = mSettings.getUserIdLPr(uid);
11124            if (obj != null) {
11125                if (obj instanceof SharedUserSetting) {
11126                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11127                } else if (obj instanceof PackageSetting) {
11128                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11129                } else {
11130                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11131                }
11132            } else {
11133                throw new SecurityException("Unknown calling UID: " + uid);
11134            }
11135
11136            // Verify: can't set installerPackageName to a package that is
11137            // not signed with the same cert as the caller.
11138            if (installerPackageSetting != null) {
11139                if (compareSignatures(callerSignature,
11140                        installerPackageSetting.signatures.mSignatures)
11141                        != PackageManager.SIGNATURE_MATCH) {
11142                    throw new SecurityException(
11143                            "Caller does not have same cert as new installer package "
11144                            + installerPackageName);
11145                }
11146            }
11147
11148            // Verify: if target already has an installer package, it must
11149            // be signed with the same cert as the caller.
11150            if (targetPackageSetting.installerPackageName != null) {
11151                PackageSetting setting = mSettings.mPackages.get(
11152                        targetPackageSetting.installerPackageName);
11153                // If the currently set package isn't valid, then it's always
11154                // okay to change it.
11155                if (setting != null) {
11156                    if (compareSignatures(callerSignature,
11157                            setting.signatures.mSignatures)
11158                            != PackageManager.SIGNATURE_MATCH) {
11159                        throw new SecurityException(
11160                                "Caller does not have same cert as old installer package "
11161                                + targetPackageSetting.installerPackageName);
11162                    }
11163                }
11164            }
11165
11166            // Okay!
11167            targetPackageSetting.installerPackageName = installerPackageName;
11168            scheduleWriteSettingsLocked();
11169        }
11170    }
11171
11172    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11173        // Queue up an async operation since the package installation may take a little while.
11174        mHandler.post(new Runnable() {
11175            public void run() {
11176                mHandler.removeCallbacks(this);
11177                 // Result object to be returned
11178                PackageInstalledInfo res = new PackageInstalledInfo();
11179                res.setReturnCode(currentStatus);
11180                res.uid = -1;
11181                res.pkg = null;
11182                res.removedInfo = null;
11183                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11184                    args.doPreInstall(res.returnCode);
11185                    synchronized (mInstallLock) {
11186                        installPackageTracedLI(args, res);
11187                    }
11188                    args.doPostInstall(res.returnCode, res.uid);
11189                }
11190
11191                // A restore should be performed at this point if (a) the install
11192                // succeeded, (b) the operation is not an update, and (c) the new
11193                // package has not opted out of backup participation.
11194                final boolean update = res.removedInfo != null
11195                        && res.removedInfo.removedPackage != null;
11196                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11197                boolean doRestore = !update
11198                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11199
11200                // Set up the post-install work request bookkeeping.  This will be used
11201                // and cleaned up by the post-install event handling regardless of whether
11202                // there's a restore pass performed.  Token values are >= 1.
11203                int token;
11204                if (mNextInstallToken < 0) mNextInstallToken = 1;
11205                token = mNextInstallToken++;
11206
11207                PostInstallData data = new PostInstallData(args, res);
11208                mRunningInstalls.put(token, data);
11209                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11210
11211                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11212                    // Pass responsibility to the Backup Manager.  It will perform a
11213                    // restore if appropriate, then pass responsibility back to the
11214                    // Package Manager to run the post-install observer callbacks
11215                    // and broadcasts.
11216                    IBackupManager bm = IBackupManager.Stub.asInterface(
11217                            ServiceManager.getService(Context.BACKUP_SERVICE));
11218                    if (bm != null) {
11219                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11220                                + " to BM for possible restore");
11221                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11222                        try {
11223                            // TODO: http://b/22388012
11224                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11225                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11226                            } else {
11227                                doRestore = false;
11228                            }
11229                        } catch (RemoteException e) {
11230                            // can't happen; the backup manager is local
11231                        } catch (Exception e) {
11232                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11233                            doRestore = false;
11234                        }
11235                    } else {
11236                        Slog.e(TAG, "Backup Manager not found!");
11237                        doRestore = false;
11238                    }
11239                }
11240
11241                if (!doRestore) {
11242                    // No restore possible, or the Backup Manager was mysteriously not
11243                    // available -- just fire the post-install work request directly.
11244                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11245
11246                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11247
11248                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11249                    mHandler.sendMessage(msg);
11250                }
11251            }
11252        });
11253    }
11254
11255    private abstract class HandlerParams {
11256        private static final int MAX_RETRIES = 4;
11257
11258        /**
11259         * Number of times startCopy() has been attempted and had a non-fatal
11260         * error.
11261         */
11262        private int mRetries = 0;
11263
11264        /** User handle for the user requesting the information or installation. */
11265        private final UserHandle mUser;
11266        String traceMethod;
11267        int traceCookie;
11268
11269        HandlerParams(UserHandle user) {
11270            mUser = user;
11271        }
11272
11273        UserHandle getUser() {
11274            return mUser;
11275        }
11276
11277        HandlerParams setTraceMethod(String traceMethod) {
11278            this.traceMethod = traceMethod;
11279            return this;
11280        }
11281
11282        HandlerParams setTraceCookie(int traceCookie) {
11283            this.traceCookie = traceCookie;
11284            return this;
11285        }
11286
11287        final boolean startCopy() {
11288            boolean res;
11289            try {
11290                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11291
11292                if (++mRetries > MAX_RETRIES) {
11293                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11294                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11295                    handleServiceError();
11296                    return false;
11297                } else {
11298                    handleStartCopy();
11299                    res = true;
11300                }
11301            } catch (RemoteException e) {
11302                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11303                mHandler.sendEmptyMessage(MCS_RECONNECT);
11304                res = false;
11305            }
11306            handleReturnCode();
11307            return res;
11308        }
11309
11310        final void serviceError() {
11311            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11312            handleServiceError();
11313            handleReturnCode();
11314        }
11315
11316        abstract void handleStartCopy() throws RemoteException;
11317        abstract void handleServiceError();
11318        abstract void handleReturnCode();
11319    }
11320
11321    class MeasureParams extends HandlerParams {
11322        private final PackageStats mStats;
11323        private boolean mSuccess;
11324
11325        private final IPackageStatsObserver mObserver;
11326
11327        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11328            super(new UserHandle(stats.userHandle));
11329            mObserver = observer;
11330            mStats = stats;
11331        }
11332
11333        @Override
11334        public String toString() {
11335            return "MeasureParams{"
11336                + Integer.toHexString(System.identityHashCode(this))
11337                + " " + mStats.packageName + "}";
11338        }
11339
11340        @Override
11341        void handleStartCopy() throws RemoteException {
11342            synchronized (mInstallLock) {
11343                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11344            }
11345
11346            if (mSuccess) {
11347                final boolean mounted;
11348                if (Environment.isExternalStorageEmulated()) {
11349                    mounted = true;
11350                } else {
11351                    final String status = Environment.getExternalStorageState();
11352                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11353                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11354                }
11355
11356                if (mounted) {
11357                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11358
11359                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11360                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11361
11362                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11363                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11364
11365                    // Always subtract cache size, since it's a subdirectory
11366                    mStats.externalDataSize -= mStats.externalCacheSize;
11367
11368                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11369                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11370
11371                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11372                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11373                }
11374            }
11375        }
11376
11377        @Override
11378        void handleReturnCode() {
11379            if (mObserver != null) {
11380                try {
11381                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11382                } catch (RemoteException e) {
11383                    Slog.i(TAG, "Observer no longer exists.");
11384                }
11385            }
11386        }
11387
11388        @Override
11389        void handleServiceError() {
11390            Slog.e(TAG, "Could not measure application " + mStats.packageName
11391                            + " external storage");
11392        }
11393    }
11394
11395    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11396            throws RemoteException {
11397        long result = 0;
11398        for (File path : paths) {
11399            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11400        }
11401        return result;
11402    }
11403
11404    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11405        for (File path : paths) {
11406            try {
11407                mcs.clearDirectory(path.getAbsolutePath());
11408            } catch (RemoteException e) {
11409            }
11410        }
11411    }
11412
11413    static class OriginInfo {
11414        /**
11415         * Location where install is coming from, before it has been
11416         * copied/renamed into place. This could be a single monolithic APK
11417         * file, or a cluster directory. This location may be untrusted.
11418         */
11419        final File file;
11420        final String cid;
11421
11422        /**
11423         * Flag indicating that {@link #file} or {@link #cid} has already been
11424         * staged, meaning downstream users don't need to defensively copy the
11425         * contents.
11426         */
11427        final boolean staged;
11428
11429        /**
11430         * Flag indicating that {@link #file} or {@link #cid} is an already
11431         * installed app that is being moved.
11432         */
11433        final boolean existing;
11434
11435        final String resolvedPath;
11436        final File resolvedFile;
11437
11438        static OriginInfo fromNothing() {
11439            return new OriginInfo(null, null, false, false);
11440        }
11441
11442        static OriginInfo fromUntrustedFile(File file) {
11443            return new OriginInfo(file, null, false, false);
11444        }
11445
11446        static OriginInfo fromExistingFile(File file) {
11447            return new OriginInfo(file, null, false, true);
11448        }
11449
11450        static OriginInfo fromStagedFile(File file) {
11451            return new OriginInfo(file, null, true, false);
11452        }
11453
11454        static OriginInfo fromStagedContainer(String cid) {
11455            return new OriginInfo(null, cid, true, false);
11456        }
11457
11458        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11459            this.file = file;
11460            this.cid = cid;
11461            this.staged = staged;
11462            this.existing = existing;
11463
11464            if (cid != null) {
11465                resolvedPath = PackageHelper.getSdDir(cid);
11466                resolvedFile = new File(resolvedPath);
11467            } else if (file != null) {
11468                resolvedPath = file.getAbsolutePath();
11469                resolvedFile = file;
11470            } else {
11471                resolvedPath = null;
11472                resolvedFile = null;
11473            }
11474        }
11475    }
11476
11477    static class MoveInfo {
11478        final int moveId;
11479        final String fromUuid;
11480        final String toUuid;
11481        final String packageName;
11482        final String dataAppName;
11483        final int appId;
11484        final String seinfo;
11485        final int targetSdkVersion;
11486
11487        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11488                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11489            this.moveId = moveId;
11490            this.fromUuid = fromUuid;
11491            this.toUuid = toUuid;
11492            this.packageName = packageName;
11493            this.dataAppName = dataAppName;
11494            this.appId = appId;
11495            this.seinfo = seinfo;
11496            this.targetSdkVersion = targetSdkVersion;
11497        }
11498    }
11499
11500    static class VerificationInfo {
11501        /** A constant used to indicate that a uid value is not present. */
11502        public static final int NO_UID = -1;
11503
11504        /** URI referencing where the package was downloaded from. */
11505        final Uri originatingUri;
11506
11507        /** HTTP referrer URI associated with the originatingURI. */
11508        final Uri referrer;
11509
11510        /** UID of the application that the install request originated from. */
11511        final int originatingUid;
11512
11513        /** UID of application requesting the install */
11514        final int installerUid;
11515
11516        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11517            this.originatingUri = originatingUri;
11518            this.referrer = referrer;
11519            this.originatingUid = originatingUid;
11520            this.installerUid = installerUid;
11521        }
11522    }
11523
11524    class InstallParams extends HandlerParams {
11525        final OriginInfo origin;
11526        final MoveInfo move;
11527        final IPackageInstallObserver2 observer;
11528        int installFlags;
11529        final String installerPackageName;
11530        final String volumeUuid;
11531        private InstallArgs mArgs;
11532        private int mRet;
11533        final String packageAbiOverride;
11534        final String[] grantedRuntimePermissions;
11535        final VerificationInfo verificationInfo;
11536
11537        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11538                int installFlags, String installerPackageName, String volumeUuid,
11539                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11540                String[] grantedPermissions) {
11541            super(user);
11542            this.origin = origin;
11543            this.move = move;
11544            this.observer = observer;
11545            this.installFlags = installFlags;
11546            this.installerPackageName = installerPackageName;
11547            this.volumeUuid = volumeUuid;
11548            this.verificationInfo = verificationInfo;
11549            this.packageAbiOverride = packageAbiOverride;
11550            this.grantedRuntimePermissions = grantedPermissions;
11551        }
11552
11553        @Override
11554        public String toString() {
11555            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11556                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11557        }
11558
11559        private int installLocationPolicy(PackageInfoLite pkgLite) {
11560            String packageName = pkgLite.packageName;
11561            int installLocation = pkgLite.installLocation;
11562            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11563            // reader
11564            synchronized (mPackages) {
11565                // Currently installed package which the new package is attempting to replace or
11566                // null if no such package is installed.
11567                PackageParser.Package installedPkg = mPackages.get(packageName);
11568                // Package which currently owns the data which the new package will own if installed.
11569                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11570                // will be null whereas dataOwnerPkg will contain information about the package
11571                // which was uninstalled while keeping its data.
11572                PackageParser.Package dataOwnerPkg = installedPkg;
11573                if (dataOwnerPkg  == null) {
11574                    PackageSetting ps = mSettings.mPackages.get(packageName);
11575                    if (ps != null) {
11576                        dataOwnerPkg = ps.pkg;
11577                    }
11578                }
11579
11580                if (dataOwnerPkg != null) {
11581                    // If installed, the package will get access to data left on the device by its
11582                    // predecessor. As a security measure, this is permited only if this is not a
11583                    // version downgrade or if the predecessor package is marked as debuggable and
11584                    // a downgrade is explicitly requested.
11585                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11586                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11587                        try {
11588                            checkDowngrade(dataOwnerPkg, pkgLite);
11589                        } catch (PackageManagerException e) {
11590                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11591                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11592                        }
11593                    }
11594                }
11595
11596                if (installedPkg != null) {
11597                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11598                        // Check for updated system application.
11599                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11600                            if (onSd) {
11601                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11602                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11603                            }
11604                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11605                        } else {
11606                            if (onSd) {
11607                                // Install flag overrides everything.
11608                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11609                            }
11610                            // If current upgrade specifies particular preference
11611                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11612                                // Application explicitly specified internal.
11613                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11614                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11615                                // App explictly prefers external. Let policy decide
11616                            } else {
11617                                // Prefer previous location
11618                                if (isExternal(installedPkg)) {
11619                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11620                                }
11621                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11622                            }
11623                        }
11624                    } else {
11625                        // Invalid install. Return error code
11626                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11627                    }
11628                }
11629            }
11630            // All the special cases have been taken care of.
11631            // Return result based on recommended install location.
11632            if (onSd) {
11633                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11634            }
11635            return pkgLite.recommendedInstallLocation;
11636        }
11637
11638        /*
11639         * Invoke remote method to get package information and install
11640         * location values. Override install location based on default
11641         * policy if needed and then create install arguments based
11642         * on the install location.
11643         */
11644        public void handleStartCopy() throws RemoteException {
11645            int ret = PackageManager.INSTALL_SUCCEEDED;
11646
11647            // If we're already staged, we've firmly committed to an install location
11648            if (origin.staged) {
11649                if (origin.file != null) {
11650                    installFlags |= PackageManager.INSTALL_INTERNAL;
11651                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11652                } else if (origin.cid != null) {
11653                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11654                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11655                } else {
11656                    throw new IllegalStateException("Invalid stage location");
11657                }
11658            }
11659
11660            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11661            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11662            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11663            PackageInfoLite pkgLite = null;
11664
11665            if (onInt && onSd) {
11666                // Check if both bits are set.
11667                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11668                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11669            } else if (onSd && ephemeral) {
11670                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11671                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11672            } else {
11673                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11674                        packageAbiOverride);
11675
11676                if (DEBUG_EPHEMERAL && ephemeral) {
11677                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11678                }
11679
11680                /*
11681                 * If we have too little free space, try to free cache
11682                 * before giving up.
11683                 */
11684                if (!origin.staged && pkgLite.recommendedInstallLocation
11685                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11686                    // TODO: focus freeing disk space on the target device
11687                    final StorageManager storage = StorageManager.from(mContext);
11688                    final long lowThreshold = storage.getStorageLowBytes(
11689                            Environment.getDataDirectory());
11690
11691                    final long sizeBytes = mContainerService.calculateInstalledSize(
11692                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11693
11694                    try {
11695                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11696                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11697                                installFlags, packageAbiOverride);
11698                    } catch (InstallerException e) {
11699                        Slog.w(TAG, "Failed to free cache", e);
11700                    }
11701
11702                    /*
11703                     * The cache free must have deleted the file we
11704                     * downloaded to install.
11705                     *
11706                     * TODO: fix the "freeCache" call to not delete
11707                     *       the file we care about.
11708                     */
11709                    if (pkgLite.recommendedInstallLocation
11710                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11711                        pkgLite.recommendedInstallLocation
11712                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11713                    }
11714                }
11715            }
11716
11717            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11718                int loc = pkgLite.recommendedInstallLocation;
11719                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11720                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11721                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11722                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11723                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11724                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11725                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11726                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11727                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11728                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11729                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11730                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11731                } else {
11732                    // Override with defaults if needed.
11733                    loc = installLocationPolicy(pkgLite);
11734                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11735                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11736                    } else if (!onSd && !onInt) {
11737                        // Override install location with flags
11738                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11739                            // Set the flag to install on external media.
11740                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11741                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11742                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11743                            if (DEBUG_EPHEMERAL) {
11744                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11745                            }
11746                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11747                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11748                                    |PackageManager.INSTALL_INTERNAL);
11749                        } else {
11750                            // Make sure the flag for installing on external
11751                            // media is unset
11752                            installFlags |= PackageManager.INSTALL_INTERNAL;
11753                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11754                        }
11755                    }
11756                }
11757            }
11758
11759            final InstallArgs args = createInstallArgs(this);
11760            mArgs = args;
11761
11762            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11763                // TODO: http://b/22976637
11764                // Apps installed for "all" users use the device owner to verify the app
11765                UserHandle verifierUser = getUser();
11766                if (verifierUser == UserHandle.ALL) {
11767                    verifierUser = UserHandle.SYSTEM;
11768                }
11769
11770                /*
11771                 * Determine if we have any installed package verifiers. If we
11772                 * do, then we'll defer to them to verify the packages.
11773                 */
11774                final int requiredUid = mRequiredVerifierPackage == null ? -1
11775                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11776                                verifierUser.getIdentifier());
11777                if (!origin.existing && requiredUid != -1
11778                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11779                    final Intent verification = new Intent(
11780                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11781                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11782                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11783                            PACKAGE_MIME_TYPE);
11784                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11785
11786                    // Query all live verifiers based on current user state
11787                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11788                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11789
11790                    if (DEBUG_VERIFY) {
11791                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11792                                + verification.toString() + " with " + pkgLite.verifiers.length
11793                                + " optional verifiers");
11794                    }
11795
11796                    final int verificationId = mPendingVerificationToken++;
11797
11798                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11799
11800                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11801                            installerPackageName);
11802
11803                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11804                            installFlags);
11805
11806                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11807                            pkgLite.packageName);
11808
11809                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11810                            pkgLite.versionCode);
11811
11812                    if (verificationInfo != null) {
11813                        if (verificationInfo.originatingUri != null) {
11814                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11815                                    verificationInfo.originatingUri);
11816                        }
11817                        if (verificationInfo.referrer != null) {
11818                            verification.putExtra(Intent.EXTRA_REFERRER,
11819                                    verificationInfo.referrer);
11820                        }
11821                        if (verificationInfo.originatingUid >= 0) {
11822                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11823                                    verificationInfo.originatingUid);
11824                        }
11825                        if (verificationInfo.installerUid >= 0) {
11826                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11827                                    verificationInfo.installerUid);
11828                        }
11829                    }
11830
11831                    final PackageVerificationState verificationState = new PackageVerificationState(
11832                            requiredUid, args);
11833
11834                    mPendingVerification.append(verificationId, verificationState);
11835
11836                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11837                            receivers, verificationState);
11838
11839                    /*
11840                     * If any sufficient verifiers were listed in the package
11841                     * manifest, attempt to ask them.
11842                     */
11843                    if (sufficientVerifiers != null) {
11844                        final int N = sufficientVerifiers.size();
11845                        if (N == 0) {
11846                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11847                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11848                        } else {
11849                            for (int i = 0; i < N; i++) {
11850                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11851
11852                                final Intent sufficientIntent = new Intent(verification);
11853                                sufficientIntent.setComponent(verifierComponent);
11854                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11855                            }
11856                        }
11857                    }
11858
11859                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11860                            mRequiredVerifierPackage, receivers);
11861                    if (ret == PackageManager.INSTALL_SUCCEEDED
11862                            && mRequiredVerifierPackage != null) {
11863                        Trace.asyncTraceBegin(
11864                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11865                        /*
11866                         * Send the intent to the required verification agent,
11867                         * but only start the verification timeout after the
11868                         * target BroadcastReceivers have run.
11869                         */
11870                        verification.setComponent(requiredVerifierComponent);
11871                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11872                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11873                                new BroadcastReceiver() {
11874                                    @Override
11875                                    public void onReceive(Context context, Intent intent) {
11876                                        final Message msg = mHandler
11877                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11878                                        msg.arg1 = verificationId;
11879                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11880                                    }
11881                                }, null, 0, null, null);
11882
11883                        /*
11884                         * We don't want the copy to proceed until verification
11885                         * succeeds, so null out this field.
11886                         */
11887                        mArgs = null;
11888                    }
11889                } else {
11890                    /*
11891                     * No package verification is enabled, so immediately start
11892                     * the remote call to initiate copy using temporary file.
11893                     */
11894                    ret = args.copyApk(mContainerService, true);
11895                }
11896            }
11897
11898            mRet = ret;
11899        }
11900
11901        @Override
11902        void handleReturnCode() {
11903            // If mArgs is null, then MCS couldn't be reached. When it
11904            // reconnects, it will try again to install. At that point, this
11905            // will succeed.
11906            if (mArgs != null) {
11907                processPendingInstall(mArgs, mRet);
11908            }
11909        }
11910
11911        @Override
11912        void handleServiceError() {
11913            mArgs = createInstallArgs(this);
11914            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11915        }
11916
11917        public boolean isForwardLocked() {
11918            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11919        }
11920    }
11921
11922    /**
11923     * Used during creation of InstallArgs
11924     *
11925     * @param installFlags package installation flags
11926     * @return true if should be installed on external storage
11927     */
11928    private static boolean installOnExternalAsec(int installFlags) {
11929        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11930            return false;
11931        }
11932        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11933            return true;
11934        }
11935        return false;
11936    }
11937
11938    /**
11939     * Used during creation of InstallArgs
11940     *
11941     * @param installFlags package installation flags
11942     * @return true if should be installed as forward locked
11943     */
11944    private static boolean installForwardLocked(int installFlags) {
11945        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11946    }
11947
11948    private InstallArgs createInstallArgs(InstallParams params) {
11949        if (params.move != null) {
11950            return new MoveInstallArgs(params);
11951        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11952            return new AsecInstallArgs(params);
11953        } else {
11954            return new FileInstallArgs(params);
11955        }
11956    }
11957
11958    /**
11959     * Create args that describe an existing installed package. Typically used
11960     * when cleaning up old installs, or used as a move source.
11961     */
11962    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11963            String resourcePath, String[] instructionSets) {
11964        final boolean isInAsec;
11965        if (installOnExternalAsec(installFlags)) {
11966            /* Apps on SD card are always in ASEC containers. */
11967            isInAsec = true;
11968        } else if (installForwardLocked(installFlags)
11969                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11970            /*
11971             * Forward-locked apps are only in ASEC containers if they're the
11972             * new style
11973             */
11974            isInAsec = true;
11975        } else {
11976            isInAsec = false;
11977        }
11978
11979        if (isInAsec) {
11980            return new AsecInstallArgs(codePath, instructionSets,
11981                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11982        } else {
11983            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11984        }
11985    }
11986
11987    static abstract class InstallArgs {
11988        /** @see InstallParams#origin */
11989        final OriginInfo origin;
11990        /** @see InstallParams#move */
11991        final MoveInfo move;
11992
11993        final IPackageInstallObserver2 observer;
11994        // Always refers to PackageManager flags only
11995        final int installFlags;
11996        final String installerPackageName;
11997        final String volumeUuid;
11998        final UserHandle user;
11999        final String abiOverride;
12000        final String[] installGrantPermissions;
12001        /** If non-null, drop an async trace when the install completes */
12002        final String traceMethod;
12003        final int traceCookie;
12004
12005        // The list of instruction sets supported by this app. This is currently
12006        // only used during the rmdex() phase to clean up resources. We can get rid of this
12007        // if we move dex files under the common app path.
12008        /* nullable */ String[] instructionSets;
12009
12010        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12011                int installFlags, String installerPackageName, String volumeUuid,
12012                UserHandle user, String[] instructionSets,
12013                String abiOverride, String[] installGrantPermissions,
12014                String traceMethod, int traceCookie) {
12015            this.origin = origin;
12016            this.move = move;
12017            this.installFlags = installFlags;
12018            this.observer = observer;
12019            this.installerPackageName = installerPackageName;
12020            this.volumeUuid = volumeUuid;
12021            this.user = user;
12022            this.instructionSets = instructionSets;
12023            this.abiOverride = abiOverride;
12024            this.installGrantPermissions = installGrantPermissions;
12025            this.traceMethod = traceMethod;
12026            this.traceCookie = traceCookie;
12027        }
12028
12029        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12030        abstract int doPreInstall(int status);
12031
12032        /**
12033         * Rename package into final resting place. All paths on the given
12034         * scanned package should be updated to reflect the rename.
12035         */
12036        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12037        abstract int doPostInstall(int status, int uid);
12038
12039        /** @see PackageSettingBase#codePathString */
12040        abstract String getCodePath();
12041        /** @see PackageSettingBase#resourcePathString */
12042        abstract String getResourcePath();
12043
12044        // Need installer lock especially for dex file removal.
12045        abstract void cleanUpResourcesLI();
12046        abstract boolean doPostDeleteLI(boolean delete);
12047
12048        /**
12049         * Called before the source arguments are copied. This is used mostly
12050         * for MoveParams when it needs to read the source file to put it in the
12051         * destination.
12052         */
12053        int doPreCopy() {
12054            return PackageManager.INSTALL_SUCCEEDED;
12055        }
12056
12057        /**
12058         * Called after the source arguments are copied. This is used mostly for
12059         * MoveParams when it needs to read the source file to put it in the
12060         * destination.
12061         *
12062         * @return
12063         */
12064        int doPostCopy(int uid) {
12065            return PackageManager.INSTALL_SUCCEEDED;
12066        }
12067
12068        protected boolean isFwdLocked() {
12069            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12070        }
12071
12072        protected boolean isExternalAsec() {
12073            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12074        }
12075
12076        protected boolean isEphemeral() {
12077            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12078        }
12079
12080        UserHandle getUser() {
12081            return user;
12082        }
12083    }
12084
12085    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12086        if (!allCodePaths.isEmpty()) {
12087            if (instructionSets == null) {
12088                throw new IllegalStateException("instructionSet == null");
12089            }
12090            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12091            for (String codePath : allCodePaths) {
12092                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12093                    try {
12094                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12095                    } catch (InstallerException ignored) {
12096                    }
12097                }
12098            }
12099        }
12100    }
12101
12102    /**
12103     * Logic to handle installation of non-ASEC applications, including copying
12104     * and renaming logic.
12105     */
12106    class FileInstallArgs extends InstallArgs {
12107        private File codeFile;
12108        private File resourceFile;
12109
12110        // Example topology:
12111        // /data/app/com.example/base.apk
12112        // /data/app/com.example/split_foo.apk
12113        // /data/app/com.example/lib/arm/libfoo.so
12114        // /data/app/com.example/lib/arm64/libfoo.so
12115        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12116
12117        /** New install */
12118        FileInstallArgs(InstallParams params) {
12119            super(params.origin, params.move, params.observer, params.installFlags,
12120                    params.installerPackageName, params.volumeUuid,
12121                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12122                    params.grantedRuntimePermissions,
12123                    params.traceMethod, params.traceCookie);
12124            if (isFwdLocked()) {
12125                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12126            }
12127        }
12128
12129        /** Existing install */
12130        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12131            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12132                    null, null, null, 0);
12133            this.codeFile = (codePath != null) ? new File(codePath) : null;
12134            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12135        }
12136
12137        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12138            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12139            try {
12140                return doCopyApk(imcs, temp);
12141            } finally {
12142                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12143            }
12144        }
12145
12146        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12147            if (origin.staged) {
12148                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12149                codeFile = origin.file;
12150                resourceFile = origin.file;
12151                return PackageManager.INSTALL_SUCCEEDED;
12152            }
12153
12154            try {
12155                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12156                final File tempDir =
12157                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12158                codeFile = tempDir;
12159                resourceFile = tempDir;
12160            } catch (IOException e) {
12161                Slog.w(TAG, "Failed to create copy file: " + e);
12162                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12163            }
12164
12165            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12166                @Override
12167                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12168                    if (!FileUtils.isValidExtFilename(name)) {
12169                        throw new IllegalArgumentException("Invalid filename: " + name);
12170                    }
12171                    try {
12172                        final File file = new File(codeFile, name);
12173                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12174                                O_RDWR | O_CREAT, 0644);
12175                        Os.chmod(file.getAbsolutePath(), 0644);
12176                        return new ParcelFileDescriptor(fd);
12177                    } catch (ErrnoException e) {
12178                        throw new RemoteException("Failed to open: " + e.getMessage());
12179                    }
12180                }
12181            };
12182
12183            int ret = PackageManager.INSTALL_SUCCEEDED;
12184            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12185            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12186                Slog.e(TAG, "Failed to copy package");
12187                return ret;
12188            }
12189
12190            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12191            NativeLibraryHelper.Handle handle = null;
12192            try {
12193                handle = NativeLibraryHelper.Handle.create(codeFile);
12194                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12195                        abiOverride);
12196            } catch (IOException e) {
12197                Slog.e(TAG, "Copying native libraries failed", e);
12198                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12199            } finally {
12200                IoUtils.closeQuietly(handle);
12201            }
12202
12203            return ret;
12204        }
12205
12206        int doPreInstall(int status) {
12207            if (status != PackageManager.INSTALL_SUCCEEDED) {
12208                cleanUp();
12209            }
12210            return status;
12211        }
12212
12213        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12214            if (status != PackageManager.INSTALL_SUCCEEDED) {
12215                cleanUp();
12216                return false;
12217            }
12218
12219            final File targetDir = codeFile.getParentFile();
12220            final File beforeCodeFile = codeFile;
12221            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12222
12223            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12224            try {
12225                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12226            } catch (ErrnoException e) {
12227                Slog.w(TAG, "Failed to rename", e);
12228                return false;
12229            }
12230
12231            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12232                Slog.w(TAG, "Failed to restorecon");
12233                return false;
12234            }
12235
12236            // Reflect the rename internally
12237            codeFile = afterCodeFile;
12238            resourceFile = afterCodeFile;
12239
12240            // Reflect the rename in scanned details
12241            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12242            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12243                    afterCodeFile, pkg.baseCodePath));
12244            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12245                    afterCodeFile, pkg.splitCodePaths));
12246
12247            // Reflect the rename in app info
12248            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12249            pkg.setApplicationInfoCodePath(pkg.codePath);
12250            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12251            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12252            pkg.setApplicationInfoResourcePath(pkg.codePath);
12253            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12254            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12255
12256            return true;
12257        }
12258
12259        int doPostInstall(int status, int uid) {
12260            if (status != PackageManager.INSTALL_SUCCEEDED) {
12261                cleanUp();
12262            }
12263            return status;
12264        }
12265
12266        @Override
12267        String getCodePath() {
12268            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12269        }
12270
12271        @Override
12272        String getResourcePath() {
12273            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12274        }
12275
12276        private boolean cleanUp() {
12277            if (codeFile == null || !codeFile.exists()) {
12278                return false;
12279            }
12280
12281            removeCodePathLI(codeFile);
12282
12283            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12284                resourceFile.delete();
12285            }
12286
12287            return true;
12288        }
12289
12290        void cleanUpResourcesLI() {
12291            // Try enumerating all code paths before deleting
12292            List<String> allCodePaths = Collections.EMPTY_LIST;
12293            if (codeFile != null && codeFile.exists()) {
12294                try {
12295                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12296                    allCodePaths = pkg.getAllCodePaths();
12297                } catch (PackageParserException e) {
12298                    // Ignored; we tried our best
12299                }
12300            }
12301
12302            cleanUp();
12303            removeDexFiles(allCodePaths, instructionSets);
12304        }
12305
12306        boolean doPostDeleteLI(boolean delete) {
12307            // XXX err, shouldn't we respect the delete flag?
12308            cleanUpResourcesLI();
12309            return true;
12310        }
12311    }
12312
12313    private boolean isAsecExternal(String cid) {
12314        final String asecPath = PackageHelper.getSdFilesystem(cid);
12315        return !asecPath.startsWith(mAsecInternalPath);
12316    }
12317
12318    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12319            PackageManagerException {
12320        if (copyRet < 0) {
12321            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12322                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12323                throw new PackageManagerException(copyRet, message);
12324            }
12325        }
12326    }
12327
12328    /**
12329     * Extract the MountService "container ID" from the full code path of an
12330     * .apk.
12331     */
12332    static String cidFromCodePath(String fullCodePath) {
12333        int eidx = fullCodePath.lastIndexOf("/");
12334        String subStr1 = fullCodePath.substring(0, eidx);
12335        int sidx = subStr1.lastIndexOf("/");
12336        return subStr1.substring(sidx+1, eidx);
12337    }
12338
12339    /**
12340     * Logic to handle installation of ASEC applications, including copying and
12341     * renaming logic.
12342     */
12343    class AsecInstallArgs extends InstallArgs {
12344        static final String RES_FILE_NAME = "pkg.apk";
12345        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12346
12347        String cid;
12348        String packagePath;
12349        String resourcePath;
12350
12351        /** New install */
12352        AsecInstallArgs(InstallParams params) {
12353            super(params.origin, params.move, params.observer, params.installFlags,
12354                    params.installerPackageName, params.volumeUuid,
12355                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12356                    params.grantedRuntimePermissions,
12357                    params.traceMethod, params.traceCookie);
12358        }
12359
12360        /** Existing install */
12361        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12362                        boolean isExternal, boolean isForwardLocked) {
12363            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12364                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12365                    instructionSets, null, null, null, 0);
12366            // Hackily pretend we're still looking at a full code path
12367            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12368                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12369            }
12370
12371            // Extract cid from fullCodePath
12372            int eidx = fullCodePath.lastIndexOf("/");
12373            String subStr1 = fullCodePath.substring(0, eidx);
12374            int sidx = subStr1.lastIndexOf("/");
12375            cid = subStr1.substring(sidx+1, eidx);
12376            setMountPath(subStr1);
12377        }
12378
12379        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12380            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12381                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12382                    instructionSets, null, null, null, 0);
12383            this.cid = cid;
12384            setMountPath(PackageHelper.getSdDir(cid));
12385        }
12386
12387        void createCopyFile() {
12388            cid = mInstallerService.allocateExternalStageCidLegacy();
12389        }
12390
12391        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12392            if (origin.staged && origin.cid != null) {
12393                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12394                cid = origin.cid;
12395                setMountPath(PackageHelper.getSdDir(cid));
12396                return PackageManager.INSTALL_SUCCEEDED;
12397            }
12398
12399            if (temp) {
12400                createCopyFile();
12401            } else {
12402                /*
12403                 * Pre-emptively destroy the container since it's destroyed if
12404                 * copying fails due to it existing anyway.
12405                 */
12406                PackageHelper.destroySdDir(cid);
12407            }
12408
12409            final String newMountPath = imcs.copyPackageToContainer(
12410                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12411                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12412
12413            if (newMountPath != null) {
12414                setMountPath(newMountPath);
12415                return PackageManager.INSTALL_SUCCEEDED;
12416            } else {
12417                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12418            }
12419        }
12420
12421        @Override
12422        String getCodePath() {
12423            return packagePath;
12424        }
12425
12426        @Override
12427        String getResourcePath() {
12428            return resourcePath;
12429        }
12430
12431        int doPreInstall(int status) {
12432            if (status != PackageManager.INSTALL_SUCCEEDED) {
12433                // Destroy container
12434                PackageHelper.destroySdDir(cid);
12435            } else {
12436                boolean mounted = PackageHelper.isContainerMounted(cid);
12437                if (!mounted) {
12438                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12439                            Process.SYSTEM_UID);
12440                    if (newMountPath != null) {
12441                        setMountPath(newMountPath);
12442                    } else {
12443                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12444                    }
12445                }
12446            }
12447            return status;
12448        }
12449
12450        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12451            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12452            String newMountPath = null;
12453            if (PackageHelper.isContainerMounted(cid)) {
12454                // Unmount the container
12455                if (!PackageHelper.unMountSdDir(cid)) {
12456                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12457                    return false;
12458                }
12459            }
12460            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12461                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12462                        " which might be stale. Will try to clean up.");
12463                // Clean up the stale container and proceed to recreate.
12464                if (!PackageHelper.destroySdDir(newCacheId)) {
12465                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12466                    return false;
12467                }
12468                // Successfully cleaned up stale container. Try to rename again.
12469                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12470                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12471                            + " inspite of cleaning it up.");
12472                    return false;
12473                }
12474            }
12475            if (!PackageHelper.isContainerMounted(newCacheId)) {
12476                Slog.w(TAG, "Mounting container " + newCacheId);
12477                newMountPath = PackageHelper.mountSdDir(newCacheId,
12478                        getEncryptKey(), Process.SYSTEM_UID);
12479            } else {
12480                newMountPath = PackageHelper.getSdDir(newCacheId);
12481            }
12482            if (newMountPath == null) {
12483                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12484                return false;
12485            }
12486            Log.i(TAG, "Succesfully renamed " + cid +
12487                    " to " + newCacheId +
12488                    " at new path: " + newMountPath);
12489            cid = newCacheId;
12490
12491            final File beforeCodeFile = new File(packagePath);
12492            setMountPath(newMountPath);
12493            final File afterCodeFile = new File(packagePath);
12494
12495            // Reflect the rename in scanned details
12496            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12497            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12498                    afterCodeFile, pkg.baseCodePath));
12499            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12500                    afterCodeFile, pkg.splitCodePaths));
12501
12502            // Reflect the rename in app info
12503            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12504            pkg.setApplicationInfoCodePath(pkg.codePath);
12505            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12506            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12507            pkg.setApplicationInfoResourcePath(pkg.codePath);
12508            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12509            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12510
12511            return true;
12512        }
12513
12514        private void setMountPath(String mountPath) {
12515            final File mountFile = new File(mountPath);
12516
12517            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12518            if (monolithicFile.exists()) {
12519                packagePath = monolithicFile.getAbsolutePath();
12520                if (isFwdLocked()) {
12521                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12522                } else {
12523                    resourcePath = packagePath;
12524                }
12525            } else {
12526                packagePath = mountFile.getAbsolutePath();
12527                resourcePath = packagePath;
12528            }
12529        }
12530
12531        int doPostInstall(int status, int uid) {
12532            if (status != PackageManager.INSTALL_SUCCEEDED) {
12533                cleanUp();
12534            } else {
12535                final int groupOwner;
12536                final String protectedFile;
12537                if (isFwdLocked()) {
12538                    groupOwner = UserHandle.getSharedAppGid(uid);
12539                    protectedFile = RES_FILE_NAME;
12540                } else {
12541                    groupOwner = -1;
12542                    protectedFile = null;
12543                }
12544
12545                if (uid < Process.FIRST_APPLICATION_UID
12546                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12547                    Slog.e(TAG, "Failed to finalize " + cid);
12548                    PackageHelper.destroySdDir(cid);
12549                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12550                }
12551
12552                boolean mounted = PackageHelper.isContainerMounted(cid);
12553                if (!mounted) {
12554                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12555                }
12556            }
12557            return status;
12558        }
12559
12560        private void cleanUp() {
12561            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12562
12563            // Destroy secure container
12564            PackageHelper.destroySdDir(cid);
12565        }
12566
12567        private List<String> getAllCodePaths() {
12568            final File codeFile = new File(getCodePath());
12569            if (codeFile != null && codeFile.exists()) {
12570                try {
12571                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12572                    return pkg.getAllCodePaths();
12573                } catch (PackageParserException e) {
12574                    // Ignored; we tried our best
12575                }
12576            }
12577            return Collections.EMPTY_LIST;
12578        }
12579
12580        void cleanUpResourcesLI() {
12581            // Enumerate all code paths before deleting
12582            cleanUpResourcesLI(getAllCodePaths());
12583        }
12584
12585        private void cleanUpResourcesLI(List<String> allCodePaths) {
12586            cleanUp();
12587            removeDexFiles(allCodePaths, instructionSets);
12588        }
12589
12590        String getPackageName() {
12591            return getAsecPackageName(cid);
12592        }
12593
12594        boolean doPostDeleteLI(boolean delete) {
12595            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12596            final List<String> allCodePaths = getAllCodePaths();
12597            boolean mounted = PackageHelper.isContainerMounted(cid);
12598            if (mounted) {
12599                // Unmount first
12600                if (PackageHelper.unMountSdDir(cid)) {
12601                    mounted = false;
12602                }
12603            }
12604            if (!mounted && delete) {
12605                cleanUpResourcesLI(allCodePaths);
12606            }
12607            return !mounted;
12608        }
12609
12610        @Override
12611        int doPreCopy() {
12612            if (isFwdLocked()) {
12613                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12614                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12615                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12616                }
12617            }
12618
12619            return PackageManager.INSTALL_SUCCEEDED;
12620        }
12621
12622        @Override
12623        int doPostCopy(int uid) {
12624            if (isFwdLocked()) {
12625                if (uid < Process.FIRST_APPLICATION_UID
12626                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12627                                RES_FILE_NAME)) {
12628                    Slog.e(TAG, "Failed to finalize " + cid);
12629                    PackageHelper.destroySdDir(cid);
12630                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12631                }
12632            }
12633
12634            return PackageManager.INSTALL_SUCCEEDED;
12635        }
12636    }
12637
12638    /**
12639     * Logic to handle movement of existing installed applications.
12640     */
12641    class MoveInstallArgs extends InstallArgs {
12642        private File codeFile;
12643        private File resourceFile;
12644
12645        /** New install */
12646        MoveInstallArgs(InstallParams params) {
12647            super(params.origin, params.move, params.observer, params.installFlags,
12648                    params.installerPackageName, params.volumeUuid,
12649                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12650                    params.grantedRuntimePermissions,
12651                    params.traceMethod, params.traceCookie);
12652        }
12653
12654        int copyApk(IMediaContainerService imcs, boolean temp) {
12655            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12656                    + move.fromUuid + " to " + move.toUuid);
12657            synchronized (mInstaller) {
12658                try {
12659                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12660                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12661                } catch (InstallerException e) {
12662                    Slog.w(TAG, "Failed to move app", e);
12663                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12664                }
12665            }
12666
12667            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12668            resourceFile = codeFile;
12669            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12670
12671            return PackageManager.INSTALL_SUCCEEDED;
12672        }
12673
12674        int doPreInstall(int status) {
12675            if (status != PackageManager.INSTALL_SUCCEEDED) {
12676                cleanUp(move.toUuid);
12677            }
12678            return status;
12679        }
12680
12681        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12682            if (status != PackageManager.INSTALL_SUCCEEDED) {
12683                cleanUp(move.toUuid);
12684                return false;
12685            }
12686
12687            // Reflect the move in app info
12688            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12689            pkg.setApplicationInfoCodePath(pkg.codePath);
12690            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12691            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12692            pkg.setApplicationInfoResourcePath(pkg.codePath);
12693            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12694            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12695
12696            return true;
12697        }
12698
12699        int doPostInstall(int status, int uid) {
12700            if (status == PackageManager.INSTALL_SUCCEEDED) {
12701                cleanUp(move.fromUuid);
12702            } else {
12703                cleanUp(move.toUuid);
12704            }
12705            return status;
12706        }
12707
12708        @Override
12709        String getCodePath() {
12710            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12711        }
12712
12713        @Override
12714        String getResourcePath() {
12715            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12716        }
12717
12718        private boolean cleanUp(String volumeUuid) {
12719            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12720                    move.dataAppName);
12721            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12722            synchronized (mInstallLock) {
12723                // Clean up both app data and code
12724                removeDataDirsLI(volumeUuid, move.packageName);
12725                removeCodePathLI(codeFile);
12726            }
12727            return true;
12728        }
12729
12730        void cleanUpResourcesLI() {
12731            throw new UnsupportedOperationException();
12732        }
12733
12734        boolean doPostDeleteLI(boolean delete) {
12735            throw new UnsupportedOperationException();
12736        }
12737    }
12738
12739    static String getAsecPackageName(String packageCid) {
12740        int idx = packageCid.lastIndexOf("-");
12741        if (idx == -1) {
12742            return packageCid;
12743        }
12744        return packageCid.substring(0, idx);
12745    }
12746
12747    // Utility method used to create code paths based on package name and available index.
12748    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12749        String idxStr = "";
12750        int idx = 1;
12751        // Fall back to default value of idx=1 if prefix is not
12752        // part of oldCodePath
12753        if (oldCodePath != null) {
12754            String subStr = oldCodePath;
12755            // Drop the suffix right away
12756            if (suffix != null && subStr.endsWith(suffix)) {
12757                subStr = subStr.substring(0, subStr.length() - suffix.length());
12758            }
12759            // If oldCodePath already contains prefix find out the
12760            // ending index to either increment or decrement.
12761            int sidx = subStr.lastIndexOf(prefix);
12762            if (sidx != -1) {
12763                subStr = subStr.substring(sidx + prefix.length());
12764                if (subStr != null) {
12765                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12766                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12767                    }
12768                    try {
12769                        idx = Integer.parseInt(subStr);
12770                        if (idx <= 1) {
12771                            idx++;
12772                        } else {
12773                            idx--;
12774                        }
12775                    } catch(NumberFormatException e) {
12776                    }
12777                }
12778            }
12779        }
12780        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12781        return prefix + idxStr;
12782    }
12783
12784    private File getNextCodePath(File targetDir, String packageName) {
12785        int suffix = 1;
12786        File result;
12787        do {
12788            result = new File(targetDir, packageName + "-" + suffix);
12789            suffix++;
12790        } while (result.exists());
12791        return result;
12792    }
12793
12794    // Utility method that returns the relative package path with respect
12795    // to the installation directory. Like say for /data/data/com.test-1.apk
12796    // string com.test-1 is returned.
12797    static String deriveCodePathName(String codePath) {
12798        if (codePath == null) {
12799            return null;
12800        }
12801        final File codeFile = new File(codePath);
12802        final String name = codeFile.getName();
12803        if (codeFile.isDirectory()) {
12804            return name;
12805        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12806            final int lastDot = name.lastIndexOf('.');
12807            return name.substring(0, lastDot);
12808        } else {
12809            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12810            return null;
12811        }
12812    }
12813
12814    static class PackageInstalledInfo {
12815        String name;
12816        int uid;
12817        // The set of users that originally had this package installed.
12818        int[] origUsers;
12819        // The set of users that now have this package installed.
12820        int[] newUsers;
12821        PackageParser.Package pkg;
12822        int returnCode;
12823        String returnMsg;
12824        PackageRemovedInfo removedInfo;
12825        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12826
12827        public void setError(int code, String msg) {
12828            setReturnCode(code);
12829            setReturnMessage(msg);
12830            Slog.w(TAG, msg);
12831        }
12832
12833        public void setError(String msg, PackageParserException e) {
12834            setReturnCode(e.error);
12835            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12836            Slog.w(TAG, msg, e);
12837        }
12838
12839        public void setError(String msg, PackageManagerException e) {
12840            returnCode = e.error;
12841            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12842            Slog.w(TAG, msg, e);
12843        }
12844
12845        public void setReturnCode(int returnCode) {
12846            this.returnCode = returnCode;
12847            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12848            for (int i = 0; i < childCount; i++) {
12849                addedChildPackages.valueAt(i).returnCode = returnCode;
12850            }
12851        }
12852
12853        private void setReturnMessage(String returnMsg) {
12854            this.returnMsg = returnMsg;
12855            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12856            for (int i = 0; i < childCount; i++) {
12857                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12858            }
12859        }
12860
12861        // In some error cases we want to convey more info back to the observer
12862        String origPackage;
12863        String origPermission;
12864    }
12865
12866    /*
12867     * Install a non-existing package.
12868     */
12869    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12870            UserHandle user, String installerPackageName, String volumeUuid,
12871            PackageInstalledInfo res) {
12872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12873
12874        // Remember this for later, in case we need to rollback this install
12875        String pkgName = pkg.packageName;
12876
12877        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12878
12879        synchronized(mPackages) {
12880            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12881                // A package with the same name is already installed, though
12882                // it has been renamed to an older name.  The package we
12883                // are trying to install should be installed as an update to
12884                // the existing one, but that has not been requested, so bail.
12885                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12886                        + " without first uninstalling package running as "
12887                        + mSettings.mRenamedPackages.get(pkgName));
12888                return;
12889            }
12890            if (mPackages.containsKey(pkgName)) {
12891                // Don't allow installation over an existing package with the same name.
12892                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12893                        + " without first uninstalling.");
12894                return;
12895            }
12896        }
12897
12898        try {
12899            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12900                    System.currentTimeMillis(), user);
12901
12902            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12903
12904            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12905                prepareAppDataAfterInstall(newPackage);
12906
12907            } else {
12908                // Remove package from internal structures, but keep around any
12909                // data that might have already existed
12910                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12911                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12912            }
12913        } catch (PackageManagerException e) {
12914            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12915        }
12916
12917        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12918    }
12919
12920    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12921        // Can't rotate keys during boot or if sharedUser.
12922        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12923                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12924            return false;
12925        }
12926        // app is using upgradeKeySets; make sure all are valid
12927        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12928        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12929        for (int i = 0; i < upgradeKeySets.length; i++) {
12930            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12931                Slog.wtf(TAG, "Package "
12932                         + (oldPs.name != null ? oldPs.name : "<null>")
12933                         + " contains upgrade-key-set reference to unknown key-set: "
12934                         + upgradeKeySets[i]
12935                         + " reverting to signatures check.");
12936                return false;
12937            }
12938        }
12939        return true;
12940    }
12941
12942    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12943        // Upgrade keysets are being used.  Determine if new package has a superset of the
12944        // required keys.
12945        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12946        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12947        for (int i = 0; i < upgradeKeySets.length; i++) {
12948            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12949            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12950                return true;
12951            }
12952        }
12953        return false;
12954    }
12955
12956    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12957            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12958        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12959
12960        final PackageParser.Package oldPackage;
12961        final String pkgName = pkg.packageName;
12962        final int[] allUsers;
12963
12964        // First find the old package info and check signatures
12965        synchronized(mPackages) {
12966            oldPackage = mPackages.get(pkgName);
12967            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12968            if (isEphemeral && !oldIsEphemeral) {
12969                // can't downgrade from full to ephemeral
12970                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12971                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
12972                return;
12973            }
12974            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12975            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12976            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12977                if (!checkUpgradeKeySetLP(ps, pkg)) {
12978                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12979                            "New package not signed by keys specified by upgrade-keysets: "
12980                                    + pkgName);
12981                    return;
12982                }
12983            } else {
12984                // default to original signature matching
12985                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12986                        != PackageManager.SIGNATURE_MATCH) {
12987                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12988                            "New package has a different signature: " + pkgName);
12989                    return;
12990                }
12991            }
12992
12993            // In case of rollback, remember per-user/profile install state
12994            allUsers = sUserManager.getUserIds();
12995        }
12996
12997        // Update what is removed
12998        res.removedInfo = new PackageRemovedInfo();
12999        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13000        res.removedInfo.removedPackage = oldPackage.packageName;
13001        res.removedInfo.isUpdate = true;
13002        final int childCount = (oldPackage.childPackages != null)
13003                ? oldPackage.childPackages.size() : 0;
13004        for (int i = 0; i < childCount; i++) {
13005            boolean childPackageUpdated = false;
13006            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13007            if (res.addedChildPackages != null) {
13008                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13009                if (childRes != null) {
13010                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13011                    childRes.removedInfo.removedPackage = childPkg.packageName;
13012                    childRes.removedInfo.isUpdate = true;
13013                    childPackageUpdated = true;
13014                }
13015            }
13016            if (!childPackageUpdated) {
13017                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13018                childRemovedRes.removedPackage = childPkg.packageName;
13019                childRemovedRes.isUpdate = false;
13020                childRemovedRes.dataRemoved = true;
13021                synchronized (mPackages) {
13022                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13023                    if (childPs != null) {
13024                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13025                    }
13026                }
13027                if (res.removedInfo.removedChildPackages == null) {
13028                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13029                }
13030                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13031            }
13032        }
13033
13034        boolean sysPkg = (isSystemApp(oldPackage));
13035        if (sysPkg) {
13036            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13037                    user, allUsers, installerPackageName, res);
13038        } else {
13039            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13040                    user, allUsers, installerPackageName, res);
13041        }
13042    }
13043
13044    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13045            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13046            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13047        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13048                + deletedPackage);
13049
13050        String pkgName = deletedPackage.packageName;
13051        boolean deletedPkg = true;
13052        boolean addedPkg = false;
13053
13054        final long origUpdateTime = (pkg.mExtras != null)
13055                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13056
13057        // First delete the existing package while retaining the data directory
13058        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13059                res.removedInfo, true, pkg)) {
13060            // If the existing package wasn't successfully deleted
13061            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13062            deletedPkg = false;
13063        } else {
13064            // Successfully deleted the old package; proceed with replace.
13065
13066            // If deleted package lived in a container, give users a chance to
13067            // relinquish resources before killing.
13068            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13069                if (DEBUG_INSTALL) {
13070                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13071                }
13072                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13073                final ArrayList<String> pkgList = new ArrayList<String>(1);
13074                pkgList.add(deletedPackage.applicationInfo.packageName);
13075                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13076            }
13077
13078            deleteCodeCacheDirsLI(pkg);
13079
13080            try {
13081                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13082                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13083                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13084                prepareAppDataAfterInstall(newPackage);
13085                addedPkg = true;
13086            } catch (PackageManagerException e) {
13087                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13088            }
13089        }
13090
13091        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13092            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13093
13094            // Revert all internal state mutations and added folders for the failed install
13095            if (addedPkg) {
13096                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13097                        res.removedInfo, true, null);
13098            }
13099
13100            // Restore the old package
13101            if (deletedPkg) {
13102                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13103                File restoreFile = new File(deletedPackage.codePath);
13104                // Parse old package
13105                boolean oldExternal = isExternal(deletedPackage);
13106                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13107                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13108                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13109                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13110                try {
13111                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13112                            null);
13113                } catch (PackageManagerException e) {
13114                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13115                            + e.getMessage());
13116                    return;
13117                }
13118
13119                synchronized (mPackages) {
13120                    // Ensure the installer package name up to date
13121                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13122
13123                    // Update permissions for restored package
13124                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13125
13126                    mSettings.writeLPr();
13127                }
13128
13129                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13130            }
13131        } else {
13132            synchronized (mPackages) {
13133                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13134                if (ps != null) {
13135                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13136                    if (res.removedInfo.removedChildPackages != null) {
13137                        final int childCount = res.removedInfo.removedChildPackages.size();
13138                        // Iterate in reverse as we may modify the collection
13139                        for (int i = childCount - 1; i >= 0; i--) {
13140                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13141                            if (res.addedChildPackages.containsKey(childPackageName)) {
13142                                res.removedInfo.removedChildPackages.removeAt(i);
13143                            } else {
13144                                PackageRemovedInfo childInfo = res.removedInfo
13145                                        .removedChildPackages.valueAt(i);
13146                                childInfo.removedForAllUsers = mPackages.get(
13147                                        childInfo.removedPackage) == null;
13148                            }
13149                        }
13150                    }
13151                }
13152            }
13153        }
13154    }
13155
13156    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13157            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13158            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13159        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13160                + ", old=" + deletedPackage);
13161
13162        final boolean disabledSystem;
13163
13164        // Set the system/privileged flags as needed
13165        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13166        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13167                != 0) {
13168            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13169        }
13170
13171        // Kill package processes including services, providers, etc.
13172        killPackage(deletedPackage, "replace sys pkg");
13173
13174        // Remove existing system package
13175        removePackageLI(deletedPackage, true);
13176
13177        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13178        if (!disabledSystem) {
13179            // We didn't need to disable the .apk as a current system package,
13180            // which means we are replacing another update that is already
13181            // installed.  We need to make sure to delete the older one's .apk.
13182            res.removedInfo.args = createInstallArgsForExisting(0,
13183                    deletedPackage.applicationInfo.getCodePath(),
13184                    deletedPackage.applicationInfo.getResourcePath(),
13185                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13186        } else {
13187            res.removedInfo.args = null;
13188        }
13189
13190        // Successfully disabled the old package. Now proceed with re-installation
13191        deleteCodeCacheDirsLI(pkg);
13192
13193        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13194        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13195                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13196
13197        PackageParser.Package newPackage = null;
13198        try {
13199            // Add the package to the internal data structures
13200            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13201
13202            // Set the update and install times
13203            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13204            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13205                    System.currentTimeMillis());
13206
13207            // Check for shared user id changes
13208            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13209                    deletedPackage, newPackage);
13210            if (invalidPackageName != null) {
13211                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13212                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13213                                + " to " + invalidPackageName);
13214            }
13215
13216            // Update the package dynamic state if succeeded
13217            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13218                // Now that the install succeeded make sure we remove data
13219                // directories for any child package the update removed.
13220                final int deletedChildCount = (deletedPackage.childPackages != null)
13221                        ? deletedPackage.childPackages.size() : 0;
13222                final int newChildCount = (newPackage.childPackages != null)
13223                        ? newPackage.childPackages.size() : 0;
13224                for (int i = 0; i < deletedChildCount; i++) {
13225                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13226                    boolean childPackageDeleted = true;
13227                    for (int j = 0; j < newChildCount; j++) {
13228                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13229                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13230                            childPackageDeleted = false;
13231                            break;
13232                        }
13233                    }
13234                    if (childPackageDeleted) {
13235                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13236                                deletedChildPkg.packageName);
13237                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13238                            PackageRemovedInfo removedChildRes = res.removedInfo
13239                                    .removedChildPackages.get(deletedChildPkg.packageName);
13240                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13241                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13242                        }
13243                    }
13244                }
13245
13246                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13247                prepareAppDataAfterInstall(newPackage);
13248            }
13249        } catch (PackageManagerException e) {
13250            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13251            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13252        }
13253
13254        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13255            // Re installation failed. Restore old information
13256            // Remove new pkg information
13257            if (newPackage != null) {
13258                removeInstalledPackageLI(newPackage, true);
13259            }
13260            // Add back the old system package
13261            try {
13262                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13263            } catch (PackageManagerException e) {
13264                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13265            }
13266
13267            synchronized (mPackages) {
13268                if (disabledSystem) {
13269                    enableSystemPackageLPw(deletedPackage);
13270                }
13271
13272                // Ensure the installer package name up to date
13273                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13274
13275                // Update permissions for restored package
13276                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13277
13278                mSettings.writeLPr();
13279            }
13280
13281            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13282                    + " after failed upgrade");
13283        }
13284    }
13285
13286    /**
13287     * Checks whether the parent or any of the child packages have a change shared
13288     * user. For a package to be a valid update the shred users of the parent and
13289     * the children should match. We may later support changing child shared users.
13290     * @param oldPkg The updated package.
13291     * @param newPkg The update package.
13292     * @return The shared user that change between the versions.
13293     */
13294    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13295            PackageParser.Package newPkg) {
13296        // Check parent shared user
13297        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13298            return newPkg.packageName;
13299        }
13300        // Check child shared users
13301        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13302        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13303        for (int i = 0; i < newChildCount; i++) {
13304            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13305            // If this child was present, did it have the same shared user?
13306            for (int j = 0; j < oldChildCount; j++) {
13307                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13308                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13309                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13310                    return newChildPkg.packageName;
13311                }
13312            }
13313        }
13314        return null;
13315    }
13316
13317    private void removeNativeBinariesLI(PackageSetting ps) {
13318        // Remove the lib path for the parent package
13319        if (ps != null) {
13320            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13321            // Remove the lib path for the child packages
13322            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13323            for (int i = 0; i < childCount; i++) {
13324                PackageSetting childPs = null;
13325                synchronized (mPackages) {
13326                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13327                }
13328                if (childPs != null) {
13329                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13330                            .legacyNativeLibraryPathString);
13331                }
13332            }
13333        }
13334    }
13335
13336    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13337        // Enable the parent package
13338        mSettings.enableSystemPackageLPw(pkg.packageName);
13339        // Enable the child packages
13340        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13341        for (int i = 0; i < childCount; i++) {
13342            PackageParser.Package childPkg = pkg.childPackages.get(i);
13343            mSettings.enableSystemPackageLPw(childPkg.packageName);
13344        }
13345    }
13346
13347    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13348            PackageParser.Package newPkg) {
13349        // Disable the parent package (parent always replaced)
13350        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13351        // Disable the child packages
13352        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13353        for (int i = 0; i < childCount; i++) {
13354            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13355            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13356            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13357        }
13358        return disabled;
13359    }
13360
13361    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13362            String installerPackageName) {
13363        // Enable the parent package
13364        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13365        // Enable the child packages
13366        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13367        for (int i = 0; i < childCount; i++) {
13368            PackageParser.Package childPkg = pkg.childPackages.get(i);
13369            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13370        }
13371    }
13372
13373    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13374        // Collect all used permissions in the UID
13375        ArraySet<String> usedPermissions = new ArraySet<>();
13376        final int packageCount = su.packages.size();
13377        for (int i = 0; i < packageCount; i++) {
13378            PackageSetting ps = su.packages.valueAt(i);
13379            if (ps.pkg == null) {
13380                continue;
13381            }
13382            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13383            for (int j = 0; j < requestedPermCount; j++) {
13384                String permission = ps.pkg.requestedPermissions.get(j);
13385                BasePermission bp = mSettings.mPermissions.get(permission);
13386                if (bp != null) {
13387                    usedPermissions.add(permission);
13388                }
13389            }
13390        }
13391
13392        PermissionsState permissionsState = su.getPermissionsState();
13393        // Prune install permissions
13394        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13395        final int installPermCount = installPermStates.size();
13396        for (int i = installPermCount - 1; i >= 0;  i--) {
13397            PermissionState permissionState = installPermStates.get(i);
13398            if (!usedPermissions.contains(permissionState.getName())) {
13399                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13400                if (bp != null) {
13401                    permissionsState.revokeInstallPermission(bp);
13402                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13403                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13404                }
13405            }
13406        }
13407
13408        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13409
13410        // Prune runtime permissions
13411        for (int userId : allUserIds) {
13412            List<PermissionState> runtimePermStates = permissionsState
13413                    .getRuntimePermissionStates(userId);
13414            final int runtimePermCount = runtimePermStates.size();
13415            for (int i = runtimePermCount - 1; i >= 0; i--) {
13416                PermissionState permissionState = runtimePermStates.get(i);
13417                if (!usedPermissions.contains(permissionState.getName())) {
13418                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13419                    if (bp != null) {
13420                        permissionsState.revokeRuntimePermission(bp, userId);
13421                        permissionsState.updatePermissionFlags(bp, userId,
13422                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13423                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13424                                runtimePermissionChangedUserIds, userId);
13425                    }
13426                }
13427            }
13428        }
13429
13430        return runtimePermissionChangedUserIds;
13431    }
13432
13433    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13434            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13435        // Update the parent package setting
13436        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13437                res, user);
13438        // Update the child packages setting
13439        final int childCount = (newPackage.childPackages != null)
13440                ? newPackage.childPackages.size() : 0;
13441        for (int i = 0; i < childCount; i++) {
13442            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13443            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13444            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13445                    childRes.origUsers, childRes, user);
13446        }
13447    }
13448
13449    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13450            String installerPackageName, int[] allUsers, int[] installedForUsers,
13451            PackageInstalledInfo res, UserHandle user) {
13452        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13453
13454        String pkgName = newPackage.packageName;
13455        synchronized (mPackages) {
13456            //write settings. the installStatus will be incomplete at this stage.
13457            //note that the new package setting would have already been
13458            //added to mPackages. It hasn't been persisted yet.
13459            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13460            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13461            mSettings.writeLPr();
13462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13463        }
13464
13465        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13466        synchronized (mPackages) {
13467            updatePermissionsLPw(newPackage.packageName, newPackage,
13468                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13469                            ? UPDATE_PERMISSIONS_ALL : 0));
13470            // For system-bundled packages, we assume that installing an upgraded version
13471            // of the package implies that the user actually wants to run that new code,
13472            // so we enable the package.
13473            PackageSetting ps = mSettings.mPackages.get(pkgName);
13474            final int userId = user.getIdentifier();
13475            if (ps != null) {
13476                if (isSystemApp(newPackage)) {
13477                    if (DEBUG_INSTALL) {
13478                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13479                    }
13480                    // Enable system package for requested users
13481                    if (res.origUsers != null) {
13482                        for (int origUserId : res.origUsers) {
13483                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13484                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13485                                        origUserId, installerPackageName);
13486                            }
13487                        }
13488                    }
13489                    // Also convey the prior install/uninstall state
13490                    if (allUsers != null && installedForUsers != null) {
13491                        for (int currentUserId : allUsers) {
13492                            final boolean installed = ArrayUtils.contains(
13493                                    installedForUsers, currentUserId);
13494                            if (DEBUG_INSTALL) {
13495                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13496                            }
13497                            ps.setInstalled(installed, currentUserId);
13498                        }
13499                        // these install state changes will be persisted in the
13500                        // upcoming call to mSettings.writeLPr().
13501                    }
13502                }
13503                // It's implied that when a user requests installation, they want the app to be
13504                // installed and enabled.
13505                if (userId != UserHandle.USER_ALL) {
13506                    ps.setInstalled(true, userId);
13507                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13508                }
13509            }
13510            res.name = pkgName;
13511            res.uid = newPackage.applicationInfo.uid;
13512            res.pkg = newPackage;
13513            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13514            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13515            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13516            //to update install status
13517            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13518            mSettings.writeLPr();
13519            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13520        }
13521
13522        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13523    }
13524
13525    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13526        try {
13527            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13528            installPackageLI(args, res);
13529        } finally {
13530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13531        }
13532    }
13533
13534    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13535        final int installFlags = args.installFlags;
13536        final String installerPackageName = args.installerPackageName;
13537        final String volumeUuid = args.volumeUuid;
13538        final File tmpPackageFile = new File(args.getCodePath());
13539        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13540        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13541                || (args.volumeUuid != null));
13542        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13543        boolean replace = false;
13544        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13545        if (args.move != null) {
13546            // moving a complete application; perform an initial scan on the new install location
13547            scanFlags |= SCAN_INITIAL;
13548        }
13549
13550        // Result object to be returned
13551        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13552
13553        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13554
13555        // Sanity check
13556        if (ephemeral && (forwardLocked || onExternal)) {
13557            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13558                    + " external=" + onExternal);
13559            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13560            return;
13561        }
13562
13563        // Retrieve PackageSettings and parse package
13564        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13565                | PackageParser.PARSE_ENFORCE_CODE
13566                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13567                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13568                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13569        PackageParser pp = new PackageParser();
13570        pp.setSeparateProcesses(mSeparateProcesses);
13571        pp.setDisplayMetrics(mMetrics);
13572
13573        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13574        final PackageParser.Package pkg;
13575        try {
13576            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13577        } catch (PackageParserException e) {
13578            res.setError("Failed parse during installPackageLI", e);
13579            return;
13580        } finally {
13581            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13582        }
13583
13584        // If we are installing a clustered package add results for the children
13585        if (pkg.childPackages != null) {
13586            synchronized (mPackages) {
13587                final int childCount = pkg.childPackages.size();
13588                for (int i = 0; i < childCount; i++) {
13589                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13590                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13591                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13592                    childRes.pkg = childPkg;
13593                    childRes.name = childPkg.packageName;
13594                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13595                    if (childPs != null) {
13596                        childRes.origUsers = childPs.queryInstalledUsers(
13597                                sUserManager.getUserIds(), true);
13598                    }
13599                    if ((mPackages.containsKey(childPkg.packageName))) {
13600                        childRes.removedInfo = new PackageRemovedInfo();
13601                        childRes.removedInfo.removedPackage = childPkg.packageName;
13602                    }
13603                    if (res.addedChildPackages == null) {
13604                        res.addedChildPackages = new ArrayMap<>();
13605                    }
13606                    res.addedChildPackages.put(childPkg.packageName, childRes);
13607                }
13608            }
13609        }
13610
13611        // If package doesn't declare API override, mark that we have an install
13612        // time CPU ABI override.
13613        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13614            pkg.cpuAbiOverride = args.abiOverride;
13615        }
13616
13617        String pkgName = res.name = pkg.packageName;
13618        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13619            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13620                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13621                return;
13622            }
13623        }
13624
13625        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13626        try {
13627            PackageParser.collectCertificates(pkg, parseFlags);
13628        } catch (PackageParserException e) {
13629            res.setError("Failed collect during installPackageLI", e);
13630            return;
13631        } finally {
13632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13633        }
13634
13635        // Get rid of all references to package scan path via parser.
13636        pp = null;
13637        String oldCodePath = null;
13638        boolean systemApp = false;
13639        synchronized (mPackages) {
13640            // Check if installing already existing package
13641            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13642                String oldName = mSettings.mRenamedPackages.get(pkgName);
13643                if (pkg.mOriginalPackages != null
13644                        && pkg.mOriginalPackages.contains(oldName)
13645                        && mPackages.containsKey(oldName)) {
13646                    // This package is derived from an original package,
13647                    // and this device has been updating from that original
13648                    // name.  We must continue using the original name, so
13649                    // rename the new package here.
13650                    pkg.setPackageName(oldName);
13651                    pkgName = pkg.packageName;
13652                    replace = true;
13653                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13654                            + oldName + " pkgName=" + pkgName);
13655                } else if (mPackages.containsKey(pkgName)) {
13656                    // This package, under its official name, already exists
13657                    // on the device; we should replace it.
13658                    replace = true;
13659                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13660                }
13661
13662                // Child packages are installed through the parent package
13663                if (pkg.parentPackage != null) {
13664                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13665                            "Package " + pkg.packageName + " is child of package "
13666                                    + pkg.parentPackage.parentPackage + ". Child packages "
13667                                    + "can be updated only through the parent package.");
13668                    return;
13669                }
13670
13671                if (replace) {
13672                    // Prevent apps opting out from runtime permissions
13673                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13674                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13675                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13676                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13677                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13678                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13679                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13680                                        + " doesn't support runtime permissions but the old"
13681                                        + " target SDK " + oldTargetSdk + " does.");
13682                        return;
13683                    }
13684
13685                    // Prevent installing of child packages
13686                    if (oldPackage.parentPackage != null) {
13687                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13688                                "Package " + pkg.packageName + " is child of package "
13689                                        + oldPackage.parentPackage + ". Child packages "
13690                                        + "can be updated only through the parent package.");
13691                        return;
13692                    }
13693                }
13694            }
13695
13696            PackageSetting ps = mSettings.mPackages.get(pkgName);
13697            if (ps != null) {
13698                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13699
13700                // Quick sanity check that we're signed correctly if updating;
13701                // we'll check this again later when scanning, but we want to
13702                // bail early here before tripping over redefined permissions.
13703                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13704                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13705                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13706                                + pkg.packageName + " upgrade keys do not match the "
13707                                + "previously installed version");
13708                        return;
13709                    }
13710                } else {
13711                    try {
13712                        verifySignaturesLP(ps, pkg);
13713                    } catch (PackageManagerException e) {
13714                        res.setError(e.error, e.getMessage());
13715                        return;
13716                    }
13717                }
13718
13719                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13720                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13721                    systemApp = (ps.pkg.applicationInfo.flags &
13722                            ApplicationInfo.FLAG_SYSTEM) != 0;
13723                }
13724                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13725            }
13726
13727            // Check whether the newly-scanned package wants to define an already-defined perm
13728            int N = pkg.permissions.size();
13729            for (int i = N-1; i >= 0; i--) {
13730                PackageParser.Permission perm = pkg.permissions.get(i);
13731                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13732                if (bp != null) {
13733                    // If the defining package is signed with our cert, it's okay.  This
13734                    // also includes the "updating the same package" case, of course.
13735                    // "updating same package" could also involve key-rotation.
13736                    final boolean sigsOk;
13737                    if (bp.sourcePackage.equals(pkg.packageName)
13738                            && (bp.packageSetting instanceof PackageSetting)
13739                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13740                                    scanFlags))) {
13741                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13742                    } else {
13743                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13744                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13745                    }
13746                    if (!sigsOk) {
13747                        // If the owning package is the system itself, we log but allow
13748                        // install to proceed; we fail the install on all other permission
13749                        // redefinitions.
13750                        if (!bp.sourcePackage.equals("android")) {
13751                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13752                                    + pkg.packageName + " attempting to redeclare permission "
13753                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13754                            res.origPermission = perm.info.name;
13755                            res.origPackage = bp.sourcePackage;
13756                            return;
13757                        } else {
13758                            Slog.w(TAG, "Package " + pkg.packageName
13759                                    + " attempting to redeclare system permission "
13760                                    + perm.info.name + "; ignoring new declaration");
13761                            pkg.permissions.remove(i);
13762                        }
13763                    }
13764                }
13765            }
13766        }
13767
13768        if (systemApp) {
13769            if (onExternal) {
13770                // Abort update; system app can't be replaced with app on sdcard
13771                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13772                        "Cannot install updates to system apps on sdcard");
13773                return;
13774            } else if (ephemeral) {
13775                // Abort update; system app can't be replaced with an ephemeral app
13776                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13777                        "Cannot update a system app with an ephemeral app");
13778                return;
13779            }
13780        }
13781
13782        if (args.move != null) {
13783            // We did an in-place move, so dex is ready to roll
13784            scanFlags |= SCAN_NO_DEX;
13785            scanFlags |= SCAN_MOVE;
13786
13787            synchronized (mPackages) {
13788                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13789                if (ps == null) {
13790                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13791                            "Missing settings for moved package " + pkgName);
13792                }
13793
13794                // We moved the entire application as-is, so bring over the
13795                // previously derived ABI information.
13796                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13797                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13798            }
13799
13800        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13801            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13802            scanFlags |= SCAN_NO_DEX;
13803
13804            try {
13805                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13806                    args.abiOverride : pkg.cpuAbiOverride);
13807                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13808                        true /* extract libs */);
13809            } catch (PackageManagerException pme) {
13810                Slog.e(TAG, "Error deriving application ABI", pme);
13811                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13812                return;
13813            }
13814
13815            // Extract package to save the VM unzipping the APK in memory during
13816            // launch. Only do this if profile-guided compilation is enabled because
13817            // otherwise BackgroundDexOptService will not dexopt the package later.
13818            if (mUseJitProfiles) {
13819                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13820                // Do not run PackageDexOptimizer through the local performDexOpt
13821                // method because `pkg` is not in `mPackages` yet.
13822                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13823                        false /* useProfiles */, true /* extractOnly */);
13824                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13825                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13826                    String msg = "Extracking package failed for " + pkgName;
13827                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13828                    return;
13829                }
13830            }
13831        }
13832
13833        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13834            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13835            return;
13836        }
13837
13838        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13839
13840        if (replace) {
13841            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13842                    installerPackageName, res);
13843        } else {
13844            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13845                    args.user, installerPackageName, volumeUuid, res);
13846        }
13847        synchronized (mPackages) {
13848            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13849            if (ps != null) {
13850                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13851            }
13852
13853            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13854            for (int i = 0; i < childCount; i++) {
13855                PackageParser.Package childPkg = pkg.childPackages.get(i);
13856                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13857                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13858                if (childPs != null) {
13859                    childRes.newUsers = childPs.queryInstalledUsers(
13860                            sUserManager.getUserIds(), true);
13861                }
13862            }
13863        }
13864    }
13865
13866    private void startIntentFilterVerifications(int userId, boolean replacing,
13867            PackageParser.Package pkg) {
13868        if (mIntentFilterVerifierComponent == null) {
13869            Slog.w(TAG, "No IntentFilter verification will not be done as "
13870                    + "there is no IntentFilterVerifier available!");
13871            return;
13872        }
13873
13874        final int verifierUid = getPackageUid(
13875                mIntentFilterVerifierComponent.getPackageName(),
13876                MATCH_DEBUG_TRIAGED_MISSING,
13877                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13878
13879        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13880        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13881        mHandler.sendMessage(msg);
13882
13883        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13884        for (int i = 0; i < childCount; i++) {
13885            PackageParser.Package childPkg = pkg.childPackages.get(i);
13886            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13887            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13888            mHandler.sendMessage(msg);
13889        }
13890    }
13891
13892    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13893            PackageParser.Package pkg) {
13894        int size = pkg.activities.size();
13895        if (size == 0) {
13896            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13897                    "No activity, so no need to verify any IntentFilter!");
13898            return;
13899        }
13900
13901        final boolean hasDomainURLs = hasDomainURLs(pkg);
13902        if (!hasDomainURLs) {
13903            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13904                    "No domain URLs, so no need to verify any IntentFilter!");
13905            return;
13906        }
13907
13908        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13909                + " if any IntentFilter from the " + size
13910                + " Activities needs verification ...");
13911
13912        int count = 0;
13913        final String packageName = pkg.packageName;
13914
13915        synchronized (mPackages) {
13916            // If this is a new install and we see that we've already run verification for this
13917            // package, we have nothing to do: it means the state was restored from backup.
13918            if (!replacing) {
13919                IntentFilterVerificationInfo ivi =
13920                        mSettings.getIntentFilterVerificationLPr(packageName);
13921                if (ivi != null) {
13922                    if (DEBUG_DOMAIN_VERIFICATION) {
13923                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13924                                + ivi.getStatusString());
13925                    }
13926                    return;
13927                }
13928            }
13929
13930            // If any filters need to be verified, then all need to be.
13931            boolean needToVerify = false;
13932            for (PackageParser.Activity a : pkg.activities) {
13933                for (ActivityIntentInfo filter : a.intents) {
13934                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13935                        if (DEBUG_DOMAIN_VERIFICATION) {
13936                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13937                        }
13938                        needToVerify = true;
13939                        break;
13940                    }
13941                }
13942            }
13943
13944            if (needToVerify) {
13945                final int verificationId = mIntentFilterVerificationToken++;
13946                for (PackageParser.Activity a : pkg.activities) {
13947                    for (ActivityIntentInfo filter : a.intents) {
13948                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13949                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13950                                    "Verification needed for IntentFilter:" + filter.toString());
13951                            mIntentFilterVerifier.addOneIntentFilterVerification(
13952                                    verifierUid, userId, verificationId, filter, packageName);
13953                            count++;
13954                        }
13955                    }
13956                }
13957            }
13958        }
13959
13960        if (count > 0) {
13961            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13962                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13963                    +  " for userId:" + userId);
13964            mIntentFilterVerifier.startVerifications(userId);
13965        } else {
13966            if (DEBUG_DOMAIN_VERIFICATION) {
13967                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13968            }
13969        }
13970    }
13971
13972    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13973        final ComponentName cn  = filter.activity.getComponentName();
13974        final String packageName = cn.getPackageName();
13975
13976        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13977                packageName);
13978        if (ivi == null) {
13979            return true;
13980        }
13981        int status = ivi.getStatus();
13982        switch (status) {
13983            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13984            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13985                return true;
13986
13987            default:
13988                // Nothing to do
13989                return false;
13990        }
13991    }
13992
13993    private static boolean isMultiArch(ApplicationInfo info) {
13994        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13995    }
13996
13997    private static boolean isExternal(PackageParser.Package pkg) {
13998        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13999    }
14000
14001    private static boolean isExternal(PackageSetting ps) {
14002        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14003    }
14004
14005    private static boolean isEphemeral(PackageParser.Package pkg) {
14006        return pkg.applicationInfo.isEphemeralApp();
14007    }
14008
14009    private static boolean isEphemeral(PackageSetting ps) {
14010        return ps.pkg != null && isEphemeral(ps.pkg);
14011    }
14012
14013    private static boolean isSystemApp(PackageParser.Package pkg) {
14014        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14015    }
14016
14017    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14018        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14019    }
14020
14021    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14022        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14023    }
14024
14025    private static boolean isSystemApp(PackageSetting ps) {
14026        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14027    }
14028
14029    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14030        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14031    }
14032
14033    private int packageFlagsToInstallFlags(PackageSetting ps) {
14034        int installFlags = 0;
14035        if (isEphemeral(ps)) {
14036            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14037        }
14038        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14039            // This existing package was an external ASEC install when we have
14040            // the external flag without a UUID
14041            installFlags |= PackageManager.INSTALL_EXTERNAL;
14042        }
14043        if (ps.isForwardLocked()) {
14044            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14045        }
14046        return installFlags;
14047    }
14048
14049    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14050        if (isExternal(pkg)) {
14051            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14052                return StorageManager.UUID_PRIMARY_PHYSICAL;
14053            } else {
14054                return pkg.volumeUuid;
14055            }
14056        } else {
14057            return StorageManager.UUID_PRIVATE_INTERNAL;
14058        }
14059    }
14060
14061    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14062        if (isExternal(pkg)) {
14063            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14064                return mSettings.getExternalVersion();
14065            } else {
14066                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14067            }
14068        } else {
14069            return mSettings.getInternalVersion();
14070        }
14071    }
14072
14073    private void deleteTempPackageFiles() {
14074        final FilenameFilter filter = new FilenameFilter() {
14075            public boolean accept(File dir, String name) {
14076                return name.startsWith("vmdl") && name.endsWith(".tmp");
14077            }
14078        };
14079        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14080            file.delete();
14081        }
14082    }
14083
14084    @Override
14085    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14086            int flags) {
14087        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14088                flags);
14089    }
14090
14091    @Override
14092    public void deletePackage(final String packageName,
14093            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14094        mContext.enforceCallingOrSelfPermission(
14095                android.Manifest.permission.DELETE_PACKAGES, null);
14096        Preconditions.checkNotNull(packageName);
14097        Preconditions.checkNotNull(observer);
14098        final int uid = Binder.getCallingUid();
14099        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14100        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14101        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14102            mContext.enforceCallingOrSelfPermission(
14103                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14104                    "deletePackage for user " + userId);
14105        }
14106
14107        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14108            try {
14109                observer.onPackageDeleted(packageName,
14110                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14111            } catch (RemoteException re) {
14112            }
14113            return;
14114        }
14115
14116        for (int currentUserId : users) {
14117            if (getBlockUninstallForUser(packageName, currentUserId)) {
14118                try {
14119                    observer.onPackageDeleted(packageName,
14120                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14121                } catch (RemoteException re) {
14122                }
14123                return;
14124            }
14125        }
14126
14127        if (DEBUG_REMOVE) {
14128            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
14129        }
14130        // Queue up an async operation since the package deletion may take a little while.
14131        mHandler.post(new Runnable() {
14132            public void run() {
14133                mHandler.removeCallbacks(this);
14134                final int returnCode = deletePackageX(packageName, userId, flags);
14135                try {
14136                    observer.onPackageDeleted(packageName, returnCode, null);
14137                } catch (RemoteException e) {
14138                    Log.i(TAG, "Observer no longer exists.");
14139                } //end catch
14140            } //end run
14141        });
14142    }
14143
14144    @Override
14145    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14146        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14147    }
14148
14149    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14150        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14151                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14152        try {
14153            if (dpm != null) {
14154                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14155                        /* callingUserOnly =*/ false);
14156                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14157                        : deviceOwnerComponentName.getPackageName();
14158                // Does the package contains the device owner?
14159                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14160                // this check is probably not needed, since DO should be registered as a device
14161                // admin on some user too. (Original bug for this: b/17657954)
14162                if (packageName.equals(deviceOwnerPackageName)) {
14163                    return true;
14164                }
14165                // Does it contain a device admin for any user?
14166                int[] users;
14167                if (userId == UserHandle.USER_ALL) {
14168                    users = sUserManager.getUserIds();
14169                } else {
14170                    users = new int[]{userId};
14171                }
14172                for (int i = 0; i < users.length; ++i) {
14173                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14174                        return true;
14175                    }
14176                }
14177            }
14178        } catch (RemoteException e) {
14179        }
14180        return false;
14181    }
14182
14183    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14184        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14185    }
14186
14187    /**
14188     *  This method is an internal method that could be get invoked either
14189     *  to delete an installed package or to clean up a failed installation.
14190     *  After deleting an installed package, a broadcast is sent to notify any
14191     *  listeners that the package has been installed. For cleaning up a failed
14192     *  installation, the broadcast is not necessary since the package's
14193     *  installation wouldn't have sent the initial broadcast either
14194     *  The key steps in deleting a package are
14195     *  deleting the package information in internal structures like mPackages,
14196     *  deleting the packages base directories through installd
14197     *  updating mSettings to reflect current status
14198     *  persisting settings for later use
14199     *  sending a broadcast if necessary
14200     */
14201    private int deletePackageX(String packageName, int userId, int flags) {
14202        final PackageRemovedInfo info = new PackageRemovedInfo();
14203        final boolean res;
14204
14205        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14206                ? UserHandle.ALL : new UserHandle(userId);
14207
14208        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14209            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14210            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14211        }
14212
14213        PackageSetting uninstalledPs = null;
14214
14215        // for the uninstall-updates case and restricted profiles, remember the per-
14216        // user handle installed state
14217        int[] allUsers;
14218        synchronized (mPackages) {
14219            uninstalledPs = mSettings.mPackages.get(packageName);
14220            if (uninstalledPs == null) {
14221                Slog.w(TAG, "Not removing non-existent package " + packageName);
14222                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14223            }
14224            allUsers = sUserManager.getUserIds();
14225            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14226        }
14227
14228        synchronized (mInstallLock) {
14229            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14230            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14231                    flags | REMOVE_CHATTY, info, true, null);
14232            synchronized (mPackages) {
14233                if (res) {
14234                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14235                }
14236            }
14237        }
14238
14239        if (res) {
14240            info.sendPackageRemovedBroadcasts();
14241            info.sendSystemPackageUpdatedBroadcasts();
14242            info.sendSystemPackageAppearedBroadcasts();
14243        }
14244        // Force a gc here.
14245        Runtime.getRuntime().gc();
14246        // Delete the resources here after sending the broadcast to let
14247        // other processes clean up before deleting resources.
14248        if (info.args != null) {
14249            synchronized (mInstallLock) {
14250                info.args.doPostDeleteLI(true);
14251            }
14252        }
14253
14254        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14255    }
14256
14257    class PackageRemovedInfo {
14258        String removedPackage;
14259        int uid = -1;
14260        int removedAppId = -1;
14261        int[] origUsers;
14262        int[] removedUsers = null;
14263        boolean isRemovedPackageSystemUpdate = false;
14264        boolean isUpdate;
14265        boolean dataRemoved;
14266        boolean removedForAllUsers;
14267        // Clean up resources deleted packages.
14268        InstallArgs args = null;
14269        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14270        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14271
14272        void sendPackageRemovedBroadcasts() {
14273            sendPackageRemovedBroadcastInternal();
14274            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14275            for (int i = 0; i < childCount; i++) {
14276                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14277                childInfo.sendPackageRemovedBroadcastInternal();
14278            }
14279        }
14280
14281        void sendSystemPackageUpdatedBroadcasts() {
14282            if (isRemovedPackageSystemUpdate) {
14283                sendSystemPackageUpdatedBroadcastsInternal();
14284                final int childCount = (removedChildPackages != null)
14285                        ? removedChildPackages.size() : 0;
14286                for (int i = 0; i < childCount; i++) {
14287                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14288                    if (childInfo.isRemovedPackageSystemUpdate) {
14289                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14290                    }
14291                }
14292            }
14293        }
14294
14295        void sendSystemPackageAppearedBroadcasts() {
14296            final int packageCount = (appearedChildPackages != null)
14297                    ? appearedChildPackages.size() : 0;
14298            for (int i = 0; i < packageCount; i++) {
14299                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14300                for (int userId : installedInfo.newUsers) {
14301                    sendPackageAddedForUser(installedInfo.name, true,
14302                            UserHandle.getAppId(installedInfo.uid), userId);
14303                }
14304            }
14305        }
14306
14307        private void sendSystemPackageUpdatedBroadcastsInternal() {
14308            Bundle extras = new Bundle(2);
14309            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14310            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14311            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14312                    extras, 0, null, null, null);
14313            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14314                    extras, 0, null, null, null);
14315            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14316                    null, 0, removedPackage, null, null);
14317        }
14318
14319        private void sendPackageRemovedBroadcastInternal() {
14320            Bundle extras = new Bundle(2);
14321            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14322            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14323            if (isUpdate || isRemovedPackageSystemUpdate) {
14324                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14325            }
14326            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14327            if (removedPackage != null) {
14328                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14329                        extras, 0, null, null, removedUsers);
14330                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14331                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14332                            removedPackage, extras, 0, null, null, removedUsers);
14333                }
14334            }
14335            if (removedAppId >= 0) {
14336                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14337                        removedUsers);
14338            }
14339        }
14340    }
14341
14342    /*
14343     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14344     * flag is not set, the data directory is removed as well.
14345     * make sure this flag is set for partially installed apps. If not its meaningless to
14346     * delete a partially installed application.
14347     */
14348    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14349            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14350        String packageName = ps.name;
14351        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14352        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14353        // Retrieve object to delete permissions for shared user later on
14354        final PackageSetting deletedPs;
14355        // reader
14356        synchronized (mPackages) {
14357            deletedPs = mSettings.mPackages.get(packageName);
14358            if (outInfo != null) {
14359                outInfo.removedPackage = packageName;
14360                outInfo.removedUsers = deletedPs != null
14361                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14362                        : null;
14363            }
14364        }
14365        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14366            removeDataDirsLI(ps.volumeUuid, packageName);
14367            if (outInfo != null) {
14368                outInfo.dataRemoved = true;
14369            }
14370            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14371        }
14372        // writer
14373        synchronized (mPackages) {
14374            if (deletedPs != null) {
14375                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14376                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14377                    clearDefaultBrowserIfNeeded(packageName);
14378                    if (outInfo != null) {
14379                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14380                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14381                    }
14382                    updatePermissionsLPw(deletedPs.name, null, 0);
14383                    if (deletedPs.sharedUser != null) {
14384                        // Remove permissions associated with package. Since runtime
14385                        // permissions are per user we have to kill the removed package
14386                        // or packages running under the shared user of the removed
14387                        // package if revoking the permissions requested only by the removed
14388                        // package is successful and this causes a change in gids.
14389                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14390                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14391                                    userId);
14392                            if (userIdToKill == UserHandle.USER_ALL
14393                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14394                                // If gids changed for this user, kill all affected packages.
14395                                mHandler.post(new Runnable() {
14396                                    @Override
14397                                    public void run() {
14398                                        // This has to happen with no lock held.
14399                                        killApplication(deletedPs.name, deletedPs.appId,
14400                                                KILL_APP_REASON_GIDS_CHANGED);
14401                                    }
14402                                });
14403                                break;
14404                            }
14405                        }
14406                    }
14407                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14408                }
14409                // make sure to preserve per-user disabled state if this removal was just
14410                // a downgrade of a system app to the factory package
14411                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14412                    if (DEBUG_REMOVE) {
14413                        Slog.d(TAG, "Propagating install state across downgrade");
14414                    }
14415                    for (int userId : allUserHandles) {
14416                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14417                        if (DEBUG_REMOVE) {
14418                            Slog.d(TAG, "    user " + userId + " => " + installed);
14419                        }
14420                        ps.setInstalled(installed, userId);
14421                    }
14422                }
14423            }
14424            // can downgrade to reader
14425            if (writeSettings) {
14426                // Save settings now
14427                mSettings.writeLPr();
14428            }
14429        }
14430        if (outInfo != null) {
14431            // A user ID was deleted here. Go through all users and remove it
14432            // from KeyStore.
14433            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14434        }
14435    }
14436
14437    static boolean locationIsPrivileged(File path) {
14438        try {
14439            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14440                    .getCanonicalPath();
14441            return path.getCanonicalPath().startsWith(privilegedAppDir);
14442        } catch (IOException e) {
14443            Slog.e(TAG, "Unable to access code path " + path);
14444        }
14445        return false;
14446    }
14447
14448    /*
14449     * Tries to delete system package.
14450     */
14451    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14452            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14453            boolean writeSettings) {
14454        if (deletedPs.parentPackageName != null) {
14455            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14456            return false;
14457        }
14458
14459        final boolean applyUserRestrictions
14460                = (allUserHandles != null) && (outInfo.origUsers != null);
14461        final PackageSetting disabledPs;
14462        // Confirm if the system package has been updated
14463        // An updated system app can be deleted. This will also have to restore
14464        // the system pkg from system partition
14465        // reader
14466        synchronized (mPackages) {
14467            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14468        }
14469
14470        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14471                + " disabledPs=" + disabledPs);
14472
14473        if (disabledPs == null) {
14474            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14475            return false;
14476        } else if (DEBUG_REMOVE) {
14477            Slog.d(TAG, "Deleting system pkg from data partition");
14478        }
14479
14480        if (DEBUG_REMOVE) {
14481            if (applyUserRestrictions) {
14482                Slog.d(TAG, "Remembering install states:");
14483                for (int userId : allUserHandles) {
14484                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14485                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14486                }
14487            }
14488        }
14489
14490        // Delete the updated package
14491        outInfo.isRemovedPackageSystemUpdate = true;
14492        if (outInfo.removedChildPackages != null) {
14493            final int childCount = (deletedPs.childPackageNames != null)
14494                    ? deletedPs.childPackageNames.size() : 0;
14495            for (int i = 0; i < childCount; i++) {
14496                String childPackageName = deletedPs.childPackageNames.get(i);
14497                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14498                        .contains(childPackageName)) {
14499                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14500                            childPackageName);
14501                    if (childInfo != null) {
14502                        childInfo.isRemovedPackageSystemUpdate = true;
14503                    }
14504                }
14505            }
14506        }
14507
14508        if (disabledPs.versionCode < deletedPs.versionCode) {
14509            // Delete data for downgrades
14510            flags &= ~PackageManager.DELETE_KEEP_DATA;
14511        } else {
14512            // Preserve data by setting flag
14513            flags |= PackageManager.DELETE_KEEP_DATA;
14514        }
14515
14516        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14517                outInfo, writeSettings, disabledPs.pkg);
14518        if (!ret) {
14519            return false;
14520        }
14521
14522        // writer
14523        synchronized (mPackages) {
14524            // Reinstate the old system package
14525            enableSystemPackageLPw(disabledPs.pkg);
14526            // Remove any native libraries from the upgraded package.
14527            removeNativeBinariesLI(deletedPs);
14528        }
14529
14530        // Install the system package
14531        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14532        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14533        if (locationIsPrivileged(disabledPs.codePath)) {
14534            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14535        }
14536
14537        final PackageParser.Package newPkg;
14538        try {
14539            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14540        } catch (PackageManagerException e) {
14541            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14542                    + e.getMessage());
14543            return false;
14544        }
14545
14546        prepareAppDataAfterInstall(newPkg);
14547
14548        // writer
14549        synchronized (mPackages) {
14550            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14551
14552            // Propagate the permissions state as we do not want to drop on the floor
14553            // runtime permissions. The update permissions method below will take
14554            // care of removing obsolete permissions and grant install permissions.
14555            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14556            updatePermissionsLPw(newPkg.packageName, newPkg,
14557                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14558
14559            if (applyUserRestrictions) {
14560                if (DEBUG_REMOVE) {
14561                    Slog.d(TAG, "Propagating install state across reinstall");
14562                }
14563                for (int userId : allUserHandles) {
14564                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14565                    if (DEBUG_REMOVE) {
14566                        Slog.d(TAG, "    user " + userId + " => " + installed);
14567                    }
14568                    ps.setInstalled(installed, userId);
14569
14570                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14571                }
14572                // Regardless of writeSettings we need to ensure that this restriction
14573                // state propagation is persisted
14574                mSettings.writeAllUsersPackageRestrictionsLPr();
14575            }
14576            // can downgrade to reader here
14577            if (writeSettings) {
14578                mSettings.writeLPr();
14579            }
14580        }
14581        return true;
14582    }
14583
14584    private boolean deleteInstalledPackageLI(PackageSetting ps,
14585            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14586            PackageRemovedInfo outInfo, boolean writeSettings,
14587            PackageParser.Package replacingPackage) {
14588        synchronized (mPackages) {
14589            if (outInfo != null) {
14590                outInfo.uid = ps.appId;
14591            }
14592
14593            if (outInfo != null && outInfo.removedChildPackages != null) {
14594                final int childCount = (ps.childPackageNames != null)
14595                        ? ps.childPackageNames.size() : 0;
14596                for (int i = 0; i < childCount; i++) {
14597                    String childPackageName = ps.childPackageNames.get(i);
14598                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14599                    if (childPs == null) {
14600                        return false;
14601                    }
14602                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14603                            childPackageName);
14604                    if (childInfo != null) {
14605                        childInfo.uid = childPs.appId;
14606                    }
14607                }
14608            }
14609        }
14610
14611        // Delete package data from internal structures and also remove data if flag is set
14612        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14613
14614        // Delete the child packages data
14615        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14616        for (int i = 0; i < childCount; i++) {
14617            PackageSetting childPs;
14618            synchronized (mPackages) {
14619                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14620            }
14621            if (childPs != null) {
14622                PackageRemovedInfo childOutInfo = (outInfo != null
14623                        && outInfo.removedChildPackages != null)
14624                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14625                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14626                        && (replacingPackage != null
14627                        && !replacingPackage.hasChildPackage(childPs.name))
14628                        ? flags & ~DELETE_KEEP_DATA : flags;
14629                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14630                        deleteFlags, writeSettings);
14631            }
14632        }
14633
14634        // Delete application code and resources only for parent packages
14635        if (ps.parentPackageName == null) {
14636            if (deleteCodeAndResources && (outInfo != null)) {
14637                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14638                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14639                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14640            }
14641        }
14642
14643        return true;
14644    }
14645
14646    @Override
14647    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14648            int userId) {
14649        mContext.enforceCallingOrSelfPermission(
14650                android.Manifest.permission.DELETE_PACKAGES, null);
14651        synchronized (mPackages) {
14652            PackageSetting ps = mSettings.mPackages.get(packageName);
14653            if (ps == null) {
14654                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14655                return false;
14656            }
14657            if (!ps.getInstalled(userId)) {
14658                // Can't block uninstall for an app that is not installed or enabled.
14659                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14660                return false;
14661            }
14662            ps.setBlockUninstall(blockUninstall, userId);
14663            mSettings.writePackageRestrictionsLPr(userId);
14664        }
14665        return true;
14666    }
14667
14668    @Override
14669    public boolean getBlockUninstallForUser(String packageName, int userId) {
14670        synchronized (mPackages) {
14671            PackageSetting ps = mSettings.mPackages.get(packageName);
14672            if (ps == null) {
14673                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14674                return false;
14675            }
14676            return ps.getBlockUninstall(userId);
14677        }
14678    }
14679
14680    @Override
14681    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14682        int callingUid = Binder.getCallingUid();
14683        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14684            throw new SecurityException(
14685                    "setRequiredForSystemUser can only be run by the system or root");
14686        }
14687        synchronized (mPackages) {
14688            PackageSetting ps = mSettings.mPackages.get(packageName);
14689            if (ps == null) {
14690                Log.w(TAG, "Package doesn't exist: " + packageName);
14691                return false;
14692            }
14693            if (systemUserApp) {
14694                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14695            } else {
14696                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14697            }
14698            mSettings.writeLPr();
14699        }
14700        return true;
14701    }
14702
14703    /*
14704     * This method handles package deletion in general
14705     */
14706    private boolean deletePackageLI(String packageName, UserHandle user,
14707            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14708            PackageRemovedInfo outInfo, boolean writeSettings,
14709            PackageParser.Package replacingPackage) {
14710        if (packageName == null) {
14711            Slog.w(TAG, "Attempt to delete null packageName.");
14712            return false;
14713        }
14714
14715        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14716
14717        PackageSetting ps;
14718
14719        synchronized (mPackages) {
14720            ps = mSettings.mPackages.get(packageName);
14721            if (ps == null) {
14722                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14723                return false;
14724            }
14725
14726            if (ps.parentPackageName != null && (!isSystemApp(ps)
14727                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14728                if (DEBUG_REMOVE) {
14729                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14730                            + ((user == null) ? UserHandle.USER_ALL : user));
14731                }
14732                final int removedUserId = (user != null) ? user.getIdentifier()
14733                        : UserHandle.USER_ALL;
14734                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14735                    return false;
14736                }
14737                markPackageUninstalledForUserLPw(ps, user);
14738                scheduleWritePackageRestrictionsLocked(user);
14739                return true;
14740            }
14741        }
14742
14743        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14744                && user.getIdentifier() != UserHandle.USER_ALL)) {
14745            // The caller is asking that the package only be deleted for a single
14746            // user.  To do this, we just mark its uninstalled state and delete
14747            // its data. If this is a system app, we only allow this to happen if
14748            // they have set the special DELETE_SYSTEM_APP which requests different
14749            // semantics than normal for uninstalling system apps.
14750            markPackageUninstalledForUserLPw(ps, user);
14751
14752            if (!isSystemApp(ps)) {
14753                // Do not uninstall the APK if an app should be cached
14754                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14755                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14756                    // Other user still have this package installed, so all
14757                    // we need to do is clear this user's data and save that
14758                    // it is uninstalled.
14759                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14760                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14761                        return false;
14762                    }
14763                    scheduleWritePackageRestrictionsLocked(user);
14764                    return true;
14765                } else {
14766                    // We need to set it back to 'installed' so the uninstall
14767                    // broadcasts will be sent correctly.
14768                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14769                    ps.setInstalled(true, user.getIdentifier());
14770                }
14771            } else {
14772                // This is a system app, so we assume that the
14773                // other users still have this package installed, so all
14774                // we need to do is clear this user's data and save that
14775                // it is uninstalled.
14776                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14777                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14778                    return false;
14779                }
14780                scheduleWritePackageRestrictionsLocked(user);
14781                return true;
14782            }
14783        }
14784
14785        // If we are deleting a composite package for all users, keep track
14786        // of result for each child.
14787        if (ps.childPackageNames != null && outInfo != null) {
14788            synchronized (mPackages) {
14789                final int childCount = ps.childPackageNames.size();
14790                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14791                for (int i = 0; i < childCount; i++) {
14792                    String childPackageName = ps.childPackageNames.get(i);
14793                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14794                    childInfo.removedPackage = childPackageName;
14795                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14796                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14797                    if (childPs != null) {
14798                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14799                    }
14800                }
14801            }
14802        }
14803
14804        boolean ret = false;
14805        if (isSystemApp(ps)) {
14806            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14807            // When an updated system application is deleted we delete the existing resources
14808            // as well and fall back to existing code in system partition
14809            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14810        } else {
14811            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14812            // Kill application pre-emptively especially for apps on sd.
14813            killApplication(packageName, ps.appId, "uninstall pkg");
14814            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
14815                    outInfo, writeSettings, replacingPackage);
14816        }
14817
14818        // Take a note whether we deleted the package for all users
14819        if (outInfo != null) {
14820            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14821            if (outInfo.removedChildPackages != null) {
14822                synchronized (mPackages) {
14823                    final int childCount = outInfo.removedChildPackages.size();
14824                    for (int i = 0; i < childCount; i++) {
14825                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14826                        if (childInfo != null) {
14827                            childInfo.removedForAllUsers = mPackages.get(
14828                                    childInfo.removedPackage) == null;
14829                        }
14830                    }
14831                }
14832            }
14833            // If we uninstalled an update to a system app there may be some
14834            // child packages that appeared as they are declared in the system
14835            // app but were not declared in the update.
14836            if (isSystemApp(ps)) {
14837                synchronized (mPackages) {
14838                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14839                    final int childCount = (updatedPs.childPackageNames != null)
14840                            ? updatedPs.childPackageNames.size() : 0;
14841                    for (int i = 0; i < childCount; i++) {
14842                        String childPackageName = updatedPs.childPackageNames.get(i);
14843                        if (outInfo.removedChildPackages == null
14844                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14845                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14846                            if (childPs == null) {
14847                                continue;
14848                            }
14849                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14850                            installRes.name = childPackageName;
14851                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14852                            installRes.pkg = mPackages.get(childPackageName);
14853                            installRes.uid = childPs.pkg.applicationInfo.uid;
14854                            if (outInfo.appearedChildPackages == null) {
14855                                outInfo.appearedChildPackages = new ArrayMap<>();
14856                            }
14857                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14858                        }
14859                    }
14860                }
14861            }
14862        }
14863
14864        return ret;
14865    }
14866
14867    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14868        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14869                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14870        for (int nextUserId : userIds) {
14871            if (DEBUG_REMOVE) {
14872                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14873            }
14874            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14875                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14876                    false /*hidden*/, false /*suspended*/, null, null, null,
14877                    false /*blockUninstall*/,
14878                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14879        }
14880    }
14881
14882    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14883            PackageRemovedInfo outInfo) {
14884        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14885                : new int[] {userId};
14886        for (int nextUserId : userIds) {
14887            if (DEBUG_REMOVE) {
14888                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14889                        + nextUserId);
14890            }
14891            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14892            try {
14893                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14894            } catch (InstallerException e) {
14895                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14896                return false;
14897            }
14898            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14899            schedulePackageCleaning(ps.name, nextUserId, false);
14900            synchronized (mPackages) {
14901                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14902                    scheduleWritePackageRestrictionsLocked(nextUserId);
14903                }
14904                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14905            }
14906        }
14907
14908        if (outInfo != null) {
14909            outInfo.removedPackage = ps.name;
14910            outInfo.removedAppId = ps.appId;
14911            outInfo.removedUsers = userIds;
14912        }
14913
14914        return true;
14915    }
14916
14917    private final class ClearStorageConnection implements ServiceConnection {
14918        IMediaContainerService mContainerService;
14919
14920        @Override
14921        public void onServiceConnected(ComponentName name, IBinder service) {
14922            synchronized (this) {
14923                mContainerService = IMediaContainerService.Stub.asInterface(service);
14924                notifyAll();
14925            }
14926        }
14927
14928        @Override
14929        public void onServiceDisconnected(ComponentName name) {
14930        }
14931    }
14932
14933    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14934        final boolean mounted;
14935        if (Environment.isExternalStorageEmulated()) {
14936            mounted = true;
14937        } else {
14938            final String status = Environment.getExternalStorageState();
14939
14940            mounted = status.equals(Environment.MEDIA_MOUNTED)
14941                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14942        }
14943
14944        if (!mounted) {
14945            return;
14946        }
14947
14948        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14949        int[] users;
14950        if (userId == UserHandle.USER_ALL) {
14951            users = sUserManager.getUserIds();
14952        } else {
14953            users = new int[] { userId };
14954        }
14955        final ClearStorageConnection conn = new ClearStorageConnection();
14956        if (mContext.bindServiceAsUser(
14957                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14958            try {
14959                for (int curUser : users) {
14960                    long timeout = SystemClock.uptimeMillis() + 5000;
14961                    synchronized (conn) {
14962                        long now = SystemClock.uptimeMillis();
14963                        while (conn.mContainerService == null && now < timeout) {
14964                            try {
14965                                conn.wait(timeout - now);
14966                            } catch (InterruptedException e) {
14967                            }
14968                        }
14969                    }
14970                    if (conn.mContainerService == null) {
14971                        return;
14972                    }
14973
14974                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14975                    clearDirectory(conn.mContainerService,
14976                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14977                    if (allData) {
14978                        clearDirectory(conn.mContainerService,
14979                                userEnv.buildExternalStorageAppDataDirs(packageName));
14980                        clearDirectory(conn.mContainerService,
14981                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14982                    }
14983                }
14984            } finally {
14985                mContext.unbindService(conn);
14986            }
14987        }
14988    }
14989
14990    @Override
14991    public void clearApplicationUserData(final String packageName,
14992            final IPackageDataObserver observer, final int userId) {
14993        mContext.enforceCallingOrSelfPermission(
14994                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14995        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14996        // Queue up an async operation since the package deletion may take a little while.
14997        mHandler.post(new Runnable() {
14998            public void run() {
14999                mHandler.removeCallbacks(this);
15000                final boolean succeeded;
15001                synchronized (mInstallLock) {
15002                    succeeded = clearApplicationUserDataLI(packageName, userId);
15003                }
15004                clearExternalStorageDataSync(packageName, userId, true);
15005                if (succeeded) {
15006                    // invoke DeviceStorageMonitor's update method to clear any notifications
15007                    DeviceStorageMonitorInternal
15008                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15009                    if (dsm != null) {
15010                        dsm.checkMemory();
15011                    }
15012                }
15013                if(observer != null) {
15014                    try {
15015                        observer.onRemoveCompleted(packageName, succeeded);
15016                    } catch (RemoteException e) {
15017                        Log.i(TAG, "Observer no longer exists.");
15018                    }
15019                } //end if observer
15020            } //end run
15021        });
15022    }
15023
15024    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15025        if (packageName == null) {
15026            Slog.w(TAG, "Attempt to delete null packageName.");
15027            return false;
15028        }
15029
15030        // Try finding details about the requested package
15031        PackageParser.Package pkg;
15032        synchronized (mPackages) {
15033            pkg = mPackages.get(packageName);
15034            if (pkg == null) {
15035                final PackageSetting ps = mSettings.mPackages.get(packageName);
15036                if (ps != null) {
15037                    pkg = ps.pkg;
15038                }
15039            }
15040
15041            if (pkg == null) {
15042                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15043                return false;
15044            }
15045
15046            PackageSetting ps = (PackageSetting) pkg.mExtras;
15047            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15048        }
15049
15050        // Always delete data directories for package, even if we found no other
15051        // record of app. This helps users recover from UID mismatches without
15052        // resorting to a full data wipe.
15053        // TODO: triage flags as part of 26466827
15054        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15055        try {
15056            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15057        } catch (InstallerException e) {
15058            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15059            return false;
15060        }
15061
15062        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15063        removeKeystoreDataIfNeeded(userId, appId);
15064
15065        // Create a native library symlink only if we have native libraries
15066        // and if the native libraries are 32 bit libraries. We do not provide
15067        // this symlink for 64 bit libraries.
15068        if (pkg.applicationInfo.primaryCpuAbi != null &&
15069                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15070            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15071            try {
15072                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15073                        nativeLibPath, userId);
15074            } catch (InstallerException e) {
15075                Slog.w(TAG, "Failed linking native library dir", e);
15076                return false;
15077            }
15078        }
15079
15080        return true;
15081    }
15082
15083    /**
15084     * Reverts user permission state changes (permissions and flags) in
15085     * all packages for a given user.
15086     *
15087     * @param userId The device user for which to do a reset.
15088     */
15089    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15090        final int packageCount = mPackages.size();
15091        for (int i = 0; i < packageCount; i++) {
15092            PackageParser.Package pkg = mPackages.valueAt(i);
15093            PackageSetting ps = (PackageSetting) pkg.mExtras;
15094            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15095        }
15096    }
15097
15098    /**
15099     * Reverts user permission state changes (permissions and flags).
15100     *
15101     * @param ps The package for which to reset.
15102     * @param userId The device user for which to do a reset.
15103     */
15104    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15105            final PackageSetting ps, final int userId) {
15106        if (ps.pkg == null) {
15107            return;
15108        }
15109
15110        // These are flags that can change base on user actions.
15111        final int userSettableMask = FLAG_PERMISSION_USER_SET
15112                | FLAG_PERMISSION_USER_FIXED
15113                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15114                | FLAG_PERMISSION_REVIEW_REQUIRED;
15115
15116        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15117                | FLAG_PERMISSION_POLICY_FIXED;
15118
15119        boolean writeInstallPermissions = false;
15120        boolean writeRuntimePermissions = false;
15121
15122        final int permissionCount = ps.pkg.requestedPermissions.size();
15123        for (int i = 0; i < permissionCount; i++) {
15124            String permission = ps.pkg.requestedPermissions.get(i);
15125
15126            BasePermission bp = mSettings.mPermissions.get(permission);
15127            if (bp == null) {
15128                continue;
15129            }
15130
15131            // If shared user we just reset the state to which only this app contributed.
15132            if (ps.sharedUser != null) {
15133                boolean used = false;
15134                final int packageCount = ps.sharedUser.packages.size();
15135                for (int j = 0; j < packageCount; j++) {
15136                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15137                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15138                            && pkg.pkg.requestedPermissions.contains(permission)) {
15139                        used = true;
15140                        break;
15141                    }
15142                }
15143                if (used) {
15144                    continue;
15145                }
15146            }
15147
15148            PermissionsState permissionsState = ps.getPermissionsState();
15149
15150            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15151
15152            // Always clear the user settable flags.
15153            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15154                    bp.name) != null;
15155            // If permission review is enabled and this is a legacy app, mark the
15156            // permission as requiring a review as this is the initial state.
15157            int flags = 0;
15158            if (Build.PERMISSIONS_REVIEW_REQUIRED
15159                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15160                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15161            }
15162            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15163                if (hasInstallState) {
15164                    writeInstallPermissions = true;
15165                } else {
15166                    writeRuntimePermissions = true;
15167                }
15168            }
15169
15170            // Below is only runtime permission handling.
15171            if (!bp.isRuntime()) {
15172                continue;
15173            }
15174
15175            // Never clobber system or policy.
15176            if ((oldFlags & policyOrSystemFlags) != 0) {
15177                continue;
15178            }
15179
15180            // If this permission was granted by default, make sure it is.
15181            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15182                if (permissionsState.grantRuntimePermission(bp, userId)
15183                        != PERMISSION_OPERATION_FAILURE) {
15184                    writeRuntimePermissions = true;
15185                }
15186            // If permission review is enabled the permissions for a legacy apps
15187            // are represented as constantly granted runtime ones, so don't revoke.
15188            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15189                // Otherwise, reset the permission.
15190                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15191                switch (revokeResult) {
15192                    case PERMISSION_OPERATION_SUCCESS: {
15193                        writeRuntimePermissions = true;
15194                    } break;
15195
15196                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15197                        writeRuntimePermissions = true;
15198                        final int appId = ps.appId;
15199                        mHandler.post(new Runnable() {
15200                            @Override
15201                            public void run() {
15202                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15203                            }
15204                        });
15205                    } break;
15206                }
15207            }
15208        }
15209
15210        // Synchronously write as we are taking permissions away.
15211        if (writeRuntimePermissions) {
15212            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15213        }
15214
15215        // Synchronously write as we are taking permissions away.
15216        if (writeInstallPermissions) {
15217            mSettings.writeLPr();
15218        }
15219    }
15220
15221    /**
15222     * Remove entries from the keystore daemon. Will only remove it if the
15223     * {@code appId} is valid.
15224     */
15225    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15226        if (appId < 0) {
15227            return;
15228        }
15229
15230        final KeyStore keyStore = KeyStore.getInstance();
15231        if (keyStore != null) {
15232            if (userId == UserHandle.USER_ALL) {
15233                for (final int individual : sUserManager.getUserIds()) {
15234                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15235                }
15236            } else {
15237                keyStore.clearUid(UserHandle.getUid(userId, appId));
15238            }
15239        } else {
15240            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15241        }
15242    }
15243
15244    @Override
15245    public void deleteApplicationCacheFiles(final String packageName,
15246            final IPackageDataObserver observer) {
15247        mContext.enforceCallingOrSelfPermission(
15248                android.Manifest.permission.DELETE_CACHE_FILES, null);
15249        // Queue up an async operation since the package deletion may take a little while.
15250        final int userId = UserHandle.getCallingUserId();
15251        mHandler.post(new Runnable() {
15252            public void run() {
15253                mHandler.removeCallbacks(this);
15254                final boolean succeded;
15255                synchronized (mInstallLock) {
15256                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15257                }
15258                clearExternalStorageDataSync(packageName, userId, false);
15259                if (observer != null) {
15260                    try {
15261                        observer.onRemoveCompleted(packageName, succeded);
15262                    } catch (RemoteException e) {
15263                        Log.i(TAG, "Observer no longer exists.");
15264                    }
15265                } //end if observer
15266            } //end run
15267        });
15268    }
15269
15270    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15271        if (packageName == null) {
15272            Slog.w(TAG, "Attempt to delete null packageName.");
15273            return false;
15274        }
15275        PackageParser.Package p;
15276        synchronized (mPackages) {
15277            p = mPackages.get(packageName);
15278        }
15279        if (p == null) {
15280            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15281            return false;
15282        }
15283        final ApplicationInfo applicationInfo = p.applicationInfo;
15284        if (applicationInfo == null) {
15285            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15286            return false;
15287        }
15288        // TODO: triage flags as part of 26466827
15289        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15290        try {
15291            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15292                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15293        } catch (InstallerException e) {
15294            Slog.w(TAG, "Couldn't remove cache files for package "
15295                    + packageName + " u" + userId, e);
15296            return false;
15297        }
15298        return true;
15299    }
15300
15301    @Override
15302    public void getPackageSizeInfo(final String packageName, int userHandle,
15303            final IPackageStatsObserver observer) {
15304        mContext.enforceCallingOrSelfPermission(
15305                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15306        if (packageName == null) {
15307            throw new IllegalArgumentException("Attempt to get size of null packageName");
15308        }
15309
15310        PackageStats stats = new PackageStats(packageName, userHandle);
15311
15312        /*
15313         * Queue up an async operation since the package measurement may take a
15314         * little while.
15315         */
15316        Message msg = mHandler.obtainMessage(INIT_COPY);
15317        msg.obj = new MeasureParams(stats, observer);
15318        mHandler.sendMessage(msg);
15319    }
15320
15321    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15322            PackageStats pStats) {
15323        if (packageName == null) {
15324            Slog.w(TAG, "Attempt to get size of null packageName.");
15325            return false;
15326        }
15327        PackageParser.Package p;
15328        boolean dataOnly = false;
15329        String libDirRoot = null;
15330        String asecPath = null;
15331        PackageSetting ps = null;
15332        synchronized (mPackages) {
15333            p = mPackages.get(packageName);
15334            ps = mSettings.mPackages.get(packageName);
15335            if(p == null) {
15336                dataOnly = true;
15337                if((ps == null) || (ps.pkg == null)) {
15338                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15339                    return false;
15340                }
15341                p = ps.pkg;
15342            }
15343            if (ps != null) {
15344                libDirRoot = ps.legacyNativeLibraryPathString;
15345            }
15346            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15347                final long token = Binder.clearCallingIdentity();
15348                try {
15349                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15350                    if (secureContainerId != null) {
15351                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15352                    }
15353                } finally {
15354                    Binder.restoreCallingIdentity(token);
15355                }
15356            }
15357        }
15358        String publicSrcDir = null;
15359        if(!dataOnly) {
15360            final ApplicationInfo applicationInfo = p.applicationInfo;
15361            if (applicationInfo == null) {
15362                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15363                return false;
15364            }
15365            if (p.isForwardLocked()) {
15366                publicSrcDir = applicationInfo.getBaseResourcePath();
15367            }
15368        }
15369        // TODO: extend to measure size of split APKs
15370        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15371        // not just the first level.
15372        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15373        // just the primary.
15374        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15375
15376        String apkPath;
15377        File packageDir = new File(p.codePath);
15378
15379        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15380            apkPath = packageDir.getAbsolutePath();
15381            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15382            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15383                libDirRoot = null;
15384            }
15385        } else {
15386            apkPath = p.baseCodePath;
15387        }
15388
15389        // TODO: triage flags as part of 26466827
15390        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15391        try {
15392            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15393                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15394        } catch (InstallerException e) {
15395            return false;
15396        }
15397
15398        // Fix-up for forward-locked applications in ASEC containers.
15399        if (!isExternal(p)) {
15400            pStats.codeSize += pStats.externalCodeSize;
15401            pStats.externalCodeSize = 0L;
15402        }
15403
15404        return true;
15405    }
15406
15407
15408    @Override
15409    public void addPackageToPreferred(String packageName) {
15410        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15411    }
15412
15413    @Override
15414    public void removePackageFromPreferred(String packageName) {
15415        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15416    }
15417
15418    @Override
15419    public List<PackageInfo> getPreferredPackages(int flags) {
15420        return new ArrayList<PackageInfo>();
15421    }
15422
15423    private int getUidTargetSdkVersionLockedLPr(int uid) {
15424        Object obj = mSettings.getUserIdLPr(uid);
15425        if (obj instanceof SharedUserSetting) {
15426            final SharedUserSetting sus = (SharedUserSetting) obj;
15427            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15428            final Iterator<PackageSetting> it = sus.packages.iterator();
15429            while (it.hasNext()) {
15430                final PackageSetting ps = it.next();
15431                if (ps.pkg != null) {
15432                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15433                    if (v < vers) vers = v;
15434                }
15435            }
15436            return vers;
15437        } else if (obj instanceof PackageSetting) {
15438            final PackageSetting ps = (PackageSetting) obj;
15439            if (ps.pkg != null) {
15440                return ps.pkg.applicationInfo.targetSdkVersion;
15441            }
15442        }
15443        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15444    }
15445
15446    @Override
15447    public void addPreferredActivity(IntentFilter filter, int match,
15448            ComponentName[] set, ComponentName activity, int userId) {
15449        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15450                "Adding preferred");
15451    }
15452
15453    private void addPreferredActivityInternal(IntentFilter filter, int match,
15454            ComponentName[] set, ComponentName activity, boolean always, int userId,
15455            String opname) {
15456        // writer
15457        int callingUid = Binder.getCallingUid();
15458        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15459        if (filter.countActions() == 0) {
15460            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15461            return;
15462        }
15463        synchronized (mPackages) {
15464            if (mContext.checkCallingOrSelfPermission(
15465                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15466                    != PackageManager.PERMISSION_GRANTED) {
15467                if (getUidTargetSdkVersionLockedLPr(callingUid)
15468                        < Build.VERSION_CODES.FROYO) {
15469                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15470                            + callingUid);
15471                    return;
15472                }
15473                mContext.enforceCallingOrSelfPermission(
15474                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15475            }
15476
15477            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15478            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15479                    + userId + ":");
15480            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15481            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15482            scheduleWritePackageRestrictionsLocked(userId);
15483        }
15484    }
15485
15486    @Override
15487    public void replacePreferredActivity(IntentFilter filter, int match,
15488            ComponentName[] set, ComponentName activity, int userId) {
15489        if (filter.countActions() != 1) {
15490            throw new IllegalArgumentException(
15491                    "replacePreferredActivity expects filter to have only 1 action.");
15492        }
15493        if (filter.countDataAuthorities() != 0
15494                || filter.countDataPaths() != 0
15495                || filter.countDataSchemes() > 1
15496                || filter.countDataTypes() != 0) {
15497            throw new IllegalArgumentException(
15498                    "replacePreferredActivity expects filter to have no data authorities, " +
15499                    "paths, or types; and at most one scheme.");
15500        }
15501
15502        final int callingUid = Binder.getCallingUid();
15503        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15504        synchronized (mPackages) {
15505            if (mContext.checkCallingOrSelfPermission(
15506                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15507                    != PackageManager.PERMISSION_GRANTED) {
15508                if (getUidTargetSdkVersionLockedLPr(callingUid)
15509                        < Build.VERSION_CODES.FROYO) {
15510                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15511                            + Binder.getCallingUid());
15512                    return;
15513                }
15514                mContext.enforceCallingOrSelfPermission(
15515                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15516            }
15517
15518            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15519            if (pir != null) {
15520                // Get all of the existing entries that exactly match this filter.
15521                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15522                if (existing != null && existing.size() == 1) {
15523                    PreferredActivity cur = existing.get(0);
15524                    if (DEBUG_PREFERRED) {
15525                        Slog.i(TAG, "Checking replace of preferred:");
15526                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15527                        if (!cur.mPref.mAlways) {
15528                            Slog.i(TAG, "  -- CUR; not mAlways!");
15529                        } else {
15530                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15531                            Slog.i(TAG, "  -- CUR: mSet="
15532                                    + Arrays.toString(cur.mPref.mSetComponents));
15533                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15534                            Slog.i(TAG, "  -- NEW: mMatch="
15535                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15536                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15537                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15538                        }
15539                    }
15540                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15541                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15542                            && cur.mPref.sameSet(set)) {
15543                        // Setting the preferred activity to what it happens to be already
15544                        if (DEBUG_PREFERRED) {
15545                            Slog.i(TAG, "Replacing with same preferred activity "
15546                                    + cur.mPref.mShortComponent + " for user "
15547                                    + userId + ":");
15548                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15549                        }
15550                        return;
15551                    }
15552                }
15553
15554                if (existing != null) {
15555                    if (DEBUG_PREFERRED) {
15556                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15557                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15558                    }
15559                    for (int i = 0; i < existing.size(); i++) {
15560                        PreferredActivity pa = existing.get(i);
15561                        if (DEBUG_PREFERRED) {
15562                            Slog.i(TAG, "Removing existing preferred activity "
15563                                    + pa.mPref.mComponent + ":");
15564                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15565                        }
15566                        pir.removeFilter(pa);
15567                    }
15568                }
15569            }
15570            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15571                    "Replacing preferred");
15572        }
15573    }
15574
15575    @Override
15576    public void clearPackagePreferredActivities(String packageName) {
15577        final int uid = Binder.getCallingUid();
15578        // writer
15579        synchronized (mPackages) {
15580            PackageParser.Package pkg = mPackages.get(packageName);
15581            if (pkg == null || pkg.applicationInfo.uid != uid) {
15582                if (mContext.checkCallingOrSelfPermission(
15583                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15584                        != PackageManager.PERMISSION_GRANTED) {
15585                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15586                            < Build.VERSION_CODES.FROYO) {
15587                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15588                                + Binder.getCallingUid());
15589                        return;
15590                    }
15591                    mContext.enforceCallingOrSelfPermission(
15592                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15593                }
15594            }
15595
15596            int user = UserHandle.getCallingUserId();
15597            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15598                scheduleWritePackageRestrictionsLocked(user);
15599            }
15600        }
15601    }
15602
15603    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15604    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15605        ArrayList<PreferredActivity> removed = null;
15606        boolean changed = false;
15607        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15608            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15609            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15610            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15611                continue;
15612            }
15613            Iterator<PreferredActivity> it = pir.filterIterator();
15614            while (it.hasNext()) {
15615                PreferredActivity pa = it.next();
15616                // Mark entry for removal only if it matches the package name
15617                // and the entry is of type "always".
15618                if (packageName == null ||
15619                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15620                                && pa.mPref.mAlways)) {
15621                    if (removed == null) {
15622                        removed = new ArrayList<PreferredActivity>();
15623                    }
15624                    removed.add(pa);
15625                }
15626            }
15627            if (removed != null) {
15628                for (int j=0; j<removed.size(); j++) {
15629                    PreferredActivity pa = removed.get(j);
15630                    pir.removeFilter(pa);
15631                }
15632                changed = true;
15633            }
15634        }
15635        return changed;
15636    }
15637
15638    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15639    private void clearIntentFilterVerificationsLPw(int userId) {
15640        final int packageCount = mPackages.size();
15641        for (int i = 0; i < packageCount; i++) {
15642            PackageParser.Package pkg = mPackages.valueAt(i);
15643            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15644        }
15645    }
15646
15647    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15648    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15649        if (userId == UserHandle.USER_ALL) {
15650            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15651                    sUserManager.getUserIds())) {
15652                for (int oneUserId : sUserManager.getUserIds()) {
15653                    scheduleWritePackageRestrictionsLocked(oneUserId);
15654                }
15655            }
15656        } else {
15657            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15658                scheduleWritePackageRestrictionsLocked(userId);
15659            }
15660        }
15661    }
15662
15663    void clearDefaultBrowserIfNeeded(String packageName) {
15664        for (int oneUserId : sUserManager.getUserIds()) {
15665            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15666            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15667            if (packageName.equals(defaultBrowserPackageName)) {
15668                setDefaultBrowserPackageName(null, oneUserId);
15669            }
15670        }
15671    }
15672
15673    @Override
15674    public void resetApplicationPreferences(int userId) {
15675        mContext.enforceCallingOrSelfPermission(
15676                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15677        // writer
15678        synchronized (mPackages) {
15679            final long identity = Binder.clearCallingIdentity();
15680            try {
15681                clearPackagePreferredActivitiesLPw(null, userId);
15682                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15683                // TODO: We have to reset the default SMS and Phone. This requires
15684                // significant refactoring to keep all default apps in the package
15685                // manager (cleaner but more work) or have the services provide
15686                // callbacks to the package manager to request a default app reset.
15687                applyFactoryDefaultBrowserLPw(userId);
15688                clearIntentFilterVerificationsLPw(userId);
15689                primeDomainVerificationsLPw(userId);
15690                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15691                scheduleWritePackageRestrictionsLocked(userId);
15692            } finally {
15693                Binder.restoreCallingIdentity(identity);
15694            }
15695        }
15696    }
15697
15698    @Override
15699    public int getPreferredActivities(List<IntentFilter> outFilters,
15700            List<ComponentName> outActivities, String packageName) {
15701
15702        int num = 0;
15703        final int userId = UserHandle.getCallingUserId();
15704        // reader
15705        synchronized (mPackages) {
15706            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15707            if (pir != null) {
15708                final Iterator<PreferredActivity> it = pir.filterIterator();
15709                while (it.hasNext()) {
15710                    final PreferredActivity pa = it.next();
15711                    if (packageName == null
15712                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15713                                    && pa.mPref.mAlways)) {
15714                        if (outFilters != null) {
15715                            outFilters.add(new IntentFilter(pa));
15716                        }
15717                        if (outActivities != null) {
15718                            outActivities.add(pa.mPref.mComponent);
15719                        }
15720                    }
15721                }
15722            }
15723        }
15724
15725        return num;
15726    }
15727
15728    @Override
15729    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15730            int userId) {
15731        int callingUid = Binder.getCallingUid();
15732        if (callingUid != Process.SYSTEM_UID) {
15733            throw new SecurityException(
15734                    "addPersistentPreferredActivity can only be run by the system");
15735        }
15736        if (filter.countActions() == 0) {
15737            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15738            return;
15739        }
15740        synchronized (mPackages) {
15741            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15742                    ":");
15743            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15744            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15745                    new PersistentPreferredActivity(filter, activity));
15746            scheduleWritePackageRestrictionsLocked(userId);
15747        }
15748    }
15749
15750    @Override
15751    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15752        int callingUid = Binder.getCallingUid();
15753        if (callingUid != Process.SYSTEM_UID) {
15754            throw new SecurityException(
15755                    "clearPackagePersistentPreferredActivities can only be run by the system");
15756        }
15757        ArrayList<PersistentPreferredActivity> removed = null;
15758        boolean changed = false;
15759        synchronized (mPackages) {
15760            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15761                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15762                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15763                        .valueAt(i);
15764                if (userId != thisUserId) {
15765                    continue;
15766                }
15767                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15768                while (it.hasNext()) {
15769                    PersistentPreferredActivity ppa = it.next();
15770                    // Mark entry for removal only if it matches the package name.
15771                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15772                        if (removed == null) {
15773                            removed = new ArrayList<PersistentPreferredActivity>();
15774                        }
15775                        removed.add(ppa);
15776                    }
15777                }
15778                if (removed != null) {
15779                    for (int j=0; j<removed.size(); j++) {
15780                        PersistentPreferredActivity ppa = removed.get(j);
15781                        ppir.removeFilter(ppa);
15782                    }
15783                    changed = true;
15784                }
15785            }
15786
15787            if (changed) {
15788                scheduleWritePackageRestrictionsLocked(userId);
15789            }
15790        }
15791    }
15792
15793    /**
15794     * Common machinery for picking apart a restored XML blob and passing
15795     * it to a caller-supplied functor to be applied to the running system.
15796     */
15797    private void restoreFromXml(XmlPullParser parser, int userId,
15798            String expectedStartTag, BlobXmlRestorer functor)
15799            throws IOException, XmlPullParserException {
15800        int type;
15801        while ((type = parser.next()) != XmlPullParser.START_TAG
15802                && type != XmlPullParser.END_DOCUMENT) {
15803        }
15804        if (type != XmlPullParser.START_TAG) {
15805            // oops didn't find a start tag?!
15806            if (DEBUG_BACKUP) {
15807                Slog.e(TAG, "Didn't find start tag during restore");
15808            }
15809            return;
15810        }
15811Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15812        // this is supposed to be TAG_PREFERRED_BACKUP
15813        if (!expectedStartTag.equals(parser.getName())) {
15814            if (DEBUG_BACKUP) {
15815                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15816            }
15817            return;
15818        }
15819
15820        // skip interfering stuff, then we're aligned with the backing implementation
15821        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15822Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15823        functor.apply(parser, userId);
15824    }
15825
15826    private interface BlobXmlRestorer {
15827        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15828    }
15829
15830    /**
15831     * Non-Binder method, support for the backup/restore mechanism: write the
15832     * full set of preferred activities in its canonical XML format.  Returns the
15833     * XML output as a byte array, or null if there is none.
15834     */
15835    @Override
15836    public byte[] getPreferredActivityBackup(int userId) {
15837        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15838            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15839        }
15840
15841        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15842        try {
15843            final XmlSerializer serializer = new FastXmlSerializer();
15844            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15845            serializer.startDocument(null, true);
15846            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15847
15848            synchronized (mPackages) {
15849                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15850            }
15851
15852            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15853            serializer.endDocument();
15854            serializer.flush();
15855        } catch (Exception e) {
15856            if (DEBUG_BACKUP) {
15857                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15858            }
15859            return null;
15860        }
15861
15862        return dataStream.toByteArray();
15863    }
15864
15865    @Override
15866    public void restorePreferredActivities(byte[] backup, int userId) {
15867        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15868            throw new SecurityException("Only the system may call restorePreferredActivities()");
15869        }
15870
15871        try {
15872            final XmlPullParser parser = Xml.newPullParser();
15873            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15874            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15875                    new BlobXmlRestorer() {
15876                        @Override
15877                        public void apply(XmlPullParser parser, int userId)
15878                                throws XmlPullParserException, IOException {
15879                            synchronized (mPackages) {
15880                                mSettings.readPreferredActivitiesLPw(parser, userId);
15881                            }
15882                        }
15883                    } );
15884        } catch (Exception e) {
15885            if (DEBUG_BACKUP) {
15886                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15887            }
15888        }
15889    }
15890
15891    /**
15892     * Non-Binder method, support for the backup/restore mechanism: write the
15893     * default browser (etc) settings in its canonical XML format.  Returns the default
15894     * browser XML representation as a byte array, or null if there is none.
15895     */
15896    @Override
15897    public byte[] getDefaultAppsBackup(int userId) {
15898        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15899            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15900        }
15901
15902        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15903        try {
15904            final XmlSerializer serializer = new FastXmlSerializer();
15905            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15906            serializer.startDocument(null, true);
15907            serializer.startTag(null, TAG_DEFAULT_APPS);
15908
15909            synchronized (mPackages) {
15910                mSettings.writeDefaultAppsLPr(serializer, userId);
15911            }
15912
15913            serializer.endTag(null, TAG_DEFAULT_APPS);
15914            serializer.endDocument();
15915            serializer.flush();
15916        } catch (Exception e) {
15917            if (DEBUG_BACKUP) {
15918                Slog.e(TAG, "Unable to write default apps for backup", e);
15919            }
15920            return null;
15921        }
15922
15923        return dataStream.toByteArray();
15924    }
15925
15926    @Override
15927    public void restoreDefaultApps(byte[] backup, int userId) {
15928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15929            throw new SecurityException("Only the system may call restoreDefaultApps()");
15930        }
15931
15932        try {
15933            final XmlPullParser parser = Xml.newPullParser();
15934            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15935            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15936                    new BlobXmlRestorer() {
15937                        @Override
15938                        public void apply(XmlPullParser parser, int userId)
15939                                throws XmlPullParserException, IOException {
15940                            synchronized (mPackages) {
15941                                mSettings.readDefaultAppsLPw(parser, userId);
15942                            }
15943                        }
15944                    } );
15945        } catch (Exception e) {
15946            if (DEBUG_BACKUP) {
15947                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15948            }
15949        }
15950    }
15951
15952    @Override
15953    public byte[] getIntentFilterVerificationBackup(int userId) {
15954        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15955            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15956        }
15957
15958        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15959        try {
15960            final XmlSerializer serializer = new FastXmlSerializer();
15961            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15962            serializer.startDocument(null, true);
15963            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15964
15965            synchronized (mPackages) {
15966                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15967            }
15968
15969            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15970            serializer.endDocument();
15971            serializer.flush();
15972        } catch (Exception e) {
15973            if (DEBUG_BACKUP) {
15974                Slog.e(TAG, "Unable to write default apps for backup", e);
15975            }
15976            return null;
15977        }
15978
15979        return dataStream.toByteArray();
15980    }
15981
15982    @Override
15983    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15984        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15985            throw new SecurityException("Only the system may call restorePreferredActivities()");
15986        }
15987
15988        try {
15989            final XmlPullParser parser = Xml.newPullParser();
15990            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15991            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15992                    new BlobXmlRestorer() {
15993                        @Override
15994                        public void apply(XmlPullParser parser, int userId)
15995                                throws XmlPullParserException, IOException {
15996                            synchronized (mPackages) {
15997                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15998                                mSettings.writeLPr();
15999                            }
16000                        }
16001                    } );
16002        } catch (Exception e) {
16003            if (DEBUG_BACKUP) {
16004                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16005            }
16006        }
16007    }
16008
16009    @Override
16010    public byte[] getPermissionGrantBackup(int userId) {
16011        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16012            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16013        }
16014
16015        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16016        try {
16017            final XmlSerializer serializer = new FastXmlSerializer();
16018            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16019            serializer.startDocument(null, true);
16020            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16021
16022            synchronized (mPackages) {
16023                serializeRuntimePermissionGrantsLPr(serializer, userId);
16024            }
16025
16026            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16027            serializer.endDocument();
16028            serializer.flush();
16029        } catch (Exception e) {
16030            if (DEBUG_BACKUP) {
16031                Slog.e(TAG, "Unable to write default apps for backup", e);
16032            }
16033            return null;
16034        }
16035
16036        return dataStream.toByteArray();
16037    }
16038
16039    @Override
16040    public void restorePermissionGrants(byte[] backup, int userId) {
16041        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16042            throw new SecurityException("Only the system may call restorePermissionGrants()");
16043        }
16044
16045        try {
16046            final XmlPullParser parser = Xml.newPullParser();
16047            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16048            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16049                    new BlobXmlRestorer() {
16050                        @Override
16051                        public void apply(XmlPullParser parser, int userId)
16052                                throws XmlPullParserException, IOException {
16053                            synchronized (mPackages) {
16054                                processRestoredPermissionGrantsLPr(parser, userId);
16055                            }
16056                        }
16057                    } );
16058        } catch (Exception e) {
16059            if (DEBUG_BACKUP) {
16060                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16061            }
16062        }
16063    }
16064
16065    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16066            throws IOException {
16067        serializer.startTag(null, TAG_ALL_GRANTS);
16068
16069        final int N = mSettings.mPackages.size();
16070        for (int i = 0; i < N; i++) {
16071            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16072            boolean pkgGrantsKnown = false;
16073
16074            PermissionsState packagePerms = ps.getPermissionsState();
16075
16076            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16077                final int grantFlags = state.getFlags();
16078                // only look at grants that are not system/policy fixed
16079                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16080                    final boolean isGranted = state.isGranted();
16081                    // And only back up the user-twiddled state bits
16082                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16083                        final String packageName = mSettings.mPackages.keyAt(i);
16084                        if (!pkgGrantsKnown) {
16085                            serializer.startTag(null, TAG_GRANT);
16086                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16087                            pkgGrantsKnown = true;
16088                        }
16089
16090                        final boolean userSet =
16091                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16092                        final boolean userFixed =
16093                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16094                        final boolean revoke =
16095                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16096
16097                        serializer.startTag(null, TAG_PERMISSION);
16098                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16099                        if (isGranted) {
16100                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16101                        }
16102                        if (userSet) {
16103                            serializer.attribute(null, ATTR_USER_SET, "true");
16104                        }
16105                        if (userFixed) {
16106                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16107                        }
16108                        if (revoke) {
16109                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16110                        }
16111                        serializer.endTag(null, TAG_PERMISSION);
16112                    }
16113                }
16114            }
16115
16116            if (pkgGrantsKnown) {
16117                serializer.endTag(null, TAG_GRANT);
16118            }
16119        }
16120
16121        serializer.endTag(null, TAG_ALL_GRANTS);
16122    }
16123
16124    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16125            throws XmlPullParserException, IOException {
16126        String pkgName = null;
16127        int outerDepth = parser.getDepth();
16128        int type;
16129        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16130                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16131            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16132                continue;
16133            }
16134
16135            final String tagName = parser.getName();
16136            if (tagName.equals(TAG_GRANT)) {
16137                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16138                if (DEBUG_BACKUP) {
16139                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16140                }
16141            } else if (tagName.equals(TAG_PERMISSION)) {
16142
16143                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16144                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16145
16146                int newFlagSet = 0;
16147                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16148                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16149                }
16150                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16151                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16152                }
16153                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16154                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16155                }
16156                if (DEBUG_BACKUP) {
16157                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16158                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16159                }
16160                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16161                if (ps != null) {
16162                    // Already installed so we apply the grant immediately
16163                    if (DEBUG_BACKUP) {
16164                        Slog.v(TAG, "        + already installed; applying");
16165                    }
16166                    PermissionsState perms = ps.getPermissionsState();
16167                    BasePermission bp = mSettings.mPermissions.get(permName);
16168                    if (bp != null) {
16169                        if (isGranted) {
16170                            perms.grantRuntimePermission(bp, userId);
16171                        }
16172                        if (newFlagSet != 0) {
16173                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16174                        }
16175                    }
16176                } else {
16177                    // Need to wait for post-restore install to apply the grant
16178                    if (DEBUG_BACKUP) {
16179                        Slog.v(TAG, "        - not yet installed; saving for later");
16180                    }
16181                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16182                            isGranted, newFlagSet, userId);
16183                }
16184            } else {
16185                PackageManagerService.reportSettingsProblem(Log.WARN,
16186                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16187                XmlUtils.skipCurrentTag(parser);
16188            }
16189        }
16190
16191        scheduleWriteSettingsLocked();
16192        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16193    }
16194
16195    @Override
16196    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16197            int sourceUserId, int targetUserId, int flags) {
16198        mContext.enforceCallingOrSelfPermission(
16199                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16200        int callingUid = Binder.getCallingUid();
16201        enforceOwnerRights(ownerPackage, callingUid);
16202        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16203        if (intentFilter.countActions() == 0) {
16204            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16205            return;
16206        }
16207        synchronized (mPackages) {
16208            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16209                    ownerPackage, targetUserId, flags);
16210            CrossProfileIntentResolver resolver =
16211                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16212            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16213            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16214            if (existing != null) {
16215                int size = existing.size();
16216                for (int i = 0; i < size; i++) {
16217                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16218                        return;
16219                    }
16220                }
16221            }
16222            resolver.addFilter(newFilter);
16223            scheduleWritePackageRestrictionsLocked(sourceUserId);
16224        }
16225    }
16226
16227    @Override
16228    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16229        mContext.enforceCallingOrSelfPermission(
16230                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16231        int callingUid = Binder.getCallingUid();
16232        enforceOwnerRights(ownerPackage, callingUid);
16233        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16234        synchronized (mPackages) {
16235            CrossProfileIntentResolver resolver =
16236                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16237            ArraySet<CrossProfileIntentFilter> set =
16238                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16239            for (CrossProfileIntentFilter filter : set) {
16240                if (filter.getOwnerPackage().equals(ownerPackage)) {
16241                    resolver.removeFilter(filter);
16242                }
16243            }
16244            scheduleWritePackageRestrictionsLocked(sourceUserId);
16245        }
16246    }
16247
16248    // Enforcing that callingUid is owning pkg on userId
16249    private void enforceOwnerRights(String pkg, int callingUid) {
16250        // The system owns everything.
16251        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16252            return;
16253        }
16254        int callingUserId = UserHandle.getUserId(callingUid);
16255        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16256        if (pi == null) {
16257            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16258                    + callingUserId);
16259        }
16260        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16261            throw new SecurityException("Calling uid " + callingUid
16262                    + " does not own package " + pkg);
16263        }
16264    }
16265
16266    @Override
16267    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16268        Intent intent = new Intent(Intent.ACTION_MAIN);
16269        intent.addCategory(Intent.CATEGORY_HOME);
16270
16271        final int callingUserId = UserHandle.getCallingUserId();
16272        List<ResolveInfo> list = queryIntentActivities(intent, null,
16273                PackageManager.GET_META_DATA, callingUserId);
16274        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16275                true, false, false, callingUserId);
16276
16277        allHomeCandidates.clear();
16278        if (list != null) {
16279            for (ResolveInfo ri : list) {
16280                allHomeCandidates.add(ri);
16281            }
16282        }
16283        return (preferred == null || preferred.activityInfo == null)
16284                ? null
16285                : new ComponentName(preferred.activityInfo.packageName,
16286                        preferred.activityInfo.name);
16287    }
16288
16289    @Override
16290    public void setApplicationEnabledSetting(String appPackageName,
16291            int newState, int flags, int userId, String callingPackage) {
16292        if (!sUserManager.exists(userId)) return;
16293        if (callingPackage == null) {
16294            callingPackage = Integer.toString(Binder.getCallingUid());
16295        }
16296        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16297    }
16298
16299    @Override
16300    public void setComponentEnabledSetting(ComponentName componentName,
16301            int newState, int flags, int userId) {
16302        if (!sUserManager.exists(userId)) return;
16303        setEnabledSetting(componentName.getPackageName(),
16304                componentName.getClassName(), newState, flags, userId, null);
16305    }
16306
16307    private void setEnabledSetting(final String packageName, String className, int newState,
16308            final int flags, int userId, String callingPackage) {
16309        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16310              || newState == COMPONENT_ENABLED_STATE_ENABLED
16311              || newState == COMPONENT_ENABLED_STATE_DISABLED
16312              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16313              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16314            throw new IllegalArgumentException("Invalid new component state: "
16315                    + newState);
16316        }
16317        PackageSetting pkgSetting;
16318        final int uid = Binder.getCallingUid();
16319        final int permission = mContext.checkCallingOrSelfPermission(
16320                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16321        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
16322        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16323        boolean sendNow = false;
16324        boolean isApp = (className == null);
16325        String componentName = isApp ? packageName : className;
16326        int packageUid = -1;
16327        ArrayList<String> components;
16328
16329        // writer
16330        synchronized (mPackages) {
16331            pkgSetting = mSettings.mPackages.get(packageName);
16332            if (pkgSetting == null) {
16333                if (className == null) {
16334                    throw new IllegalArgumentException("Unknown package: " + packageName);
16335                }
16336                throw new IllegalArgumentException(
16337                        "Unknown component: " + packageName + "/" + className);
16338            }
16339            // Allow root and verify that userId is not being specified by a different user
16340            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16341                throw new SecurityException(
16342                        "Permission Denial: attempt to change component state from pid="
16343                        + Binder.getCallingPid()
16344                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16345            }
16346            if (className == null) {
16347                // We're dealing with an application/package level state change
16348                if (pkgSetting.getEnabled(userId) == newState) {
16349                    // Nothing to do
16350                    return;
16351                }
16352                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16353                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16354                    // Don't care about who enables an app.
16355                    callingPackage = null;
16356                }
16357                pkgSetting.setEnabled(newState, userId, callingPackage);
16358                // pkgSetting.pkg.mSetEnabled = newState;
16359            } else {
16360                // We're dealing with a component level state change
16361                // First, verify that this is a valid class name.
16362                PackageParser.Package pkg = pkgSetting.pkg;
16363                if (pkg == null || !pkg.hasComponentClassName(className)) {
16364                    if (pkg != null &&
16365                            pkg.applicationInfo.targetSdkVersion >=
16366                                    Build.VERSION_CODES.JELLY_BEAN) {
16367                        throw new IllegalArgumentException("Component class " + className
16368                                + " does not exist in " + packageName);
16369                    } else {
16370                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16371                                + className + " does not exist in " + packageName);
16372                    }
16373                }
16374                switch (newState) {
16375                case COMPONENT_ENABLED_STATE_ENABLED:
16376                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16377                        return;
16378                    }
16379                    break;
16380                case COMPONENT_ENABLED_STATE_DISABLED:
16381                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16382                        return;
16383                    }
16384                    break;
16385                case COMPONENT_ENABLED_STATE_DEFAULT:
16386                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16387                        return;
16388                    }
16389                    break;
16390                default:
16391                    Slog.e(TAG, "Invalid new component state: " + newState);
16392                    return;
16393                }
16394            }
16395            scheduleWritePackageRestrictionsLocked(userId);
16396            components = mPendingBroadcasts.get(userId, packageName);
16397            final boolean newPackage = components == null;
16398            if (newPackage) {
16399                components = new ArrayList<String>();
16400            }
16401            if (!components.contains(componentName)) {
16402                components.add(componentName);
16403            }
16404            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16405                sendNow = true;
16406                // Purge entry from pending broadcast list if another one exists already
16407                // since we are sending one right away.
16408                mPendingBroadcasts.remove(userId, packageName);
16409            } else {
16410                if (newPackage) {
16411                    mPendingBroadcasts.put(userId, packageName, components);
16412                }
16413                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16414                    // Schedule a message
16415                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16416                }
16417            }
16418        }
16419
16420        long callingId = Binder.clearCallingIdentity();
16421        try {
16422            if (sendNow) {
16423                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16424                sendPackageChangedBroadcast(packageName,
16425                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16426            }
16427        } finally {
16428            Binder.restoreCallingIdentity(callingId);
16429        }
16430    }
16431
16432    private void sendPackageChangedBroadcast(String packageName,
16433            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16434        if (DEBUG_INSTALL)
16435            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16436                    + componentNames);
16437        Bundle extras = new Bundle(4);
16438        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16439        String nameList[] = new String[componentNames.size()];
16440        componentNames.toArray(nameList);
16441        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16442        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16443        extras.putInt(Intent.EXTRA_UID, packageUid);
16444        // If this is not reporting a change of the overall package, then only send it
16445        // to registered receivers.  We don't want to launch a swath of apps for every
16446        // little component state change.
16447        final int flags = !componentNames.contains(packageName)
16448                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16449        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16450                new int[] {UserHandle.getUserId(packageUid)});
16451    }
16452
16453    @Override
16454    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16455        if (!sUserManager.exists(userId)) return;
16456        final int uid = Binder.getCallingUid();
16457        final int permission = mContext.checkCallingOrSelfPermission(
16458                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16459        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16460        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16461        // writer
16462        synchronized (mPackages) {
16463            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16464                    allowedByPermission, uid, userId)) {
16465                scheduleWritePackageRestrictionsLocked(userId);
16466            }
16467        }
16468    }
16469
16470    @Override
16471    public String getInstallerPackageName(String packageName) {
16472        // reader
16473        synchronized (mPackages) {
16474            return mSettings.getInstallerPackageNameLPr(packageName);
16475        }
16476    }
16477
16478    @Override
16479    public int getApplicationEnabledSetting(String packageName, int userId) {
16480        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16481        int uid = Binder.getCallingUid();
16482        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16483        // reader
16484        synchronized (mPackages) {
16485            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16486        }
16487    }
16488
16489    @Override
16490    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16491        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16492        int uid = Binder.getCallingUid();
16493        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16494        // reader
16495        synchronized (mPackages) {
16496            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16497        }
16498    }
16499
16500    @Override
16501    public void enterSafeMode() {
16502        enforceSystemOrRoot("Only the system can request entering safe mode");
16503
16504        if (!mSystemReady) {
16505            mSafeMode = true;
16506        }
16507    }
16508
16509    @Override
16510    public void systemReady() {
16511        mSystemReady = true;
16512
16513        // Read the compatibilty setting when the system is ready.
16514        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16515                mContext.getContentResolver(),
16516                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16517        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16518        if (DEBUG_SETTINGS) {
16519            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16520        }
16521
16522        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16523
16524        synchronized (mPackages) {
16525            // Verify that all of the preferred activity components actually
16526            // exist.  It is possible for applications to be updated and at
16527            // that point remove a previously declared activity component that
16528            // had been set as a preferred activity.  We try to clean this up
16529            // the next time we encounter that preferred activity, but it is
16530            // possible for the user flow to never be able to return to that
16531            // situation so here we do a sanity check to make sure we haven't
16532            // left any junk around.
16533            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16534            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16535                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16536                removed.clear();
16537                for (PreferredActivity pa : pir.filterSet()) {
16538                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16539                        removed.add(pa);
16540                    }
16541                }
16542                if (removed.size() > 0) {
16543                    for (int r=0; r<removed.size(); r++) {
16544                        PreferredActivity pa = removed.get(r);
16545                        Slog.w(TAG, "Removing dangling preferred activity: "
16546                                + pa.mPref.mComponent);
16547                        pir.removeFilter(pa);
16548                    }
16549                    mSettings.writePackageRestrictionsLPr(
16550                            mSettings.mPreferredActivities.keyAt(i));
16551                }
16552            }
16553
16554            for (int userId : UserManagerService.getInstance().getUserIds()) {
16555                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16556                    grantPermissionsUserIds = ArrayUtils.appendInt(
16557                            grantPermissionsUserIds, userId);
16558                }
16559            }
16560        }
16561        sUserManager.systemReady();
16562
16563        // If we upgraded grant all default permissions before kicking off.
16564        for (int userId : grantPermissionsUserIds) {
16565            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16566        }
16567
16568        // Kick off any messages waiting for system ready
16569        if (mPostSystemReadyMessages != null) {
16570            for (Message msg : mPostSystemReadyMessages) {
16571                msg.sendToTarget();
16572            }
16573            mPostSystemReadyMessages = null;
16574        }
16575
16576        // Watch for external volumes that come and go over time
16577        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16578        storage.registerListener(mStorageListener);
16579
16580        mInstallerService.systemReady();
16581        mPackageDexOptimizer.systemReady();
16582
16583        MountServiceInternal mountServiceInternal = LocalServices.getService(
16584                MountServiceInternal.class);
16585        mountServiceInternal.addExternalStoragePolicy(
16586                new MountServiceInternal.ExternalStorageMountPolicy() {
16587            @Override
16588            public int getMountMode(int uid, String packageName) {
16589                if (Process.isIsolated(uid)) {
16590                    return Zygote.MOUNT_EXTERNAL_NONE;
16591                }
16592                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16593                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16594                }
16595                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16596                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16597                }
16598                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16599                    return Zygote.MOUNT_EXTERNAL_READ;
16600                }
16601                return Zygote.MOUNT_EXTERNAL_WRITE;
16602            }
16603
16604            @Override
16605            public boolean hasExternalStorage(int uid, String packageName) {
16606                return true;
16607            }
16608        });
16609    }
16610
16611    @Override
16612    public boolean isSafeMode() {
16613        return mSafeMode;
16614    }
16615
16616    @Override
16617    public boolean hasSystemUidErrors() {
16618        return mHasSystemUidErrors;
16619    }
16620
16621    static String arrayToString(int[] array) {
16622        StringBuffer buf = new StringBuffer(128);
16623        buf.append('[');
16624        if (array != null) {
16625            for (int i=0; i<array.length; i++) {
16626                if (i > 0) buf.append(", ");
16627                buf.append(array[i]);
16628            }
16629        }
16630        buf.append(']');
16631        return buf.toString();
16632    }
16633
16634    static class DumpState {
16635        public static final int DUMP_LIBS = 1 << 0;
16636        public static final int DUMP_FEATURES = 1 << 1;
16637        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16638        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16639        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16640        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16641        public static final int DUMP_PERMISSIONS = 1 << 6;
16642        public static final int DUMP_PACKAGES = 1 << 7;
16643        public static final int DUMP_SHARED_USERS = 1 << 8;
16644        public static final int DUMP_MESSAGES = 1 << 9;
16645        public static final int DUMP_PROVIDERS = 1 << 10;
16646        public static final int DUMP_VERIFIERS = 1 << 11;
16647        public static final int DUMP_PREFERRED = 1 << 12;
16648        public static final int DUMP_PREFERRED_XML = 1 << 13;
16649        public static final int DUMP_KEYSETS = 1 << 14;
16650        public static final int DUMP_VERSION = 1 << 15;
16651        public static final int DUMP_INSTALLS = 1 << 16;
16652        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16653        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16654
16655        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16656
16657        private int mTypes;
16658
16659        private int mOptions;
16660
16661        private boolean mTitlePrinted;
16662
16663        private SharedUserSetting mSharedUser;
16664
16665        public boolean isDumping(int type) {
16666            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16667                return true;
16668            }
16669
16670            return (mTypes & type) != 0;
16671        }
16672
16673        public void setDump(int type) {
16674            mTypes |= type;
16675        }
16676
16677        public boolean isOptionEnabled(int option) {
16678            return (mOptions & option) != 0;
16679        }
16680
16681        public void setOptionEnabled(int option) {
16682            mOptions |= option;
16683        }
16684
16685        public boolean onTitlePrinted() {
16686            final boolean printed = mTitlePrinted;
16687            mTitlePrinted = true;
16688            return printed;
16689        }
16690
16691        public boolean getTitlePrinted() {
16692            return mTitlePrinted;
16693        }
16694
16695        public void setTitlePrinted(boolean enabled) {
16696            mTitlePrinted = enabled;
16697        }
16698
16699        public SharedUserSetting getSharedUser() {
16700            return mSharedUser;
16701        }
16702
16703        public void setSharedUser(SharedUserSetting user) {
16704            mSharedUser = user;
16705        }
16706    }
16707
16708    @Override
16709    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16710            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16711        (new PackageManagerShellCommand(this)).exec(
16712                this, in, out, err, args, resultReceiver);
16713    }
16714
16715    @Override
16716    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16717        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16718                != PackageManager.PERMISSION_GRANTED) {
16719            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16720                    + Binder.getCallingPid()
16721                    + ", uid=" + Binder.getCallingUid()
16722                    + " without permission "
16723                    + android.Manifest.permission.DUMP);
16724            return;
16725        }
16726
16727        DumpState dumpState = new DumpState();
16728        boolean fullPreferred = false;
16729        boolean checkin = false;
16730
16731        String packageName = null;
16732        ArraySet<String> permissionNames = null;
16733
16734        int opti = 0;
16735        while (opti < args.length) {
16736            String opt = args[opti];
16737            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16738                break;
16739            }
16740            opti++;
16741
16742            if ("-a".equals(opt)) {
16743                // Right now we only know how to print all.
16744            } else if ("-h".equals(opt)) {
16745                pw.println("Package manager dump options:");
16746                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16747                pw.println("    --checkin: dump for a checkin");
16748                pw.println("    -f: print details of intent filters");
16749                pw.println("    -h: print this help");
16750                pw.println("  cmd may be one of:");
16751                pw.println("    l[ibraries]: list known shared libraries");
16752                pw.println("    f[eatures]: list device features");
16753                pw.println("    k[eysets]: print known keysets");
16754                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16755                pw.println("    perm[issions]: dump permissions");
16756                pw.println("    permission [name ...]: dump declaration and use of given permission");
16757                pw.println("    pref[erred]: print preferred package settings");
16758                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16759                pw.println("    prov[iders]: dump content providers");
16760                pw.println("    p[ackages]: dump installed packages");
16761                pw.println("    s[hared-users]: dump shared user IDs");
16762                pw.println("    m[essages]: print collected runtime messages");
16763                pw.println("    v[erifiers]: print package verifier info");
16764                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16765                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16766                pw.println("    version: print database version info");
16767                pw.println("    write: write current settings now");
16768                pw.println("    installs: details about install sessions");
16769                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16770                pw.println("    <package.name>: info about given package");
16771                return;
16772            } else if ("--checkin".equals(opt)) {
16773                checkin = true;
16774            } else if ("-f".equals(opt)) {
16775                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16776            } else {
16777                pw.println("Unknown argument: " + opt + "; use -h for help");
16778            }
16779        }
16780
16781        // Is the caller requesting to dump a particular piece of data?
16782        if (opti < args.length) {
16783            String cmd = args[opti];
16784            opti++;
16785            // Is this a package name?
16786            if ("android".equals(cmd) || cmd.contains(".")) {
16787                packageName = cmd;
16788                // When dumping a single package, we always dump all of its
16789                // filter information since the amount of data will be reasonable.
16790                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16791            } else if ("check-permission".equals(cmd)) {
16792                if (opti >= args.length) {
16793                    pw.println("Error: check-permission missing permission argument");
16794                    return;
16795                }
16796                String perm = args[opti];
16797                opti++;
16798                if (opti >= args.length) {
16799                    pw.println("Error: check-permission missing package argument");
16800                    return;
16801                }
16802                String pkg = args[opti];
16803                opti++;
16804                int user = UserHandle.getUserId(Binder.getCallingUid());
16805                if (opti < args.length) {
16806                    try {
16807                        user = Integer.parseInt(args[opti]);
16808                    } catch (NumberFormatException e) {
16809                        pw.println("Error: check-permission user argument is not a number: "
16810                                + args[opti]);
16811                        return;
16812                    }
16813                }
16814                pw.println(checkPermission(perm, pkg, user));
16815                return;
16816            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16817                dumpState.setDump(DumpState.DUMP_LIBS);
16818            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16819                dumpState.setDump(DumpState.DUMP_FEATURES);
16820            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16821                if (opti >= args.length) {
16822                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16823                            | DumpState.DUMP_SERVICE_RESOLVERS
16824                            | DumpState.DUMP_RECEIVER_RESOLVERS
16825                            | DumpState.DUMP_CONTENT_RESOLVERS);
16826                } else {
16827                    while (opti < args.length) {
16828                        String name = args[opti];
16829                        if ("a".equals(name) || "activity".equals(name)) {
16830                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16831                        } else if ("s".equals(name) || "service".equals(name)) {
16832                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16833                        } else if ("r".equals(name) || "receiver".equals(name)) {
16834                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16835                        } else if ("c".equals(name) || "content".equals(name)) {
16836                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16837                        } else {
16838                            pw.println("Error: unknown resolver table type: " + name);
16839                            return;
16840                        }
16841                        opti++;
16842                    }
16843                }
16844            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16845                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16846            } else if ("permission".equals(cmd)) {
16847                if (opti >= args.length) {
16848                    pw.println("Error: permission requires permission name");
16849                    return;
16850                }
16851                permissionNames = new ArraySet<>();
16852                while (opti < args.length) {
16853                    permissionNames.add(args[opti]);
16854                    opti++;
16855                }
16856                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16857                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16858            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16859                dumpState.setDump(DumpState.DUMP_PREFERRED);
16860            } else if ("preferred-xml".equals(cmd)) {
16861                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16862                if (opti < args.length && "--full".equals(args[opti])) {
16863                    fullPreferred = true;
16864                    opti++;
16865                }
16866            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16867                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16868            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16869                dumpState.setDump(DumpState.DUMP_PACKAGES);
16870            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16871                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16872            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16873                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16874            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16875                dumpState.setDump(DumpState.DUMP_MESSAGES);
16876            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16877                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16878            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16879                    || "intent-filter-verifiers".equals(cmd)) {
16880                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16881            } else if ("version".equals(cmd)) {
16882                dumpState.setDump(DumpState.DUMP_VERSION);
16883            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16884                dumpState.setDump(DumpState.DUMP_KEYSETS);
16885            } else if ("installs".equals(cmd)) {
16886                dumpState.setDump(DumpState.DUMP_INSTALLS);
16887            } else if ("write".equals(cmd)) {
16888                synchronized (mPackages) {
16889                    mSettings.writeLPr();
16890                    pw.println("Settings written.");
16891                    return;
16892                }
16893            }
16894        }
16895
16896        if (checkin) {
16897            pw.println("vers,1");
16898        }
16899
16900        // reader
16901        synchronized (mPackages) {
16902            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16903                if (!checkin) {
16904                    if (dumpState.onTitlePrinted())
16905                        pw.println();
16906                    pw.println("Database versions:");
16907                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16908                }
16909            }
16910
16911            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16912                if (!checkin) {
16913                    if (dumpState.onTitlePrinted())
16914                        pw.println();
16915                    pw.println("Verifiers:");
16916                    pw.print("  Required: ");
16917                    pw.print(mRequiredVerifierPackage);
16918                    pw.print(" (uid=");
16919                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16920                            UserHandle.USER_SYSTEM));
16921                    pw.println(")");
16922                } else if (mRequiredVerifierPackage != null) {
16923                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16924                    pw.print(",");
16925                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16926                            UserHandle.USER_SYSTEM));
16927                }
16928            }
16929
16930            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16931                    packageName == null) {
16932                if (mIntentFilterVerifierComponent != null) {
16933                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16934                    if (!checkin) {
16935                        if (dumpState.onTitlePrinted())
16936                            pw.println();
16937                        pw.println("Intent Filter Verifier:");
16938                        pw.print("  Using: ");
16939                        pw.print(verifierPackageName);
16940                        pw.print(" (uid=");
16941                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16942                                UserHandle.USER_SYSTEM));
16943                        pw.println(")");
16944                    } else if (verifierPackageName != null) {
16945                        pw.print("ifv,"); pw.print(verifierPackageName);
16946                        pw.print(",");
16947                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16948                                UserHandle.USER_SYSTEM));
16949                    }
16950                } else {
16951                    pw.println();
16952                    pw.println("No Intent Filter Verifier available!");
16953                }
16954            }
16955
16956            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16957                boolean printedHeader = false;
16958                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16959                while (it.hasNext()) {
16960                    String name = it.next();
16961                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16962                    if (!checkin) {
16963                        if (!printedHeader) {
16964                            if (dumpState.onTitlePrinted())
16965                                pw.println();
16966                            pw.println("Libraries:");
16967                            printedHeader = true;
16968                        }
16969                        pw.print("  ");
16970                    } else {
16971                        pw.print("lib,");
16972                    }
16973                    pw.print(name);
16974                    if (!checkin) {
16975                        pw.print(" -> ");
16976                    }
16977                    if (ent.path != null) {
16978                        if (!checkin) {
16979                            pw.print("(jar) ");
16980                            pw.print(ent.path);
16981                        } else {
16982                            pw.print(",jar,");
16983                            pw.print(ent.path);
16984                        }
16985                    } else {
16986                        if (!checkin) {
16987                            pw.print("(apk) ");
16988                            pw.print(ent.apk);
16989                        } else {
16990                            pw.print(",apk,");
16991                            pw.print(ent.apk);
16992                        }
16993                    }
16994                    pw.println();
16995                }
16996            }
16997
16998            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16999                if (dumpState.onTitlePrinted())
17000                    pw.println();
17001                if (!checkin) {
17002                    pw.println("Features:");
17003                }
17004
17005                for (FeatureInfo feat : mAvailableFeatures.values()) {
17006                    if (checkin) {
17007                        pw.print("feat,");
17008                        pw.print(feat.name);
17009                        pw.print(",");
17010                        pw.println(feat.version);
17011                    } else {
17012                        pw.print("  ");
17013                        pw.print(feat.name);
17014                        if (feat.version > 0) {
17015                            pw.print(" version=");
17016                            pw.print(feat.version);
17017                        }
17018                        pw.println();
17019                    }
17020                }
17021            }
17022
17023            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17024                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17025                        : "Activity Resolver Table:", "  ", packageName,
17026                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17027                    dumpState.setTitlePrinted(true);
17028                }
17029            }
17030            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17031                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17032                        : "Receiver Resolver Table:", "  ", packageName,
17033                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17034                    dumpState.setTitlePrinted(true);
17035                }
17036            }
17037            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17038                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17039                        : "Service Resolver Table:", "  ", packageName,
17040                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17041                    dumpState.setTitlePrinted(true);
17042                }
17043            }
17044            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17045                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17046                        : "Provider Resolver Table:", "  ", packageName,
17047                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17048                    dumpState.setTitlePrinted(true);
17049                }
17050            }
17051
17052            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17053                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17054                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17055                    int user = mSettings.mPreferredActivities.keyAt(i);
17056                    if (pir.dump(pw,
17057                            dumpState.getTitlePrinted()
17058                                ? "\nPreferred Activities User " + user + ":"
17059                                : "Preferred Activities User " + user + ":", "  ",
17060                            packageName, true, false)) {
17061                        dumpState.setTitlePrinted(true);
17062                    }
17063                }
17064            }
17065
17066            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17067                pw.flush();
17068                FileOutputStream fout = new FileOutputStream(fd);
17069                BufferedOutputStream str = new BufferedOutputStream(fout);
17070                XmlSerializer serializer = new FastXmlSerializer();
17071                try {
17072                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17073                    serializer.startDocument(null, true);
17074                    serializer.setFeature(
17075                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17076                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17077                    serializer.endDocument();
17078                    serializer.flush();
17079                } catch (IllegalArgumentException e) {
17080                    pw.println("Failed writing: " + e);
17081                } catch (IllegalStateException e) {
17082                    pw.println("Failed writing: " + e);
17083                } catch (IOException e) {
17084                    pw.println("Failed writing: " + e);
17085                }
17086            }
17087
17088            if (!checkin
17089                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17090                    && packageName == null) {
17091                pw.println();
17092                int count = mSettings.mPackages.size();
17093                if (count == 0) {
17094                    pw.println("No applications!");
17095                    pw.println();
17096                } else {
17097                    final String prefix = "  ";
17098                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17099                    if (allPackageSettings.size() == 0) {
17100                        pw.println("No domain preferred apps!");
17101                        pw.println();
17102                    } else {
17103                        pw.println("App verification status:");
17104                        pw.println();
17105                        count = 0;
17106                        for (PackageSetting ps : allPackageSettings) {
17107                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17108                            if (ivi == null || ivi.getPackageName() == null) continue;
17109                            pw.println(prefix + "Package: " + ivi.getPackageName());
17110                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17111                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17112                            pw.println();
17113                            count++;
17114                        }
17115                        if (count == 0) {
17116                            pw.println(prefix + "No app verification established.");
17117                            pw.println();
17118                        }
17119                        for (int userId : sUserManager.getUserIds()) {
17120                            pw.println("App linkages for user " + userId + ":");
17121                            pw.println();
17122                            count = 0;
17123                            for (PackageSetting ps : allPackageSettings) {
17124                                final long status = ps.getDomainVerificationStatusForUser(userId);
17125                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17126                                    continue;
17127                                }
17128                                pw.println(prefix + "Package: " + ps.name);
17129                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17130                                String statusStr = IntentFilterVerificationInfo.
17131                                        getStatusStringFromValue(status);
17132                                pw.println(prefix + "Status:  " + statusStr);
17133                                pw.println();
17134                                count++;
17135                            }
17136                            if (count == 0) {
17137                                pw.println(prefix + "No configured app linkages.");
17138                                pw.println();
17139                            }
17140                        }
17141                    }
17142                }
17143            }
17144
17145            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17146                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17147                if (packageName == null && permissionNames == null) {
17148                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17149                        if (iperm == 0) {
17150                            if (dumpState.onTitlePrinted())
17151                                pw.println();
17152                            pw.println("AppOp Permissions:");
17153                        }
17154                        pw.print("  AppOp Permission ");
17155                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17156                        pw.println(":");
17157                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17158                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17159                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17160                        }
17161                    }
17162                }
17163            }
17164
17165            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17166                boolean printedSomething = false;
17167                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17168                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17169                        continue;
17170                    }
17171                    if (!printedSomething) {
17172                        if (dumpState.onTitlePrinted())
17173                            pw.println();
17174                        pw.println("Registered ContentProviders:");
17175                        printedSomething = true;
17176                    }
17177                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17178                    pw.print("    "); pw.println(p.toString());
17179                }
17180                printedSomething = false;
17181                for (Map.Entry<String, PackageParser.Provider> entry :
17182                        mProvidersByAuthority.entrySet()) {
17183                    PackageParser.Provider p = entry.getValue();
17184                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17185                        continue;
17186                    }
17187                    if (!printedSomething) {
17188                        if (dumpState.onTitlePrinted())
17189                            pw.println();
17190                        pw.println("ContentProvider Authorities:");
17191                        printedSomething = true;
17192                    }
17193                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17194                    pw.print("    "); pw.println(p.toString());
17195                    if (p.info != null && p.info.applicationInfo != null) {
17196                        final String appInfo = p.info.applicationInfo.toString();
17197                        pw.print("      applicationInfo="); pw.println(appInfo);
17198                    }
17199                }
17200            }
17201
17202            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17203                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17204            }
17205
17206            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17207                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17208            }
17209
17210            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17211                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17212            }
17213
17214            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17215                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17216            }
17217
17218            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17219                // XXX should handle packageName != null by dumping only install data that
17220                // the given package is involved with.
17221                if (dumpState.onTitlePrinted()) pw.println();
17222                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17223            }
17224
17225            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17226                if (dumpState.onTitlePrinted()) pw.println();
17227                mSettings.dumpReadMessagesLPr(pw, dumpState);
17228
17229                pw.println();
17230                pw.println("Package warning messages:");
17231                BufferedReader in = null;
17232                String line = null;
17233                try {
17234                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17235                    while ((line = in.readLine()) != null) {
17236                        if (line.contains("ignored: updated version")) continue;
17237                        pw.println(line);
17238                    }
17239                } catch (IOException ignored) {
17240                } finally {
17241                    IoUtils.closeQuietly(in);
17242                }
17243            }
17244
17245            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17246                BufferedReader in = null;
17247                String line = null;
17248                try {
17249                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17250                    while ((line = in.readLine()) != null) {
17251                        if (line.contains("ignored: updated version")) continue;
17252                        pw.print("msg,");
17253                        pw.println(line);
17254                    }
17255                } catch (IOException ignored) {
17256                } finally {
17257                    IoUtils.closeQuietly(in);
17258                }
17259            }
17260        }
17261    }
17262
17263    private String dumpDomainString(String packageName) {
17264        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17265        List<IntentFilter> filters = getAllIntentFilters(packageName);
17266
17267        ArraySet<String> result = new ArraySet<>();
17268        if (iviList.size() > 0) {
17269            for (IntentFilterVerificationInfo ivi : iviList) {
17270                for (String host : ivi.getDomains()) {
17271                    result.add(host);
17272                }
17273            }
17274        }
17275        if (filters != null && filters.size() > 0) {
17276            for (IntentFilter filter : filters) {
17277                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17278                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17279                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17280                    result.addAll(filter.getHostsList());
17281                }
17282            }
17283        }
17284
17285        StringBuilder sb = new StringBuilder(result.size() * 16);
17286        for (String domain : result) {
17287            if (sb.length() > 0) sb.append(" ");
17288            sb.append(domain);
17289        }
17290        return sb.toString();
17291    }
17292
17293    // ------- apps on sdcard specific code -------
17294    static final boolean DEBUG_SD_INSTALL = false;
17295
17296    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17297
17298    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17299
17300    private boolean mMediaMounted = false;
17301
17302    static String getEncryptKey() {
17303        try {
17304            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17305                    SD_ENCRYPTION_KEYSTORE_NAME);
17306            if (sdEncKey == null) {
17307                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17308                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17309                if (sdEncKey == null) {
17310                    Slog.e(TAG, "Failed to create encryption keys");
17311                    return null;
17312                }
17313            }
17314            return sdEncKey;
17315        } catch (NoSuchAlgorithmException nsae) {
17316            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17317            return null;
17318        } catch (IOException ioe) {
17319            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17320            return null;
17321        }
17322    }
17323
17324    /*
17325     * Update media status on PackageManager.
17326     */
17327    @Override
17328    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17329        int callingUid = Binder.getCallingUid();
17330        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17331            throw new SecurityException("Media status can only be updated by the system");
17332        }
17333        // reader; this apparently protects mMediaMounted, but should probably
17334        // be a different lock in that case.
17335        synchronized (mPackages) {
17336            Log.i(TAG, "Updating external media status from "
17337                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17338                    + (mediaStatus ? "mounted" : "unmounted"));
17339            if (DEBUG_SD_INSTALL)
17340                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17341                        + ", mMediaMounted=" + mMediaMounted);
17342            if (mediaStatus == mMediaMounted) {
17343                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17344                        : 0, -1);
17345                mHandler.sendMessage(msg);
17346                return;
17347            }
17348            mMediaMounted = mediaStatus;
17349        }
17350        // Queue up an async operation since the package installation may take a
17351        // little while.
17352        mHandler.post(new Runnable() {
17353            public void run() {
17354                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17355            }
17356        });
17357    }
17358
17359    /**
17360     * Called by MountService when the initial ASECs to scan are available.
17361     * Should block until all the ASEC containers are finished being scanned.
17362     */
17363    public void scanAvailableAsecs() {
17364        updateExternalMediaStatusInner(true, false, false);
17365    }
17366
17367    /*
17368     * Collect information of applications on external media, map them against
17369     * existing containers and update information based on current mount status.
17370     * Please note that we always have to report status if reportStatus has been
17371     * set to true especially when unloading packages.
17372     */
17373    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17374            boolean externalStorage) {
17375        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17376        int[] uidArr = EmptyArray.INT;
17377
17378        final String[] list = PackageHelper.getSecureContainerList();
17379        if (ArrayUtils.isEmpty(list)) {
17380            Log.i(TAG, "No secure containers found");
17381        } else {
17382            // Process list of secure containers and categorize them
17383            // as active or stale based on their package internal state.
17384
17385            // reader
17386            synchronized (mPackages) {
17387                for (String cid : list) {
17388                    // Leave stages untouched for now; installer service owns them
17389                    if (PackageInstallerService.isStageName(cid)) continue;
17390
17391                    if (DEBUG_SD_INSTALL)
17392                        Log.i(TAG, "Processing container " + cid);
17393                    String pkgName = getAsecPackageName(cid);
17394                    if (pkgName == null) {
17395                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17396                        continue;
17397                    }
17398                    if (DEBUG_SD_INSTALL)
17399                        Log.i(TAG, "Looking for pkg : " + pkgName);
17400
17401                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17402                    if (ps == null) {
17403                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17404                        continue;
17405                    }
17406
17407                    /*
17408                     * Skip packages that are not external if we're unmounting
17409                     * external storage.
17410                     */
17411                    if (externalStorage && !isMounted && !isExternal(ps)) {
17412                        continue;
17413                    }
17414
17415                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17416                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17417                    // The package status is changed only if the code path
17418                    // matches between settings and the container id.
17419                    if (ps.codePathString != null
17420                            && ps.codePathString.startsWith(args.getCodePath())) {
17421                        if (DEBUG_SD_INSTALL) {
17422                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17423                                    + " at code path: " + ps.codePathString);
17424                        }
17425
17426                        // We do have a valid package installed on sdcard
17427                        processCids.put(args, ps.codePathString);
17428                        final int uid = ps.appId;
17429                        if (uid != -1) {
17430                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17431                        }
17432                    } else {
17433                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17434                                + ps.codePathString);
17435                    }
17436                }
17437            }
17438
17439            Arrays.sort(uidArr);
17440        }
17441
17442        // Process packages with valid entries.
17443        if (isMounted) {
17444            if (DEBUG_SD_INSTALL)
17445                Log.i(TAG, "Loading packages");
17446            loadMediaPackages(processCids, uidArr, externalStorage);
17447            startCleaningPackages();
17448            mInstallerService.onSecureContainersAvailable();
17449        } else {
17450            if (DEBUG_SD_INSTALL)
17451                Log.i(TAG, "Unloading packages");
17452            unloadMediaPackages(processCids, uidArr, reportStatus);
17453        }
17454    }
17455
17456    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17457            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17458        final int size = infos.size();
17459        final String[] packageNames = new String[size];
17460        final int[] packageUids = new int[size];
17461        for (int i = 0; i < size; i++) {
17462            final ApplicationInfo info = infos.get(i);
17463            packageNames[i] = info.packageName;
17464            packageUids[i] = info.uid;
17465        }
17466        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17467                finishedReceiver);
17468    }
17469
17470    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17471            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17472        sendResourcesChangedBroadcast(mediaStatus, replacing,
17473                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17474    }
17475
17476    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17477            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17478        int size = pkgList.length;
17479        if (size > 0) {
17480            // Send broadcasts here
17481            Bundle extras = new Bundle();
17482            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17483            if (uidArr != null) {
17484                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17485            }
17486            if (replacing) {
17487                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17488            }
17489            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17490                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17491            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17492        }
17493    }
17494
17495   /*
17496     * Look at potentially valid container ids from processCids If package
17497     * information doesn't match the one on record or package scanning fails,
17498     * the cid is added to list of removeCids. We currently don't delete stale
17499     * containers.
17500     */
17501    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17502            boolean externalStorage) {
17503        ArrayList<String> pkgList = new ArrayList<String>();
17504        Set<AsecInstallArgs> keys = processCids.keySet();
17505
17506        for (AsecInstallArgs args : keys) {
17507            String codePath = processCids.get(args);
17508            if (DEBUG_SD_INSTALL)
17509                Log.i(TAG, "Loading container : " + args.cid);
17510            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17511            try {
17512                // Make sure there are no container errors first.
17513                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17514                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17515                            + " when installing from sdcard");
17516                    continue;
17517                }
17518                // Check code path here.
17519                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17520                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17521                            + " does not match one in settings " + codePath);
17522                    continue;
17523                }
17524                // Parse package
17525                int parseFlags = mDefParseFlags;
17526                if (args.isExternalAsec()) {
17527                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17528                }
17529                if (args.isFwdLocked()) {
17530                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17531                }
17532
17533                synchronized (mInstallLock) {
17534                    PackageParser.Package pkg = null;
17535                    try {
17536                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17537                    } catch (PackageManagerException e) {
17538                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17539                    }
17540                    // Scan the package
17541                    if (pkg != null) {
17542                        /*
17543                         * TODO why is the lock being held? doPostInstall is
17544                         * called in other places without the lock. This needs
17545                         * to be straightened out.
17546                         */
17547                        // writer
17548                        synchronized (mPackages) {
17549                            retCode = PackageManager.INSTALL_SUCCEEDED;
17550                            pkgList.add(pkg.packageName);
17551                            // Post process args
17552                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17553                                    pkg.applicationInfo.uid);
17554                        }
17555                    } else {
17556                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17557                    }
17558                }
17559
17560            } finally {
17561                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17562                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17563                }
17564            }
17565        }
17566        // writer
17567        synchronized (mPackages) {
17568            // If the platform SDK has changed since the last time we booted,
17569            // we need to re-grant app permission to catch any new ones that
17570            // appear. This is really a hack, and means that apps can in some
17571            // cases get permissions that the user didn't initially explicitly
17572            // allow... it would be nice to have some better way to handle
17573            // this situation.
17574            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17575                    : mSettings.getInternalVersion();
17576            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17577                    : StorageManager.UUID_PRIVATE_INTERNAL;
17578
17579            int updateFlags = UPDATE_PERMISSIONS_ALL;
17580            if (ver.sdkVersion != mSdkVersion) {
17581                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17582                        + mSdkVersion + "; regranting permissions for external");
17583                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17584            }
17585            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17586
17587            // Yay, everything is now upgraded
17588            ver.forceCurrent();
17589
17590            // can downgrade to reader
17591            // Persist settings
17592            mSettings.writeLPr();
17593        }
17594        // Send a broadcast to let everyone know we are done processing
17595        if (pkgList.size() > 0) {
17596            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17597        }
17598    }
17599
17600   /*
17601     * Utility method to unload a list of specified containers
17602     */
17603    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17604        // Just unmount all valid containers.
17605        for (AsecInstallArgs arg : cidArgs) {
17606            synchronized (mInstallLock) {
17607                arg.doPostDeleteLI(false);
17608           }
17609       }
17610   }
17611
17612    /*
17613     * Unload packages mounted on external media. This involves deleting package
17614     * data from internal structures, sending broadcasts about disabled packages,
17615     * gc'ing to free up references, unmounting all secure containers
17616     * corresponding to packages on external media, and posting a
17617     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17618     * that we always have to post this message if status has been requested no
17619     * matter what.
17620     */
17621    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17622            final boolean reportStatus) {
17623        if (DEBUG_SD_INSTALL)
17624            Log.i(TAG, "unloading media packages");
17625        ArrayList<String> pkgList = new ArrayList<String>();
17626        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17627        final Set<AsecInstallArgs> keys = processCids.keySet();
17628        for (AsecInstallArgs args : keys) {
17629            String pkgName = args.getPackageName();
17630            if (DEBUG_SD_INSTALL)
17631                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17632            // Delete package internally
17633            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17634            synchronized (mInstallLock) {
17635                boolean res = deletePackageLI(pkgName, null, false, null,
17636                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17637                if (res) {
17638                    pkgList.add(pkgName);
17639                } else {
17640                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17641                    failedList.add(args);
17642                }
17643            }
17644        }
17645
17646        // reader
17647        synchronized (mPackages) {
17648            // We didn't update the settings after removing each package;
17649            // write them now for all packages.
17650            mSettings.writeLPr();
17651        }
17652
17653        // We have to absolutely send UPDATED_MEDIA_STATUS only
17654        // after confirming that all the receivers processed the ordered
17655        // broadcast when packages get disabled, force a gc to clean things up.
17656        // and unload all the containers.
17657        if (pkgList.size() > 0) {
17658            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17659                    new IIntentReceiver.Stub() {
17660                public void performReceive(Intent intent, int resultCode, String data,
17661                        Bundle extras, boolean ordered, boolean sticky,
17662                        int sendingUser) throws RemoteException {
17663                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17664                            reportStatus ? 1 : 0, 1, keys);
17665                    mHandler.sendMessage(msg);
17666                }
17667            });
17668        } else {
17669            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17670                    keys);
17671            mHandler.sendMessage(msg);
17672        }
17673    }
17674
17675    private void loadPrivatePackages(final VolumeInfo vol) {
17676        mHandler.post(new Runnable() {
17677            @Override
17678            public void run() {
17679                loadPrivatePackagesInner(vol);
17680            }
17681        });
17682    }
17683
17684    private void loadPrivatePackagesInner(VolumeInfo vol) {
17685        final String volumeUuid = vol.fsUuid;
17686        if (TextUtils.isEmpty(volumeUuid)) {
17687            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17688            return;
17689        }
17690
17691        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17692        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17693
17694        final VersionInfo ver;
17695        final List<PackageSetting> packages;
17696        synchronized (mPackages) {
17697            ver = mSettings.findOrCreateVersion(volumeUuid);
17698            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17699        }
17700
17701        // TODO: introduce a new concept similar to "frozen" to prevent these
17702        // apps from being launched until after data has been fully reconciled
17703        for (PackageSetting ps : packages) {
17704            synchronized (mInstallLock) {
17705                final PackageParser.Package pkg;
17706                try {
17707                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17708                    loaded.add(pkg.applicationInfo);
17709
17710                } catch (PackageManagerException e) {
17711                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17712                }
17713
17714                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17715                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17716                }
17717            }
17718        }
17719
17720        // Reconcile app data for all started/unlocked users
17721        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17722        final UserManager um = mContext.getSystemService(UserManager.class);
17723        for (UserInfo user : um.getUsers()) {
17724            final int flags;
17725            if (um.isUserUnlocked(user.id)) {
17726                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17727            } else if (um.isUserRunning(user.id)) {
17728                flags = StorageManager.FLAG_STORAGE_DE;
17729            } else {
17730                continue;
17731            }
17732
17733            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17734            reconcileAppsData(volumeUuid, user.id, flags);
17735        }
17736
17737        synchronized (mPackages) {
17738            int updateFlags = UPDATE_PERMISSIONS_ALL;
17739            if (ver.sdkVersion != mSdkVersion) {
17740                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17741                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17742                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17743            }
17744            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17745
17746            // Yay, everything is now upgraded
17747            ver.forceCurrent();
17748
17749            mSettings.writeLPr();
17750        }
17751
17752        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17753        sendResourcesChangedBroadcast(true, false, loaded, null);
17754    }
17755
17756    private void unloadPrivatePackages(final VolumeInfo vol) {
17757        mHandler.post(new Runnable() {
17758            @Override
17759            public void run() {
17760                unloadPrivatePackagesInner(vol);
17761            }
17762        });
17763    }
17764
17765    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17766        final String volumeUuid = vol.fsUuid;
17767        if (TextUtils.isEmpty(volumeUuid)) {
17768            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17769            return;
17770        }
17771
17772        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17773        synchronized (mInstallLock) {
17774        synchronized (mPackages) {
17775            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17776            for (PackageSetting ps : packages) {
17777                if (ps.pkg == null) continue;
17778
17779                final ApplicationInfo info = ps.pkg.applicationInfo;
17780                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17781                if (deletePackageLI(ps.name, null, false, null,
17782                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17783                    unloaded.add(info);
17784                } else {
17785                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17786                }
17787            }
17788
17789            mSettings.writeLPr();
17790        }
17791        }
17792
17793        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17794        sendResourcesChangedBroadcast(false, false, unloaded, null);
17795    }
17796
17797    /**
17798     * Examine all users present on given mounted volume, and destroy data
17799     * belonging to users that are no longer valid, or whose user ID has been
17800     * recycled.
17801     */
17802    private void reconcileUsers(String volumeUuid) {
17803        // TODO: also reconcile DE directories
17804        final File[] files = FileUtils
17805                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17806        for (File file : files) {
17807            if (!file.isDirectory()) continue;
17808
17809            final int userId;
17810            final UserInfo info;
17811            try {
17812                userId = Integer.parseInt(file.getName());
17813                info = sUserManager.getUserInfo(userId);
17814            } catch (NumberFormatException e) {
17815                Slog.w(TAG, "Invalid user directory " + file);
17816                continue;
17817            }
17818
17819            boolean destroyUser = false;
17820            if (info == null) {
17821                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17822                        + " because no matching user was found");
17823                destroyUser = true;
17824            } else {
17825                try {
17826                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17827                } catch (IOException e) {
17828                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17829                            + " because we failed to enforce serial number: " + e);
17830                    destroyUser = true;
17831                }
17832            }
17833
17834            if (destroyUser) {
17835                synchronized (mInstallLock) {
17836                    try {
17837                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17838                    } catch (InstallerException e) {
17839                        Slog.w(TAG, "Failed to clean up user dirs", e);
17840                    }
17841                }
17842            }
17843        }
17844    }
17845
17846    private void assertPackageKnown(String volumeUuid, String packageName)
17847            throws PackageManagerException {
17848        synchronized (mPackages) {
17849            final PackageSetting ps = mSettings.mPackages.get(packageName);
17850            if (ps == null) {
17851                throw new PackageManagerException("Package " + packageName + " is unknown");
17852            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17853                throw new PackageManagerException(
17854                        "Package " + packageName + " found on unknown volume " + volumeUuid
17855                                + "; expected volume " + ps.volumeUuid);
17856            }
17857        }
17858    }
17859
17860    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17861            throws PackageManagerException {
17862        synchronized (mPackages) {
17863            final PackageSetting ps = mSettings.mPackages.get(packageName);
17864            if (ps == null) {
17865                throw new PackageManagerException("Package " + packageName + " is unknown");
17866            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17867                throw new PackageManagerException(
17868                        "Package " + packageName + " found on unknown volume " + volumeUuid
17869                                + "; expected volume " + ps.volumeUuid);
17870            } else if (!ps.getInstalled(userId)) {
17871                throw new PackageManagerException(
17872                        "Package " + packageName + " not installed for user " + userId);
17873            }
17874        }
17875    }
17876
17877    /**
17878     * Examine all apps present on given mounted volume, and destroy apps that
17879     * aren't expected, either due to uninstallation or reinstallation on
17880     * another volume.
17881     */
17882    private void reconcileApps(String volumeUuid) {
17883        final File[] files = FileUtils
17884                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17885        for (File file : files) {
17886            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17887                    && !PackageInstallerService.isStageName(file.getName());
17888            if (!isPackage) {
17889                // Ignore entries which are not packages
17890                continue;
17891            }
17892
17893            try {
17894                final PackageLite pkg = PackageParser.parsePackageLite(file,
17895                        PackageParser.PARSE_MUST_BE_APK);
17896                assertPackageKnown(volumeUuid, pkg.packageName);
17897
17898            } catch (PackageParserException | PackageManagerException e) {
17899                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17900                synchronized (mInstallLock) {
17901                    removeCodePathLI(file);
17902                }
17903            }
17904        }
17905    }
17906
17907    /**
17908     * Reconcile all app data for the given user.
17909     * <p>
17910     * Verifies that directories exist and that ownership and labeling is
17911     * correct for all installed apps on all mounted volumes.
17912     */
17913    void reconcileAppsData(int userId, int flags) {
17914        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17915        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17916            final String volumeUuid = vol.getFsUuid();
17917            reconcileAppsData(volumeUuid, userId, flags);
17918        }
17919    }
17920
17921    /**
17922     * Reconcile all app data on given mounted volume.
17923     * <p>
17924     * Destroys app data that isn't expected, either due to uninstallation or
17925     * reinstallation on another volume.
17926     * <p>
17927     * Verifies that directories exist and that ownership and labeling is
17928     * correct for all installed apps.
17929     */
17930    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17931        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17932                + Integer.toHexString(flags));
17933
17934        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17935        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17936
17937        boolean restoreconNeeded = false;
17938
17939        // First look for stale data that doesn't belong, and check if things
17940        // have changed since we did our last restorecon
17941        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17942            if (!isUserKeyUnlocked(userId)) {
17943                throw new RuntimeException(
17944                        "Yikes, someone asked us to reconcile CE storage while " + userId
17945                                + " was still locked; this would have caused massive data loss!");
17946            }
17947
17948            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17949
17950            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17951            for (File file : files) {
17952                final String packageName = file.getName();
17953                try {
17954                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17955                } catch (PackageManagerException e) {
17956                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17957                    synchronized (mInstallLock) {
17958                        destroyAppDataLI(volumeUuid, packageName, userId,
17959                                StorageManager.FLAG_STORAGE_CE);
17960                    }
17961                }
17962            }
17963        }
17964        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17965            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17966
17967            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17968            for (File file : files) {
17969                final String packageName = file.getName();
17970                try {
17971                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17972                } catch (PackageManagerException e) {
17973                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17974                    synchronized (mInstallLock) {
17975                        destroyAppDataLI(volumeUuid, packageName, userId,
17976                                StorageManager.FLAG_STORAGE_DE);
17977                    }
17978                }
17979            }
17980        }
17981
17982        // Ensure that data directories are ready to roll for all packages
17983        // installed for this volume and user
17984        final List<PackageSetting> packages;
17985        synchronized (mPackages) {
17986            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17987        }
17988        int preparedCount = 0;
17989        for (PackageSetting ps : packages) {
17990            final String packageName = ps.name;
17991            if (ps.pkg == null) {
17992                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17993                // TODO: might be due to legacy ASEC apps; we should circle back
17994                // and reconcile again once they're scanned
17995                continue;
17996            }
17997
17998            if (ps.getInstalled(userId)) {
17999                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18000
18001                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18002                    // We may have just shuffled around app data directories, so
18003                    // prepare them one more time
18004                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18005                }
18006
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     * <p>
18034     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18035     */
18036    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18037        prepareAppDataAfterInstallInternal(pkg);
18038        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18039        for (int i = 0; i < childCount; i++) {
18040            PackageParser.Package childPackage = pkg.childPackages.get(i);
18041            prepareAppDataAfterInstallInternal(childPackage);
18042        }
18043    }
18044
18045    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18046        final PackageSetting ps;
18047        synchronized (mPackages) {
18048            ps = mSettings.mPackages.get(pkg.packageName);
18049            mSettings.writeKernelMappingLPr(ps);
18050        }
18051
18052        final UserManager um = mContext.getSystemService(UserManager.class);
18053        for (UserInfo user : um.getUsers()) {
18054            final int flags;
18055            if (um.isUserUnlocked(user.id)) {
18056                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18057            } else if (um.isUserRunning(user.id)) {
18058                flags = StorageManager.FLAG_STORAGE_DE;
18059            } else {
18060                continue;
18061            }
18062
18063            if (ps.getInstalled(user.id)) {
18064                // Whenever an app changes, force a restorecon of its data
18065                // TODO: when user data is locked, mark that we're still dirty
18066                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18067            }
18068        }
18069    }
18070
18071    /**
18072     * Prepare app data for the given app.
18073     * <p>
18074     * Verifies that directories exist and that ownership and labeling is
18075     * correct for all installed apps. If there is an ownership mismatch, this
18076     * will try recovering system apps by wiping data; third-party app data is
18077     * left intact.
18078     */
18079    private void prepareAppData(String volumeUuid, int userId, int flags,
18080            PackageParser.Package pkg, boolean restoreconNeeded) {
18081        if (DEBUG_APP_DATA) {
18082            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18083                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18084        }
18085
18086        final String packageName = pkg.packageName;
18087        final ApplicationInfo app = pkg.applicationInfo;
18088        final int appId = UserHandle.getAppId(app.uid);
18089
18090        Preconditions.checkNotNull(app.seinfo);
18091
18092        synchronized (mInstallLock) {
18093            try {
18094                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18095                        appId, app.seinfo, app.targetSdkVersion);
18096            } catch (InstallerException e) {
18097                if (app.isSystemApp()) {
18098                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18099                            + ", but trying to recover: " + e);
18100                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18101                    try {
18102                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18103                                appId, app.seinfo, app.targetSdkVersion);
18104                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18105                    } catch (InstallerException e2) {
18106                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18107                    }
18108                } else {
18109                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18110                }
18111            }
18112
18113            if (restoreconNeeded) {
18114                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18115            }
18116
18117            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18118                // Create a native library symlink only if we have native libraries
18119                // and if the native libraries are 32 bit libraries. We do not provide
18120                // this symlink for 64 bit libraries.
18121                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18122                    final String nativeLibPath = app.nativeLibraryDir;
18123                    try {
18124                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18125                                nativeLibPath, userId);
18126                    } catch (InstallerException e) {
18127                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18128                    }
18129                }
18130            }
18131        }
18132    }
18133
18134    /**
18135     * For system apps on non-FBE devices, this method migrates any existing
18136     * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by
18137     * the app.
18138     */
18139    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18140        if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled()
18141                && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
18142            final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted()
18143                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18144            synchronized (mInstallLock) {
18145                try {
18146                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18147                } catch (InstallerException e) {
18148                    logCriticalInfo(Log.WARN,
18149                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18150                }
18151            }
18152            return true;
18153        } else {
18154            return false;
18155        }
18156    }
18157
18158    private void unfreezePackage(String packageName) {
18159        synchronized (mPackages) {
18160            final PackageSetting ps = mSettings.mPackages.get(packageName);
18161            if (ps != null) {
18162                ps.frozen = false;
18163            }
18164        }
18165    }
18166
18167    @Override
18168    public int movePackage(final String packageName, final String volumeUuid) {
18169        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18170
18171        final int moveId = mNextMoveId.getAndIncrement();
18172        mHandler.post(new Runnable() {
18173            @Override
18174            public void run() {
18175                try {
18176                    movePackageInternal(packageName, volumeUuid, moveId);
18177                } catch (PackageManagerException e) {
18178                    Slog.w(TAG, "Failed to move " + packageName, e);
18179                    mMoveCallbacks.notifyStatusChanged(moveId,
18180                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18181                }
18182            }
18183        });
18184        return moveId;
18185    }
18186
18187    private void movePackageInternal(final String packageName, final String volumeUuid,
18188            final int moveId) throws PackageManagerException {
18189        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18190        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18191        final PackageManager pm = mContext.getPackageManager();
18192
18193        final boolean currentAsec;
18194        final String currentVolumeUuid;
18195        final File codeFile;
18196        final String installerPackageName;
18197        final String packageAbiOverride;
18198        final int appId;
18199        final String seinfo;
18200        final String label;
18201        final int targetSdkVersion;
18202
18203        // reader
18204        synchronized (mPackages) {
18205            final PackageParser.Package pkg = mPackages.get(packageName);
18206            final PackageSetting ps = mSettings.mPackages.get(packageName);
18207            if (pkg == null || ps == null) {
18208                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18209            }
18210
18211            if (pkg.applicationInfo.isSystemApp()) {
18212                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18213                        "Cannot move system application");
18214            }
18215
18216            if (pkg.applicationInfo.isExternalAsec()) {
18217                currentAsec = true;
18218                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18219            } else if (pkg.applicationInfo.isForwardLocked()) {
18220                currentAsec = true;
18221                currentVolumeUuid = "forward_locked";
18222            } else {
18223                currentAsec = false;
18224                currentVolumeUuid = ps.volumeUuid;
18225
18226                final File probe = new File(pkg.codePath);
18227                final File probeOat = new File(probe, "oat");
18228                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18229                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18230                            "Move only supported for modern cluster style installs");
18231                }
18232            }
18233
18234            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18235                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18236                        "Package already moved to " + volumeUuid);
18237            }
18238            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18239                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18240                        "Device admin cannot be moved");
18241            }
18242
18243            if (ps.frozen) {
18244                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18245                        "Failed to move already frozen package");
18246            }
18247            ps.frozen = true;
18248
18249            codeFile = new File(pkg.codePath);
18250            installerPackageName = ps.installerPackageName;
18251            packageAbiOverride = ps.cpuAbiOverrideString;
18252            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18253            seinfo = pkg.applicationInfo.seinfo;
18254            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18255            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18256        }
18257
18258        // Now that we're guarded by frozen state, kill app during move
18259        final long token = Binder.clearCallingIdentity();
18260        try {
18261            killApplication(packageName, appId, "move pkg");
18262        } finally {
18263            Binder.restoreCallingIdentity(token);
18264        }
18265
18266        final Bundle extras = new Bundle();
18267        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18268        extras.putString(Intent.EXTRA_TITLE, label);
18269        mMoveCallbacks.notifyCreated(moveId, extras);
18270
18271        int installFlags;
18272        final boolean moveCompleteApp;
18273        final File measurePath;
18274
18275        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18276            installFlags = INSTALL_INTERNAL;
18277            moveCompleteApp = !currentAsec;
18278            measurePath = Environment.getDataAppDirectory(volumeUuid);
18279        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18280            installFlags = INSTALL_EXTERNAL;
18281            moveCompleteApp = false;
18282            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18283        } else {
18284            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18285            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18286                    || !volume.isMountedWritable()) {
18287                unfreezePackage(packageName);
18288                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18289                        "Move location not mounted private volume");
18290            }
18291
18292            Preconditions.checkState(!currentAsec);
18293
18294            installFlags = INSTALL_INTERNAL;
18295            moveCompleteApp = true;
18296            measurePath = Environment.getDataAppDirectory(volumeUuid);
18297        }
18298
18299        final PackageStats stats = new PackageStats(null, -1);
18300        synchronized (mInstaller) {
18301            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18302                unfreezePackage(packageName);
18303                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18304                        "Failed to measure package size");
18305            }
18306        }
18307
18308        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18309                + stats.dataSize);
18310
18311        final long startFreeBytes = measurePath.getFreeSpace();
18312        final long sizeBytes;
18313        if (moveCompleteApp) {
18314            sizeBytes = stats.codeSize + stats.dataSize;
18315        } else {
18316            sizeBytes = stats.codeSize;
18317        }
18318
18319        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18320            unfreezePackage(packageName);
18321            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18322                    "Not enough free space to move");
18323        }
18324
18325        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18326
18327        final CountDownLatch installedLatch = new CountDownLatch(1);
18328        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18329            @Override
18330            public void onUserActionRequired(Intent intent) throws RemoteException {
18331                throw new IllegalStateException();
18332            }
18333
18334            @Override
18335            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18336                    Bundle extras) throws RemoteException {
18337                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18338                        + PackageManager.installStatusToString(returnCode, msg));
18339
18340                installedLatch.countDown();
18341
18342                // Regardless of success or failure of the move operation,
18343                // always unfreeze the package
18344                unfreezePackage(packageName);
18345
18346                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18347                switch (status) {
18348                    case PackageInstaller.STATUS_SUCCESS:
18349                        mMoveCallbacks.notifyStatusChanged(moveId,
18350                                PackageManager.MOVE_SUCCEEDED);
18351                        break;
18352                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18353                        mMoveCallbacks.notifyStatusChanged(moveId,
18354                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18355                        break;
18356                    default:
18357                        mMoveCallbacks.notifyStatusChanged(moveId,
18358                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18359                        break;
18360                }
18361            }
18362        };
18363
18364        final MoveInfo move;
18365        if (moveCompleteApp) {
18366            // Kick off a thread to report progress estimates
18367            new Thread() {
18368                @Override
18369                public void run() {
18370                    while (true) {
18371                        try {
18372                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18373                                break;
18374                            }
18375                        } catch (InterruptedException ignored) {
18376                        }
18377
18378                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18379                        final int progress = 10 + (int) MathUtils.constrain(
18380                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18381                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18382                    }
18383                }
18384            }.start();
18385
18386            final String dataAppName = codeFile.getName();
18387            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18388                    dataAppName, appId, seinfo, targetSdkVersion);
18389        } else {
18390            move = null;
18391        }
18392
18393        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18394
18395        final Message msg = mHandler.obtainMessage(INIT_COPY);
18396        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18397        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18398                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18399                packageAbiOverride, null);
18400        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18401        msg.obj = params;
18402
18403        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18404                System.identityHashCode(msg.obj));
18405        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18406                System.identityHashCode(msg.obj));
18407
18408        mHandler.sendMessage(msg);
18409    }
18410
18411    @Override
18412    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18413        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18414
18415        final int realMoveId = mNextMoveId.getAndIncrement();
18416        final Bundle extras = new Bundle();
18417        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18418        mMoveCallbacks.notifyCreated(realMoveId, extras);
18419
18420        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18421            @Override
18422            public void onCreated(int moveId, Bundle extras) {
18423                // Ignored
18424            }
18425
18426            @Override
18427            public void onStatusChanged(int moveId, int status, long estMillis) {
18428                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18429            }
18430        };
18431
18432        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18433        storage.setPrimaryStorageUuid(volumeUuid, callback);
18434        return realMoveId;
18435    }
18436
18437    @Override
18438    public int getMoveStatus(int moveId) {
18439        mContext.enforceCallingOrSelfPermission(
18440                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18441        return mMoveCallbacks.mLastStatus.get(moveId);
18442    }
18443
18444    @Override
18445    public void registerMoveCallback(IPackageMoveObserver callback) {
18446        mContext.enforceCallingOrSelfPermission(
18447                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18448        mMoveCallbacks.register(callback);
18449    }
18450
18451    @Override
18452    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18453        mContext.enforceCallingOrSelfPermission(
18454                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18455        mMoveCallbacks.unregister(callback);
18456    }
18457
18458    @Override
18459    public boolean setInstallLocation(int loc) {
18460        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18461                null);
18462        if (getInstallLocation() == loc) {
18463            return true;
18464        }
18465        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18466                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18467            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18468                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18469            return true;
18470        }
18471        return false;
18472   }
18473
18474    @Override
18475    public int getInstallLocation() {
18476        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18477                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18478                PackageHelper.APP_INSTALL_AUTO);
18479    }
18480
18481    /** Called by UserManagerService */
18482    void cleanUpUser(UserManagerService userManager, int userHandle) {
18483        synchronized (mPackages) {
18484            mDirtyUsers.remove(userHandle);
18485            mUserNeedsBadging.delete(userHandle);
18486            mSettings.removeUserLPw(userHandle);
18487            mPendingBroadcasts.remove(userHandle);
18488            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18489        }
18490        synchronized (mInstallLock) {
18491            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18492            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18493                final String volumeUuid = vol.getFsUuid();
18494                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18495                try {
18496                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18497                } catch (InstallerException e) {
18498                    Slog.w(TAG, "Failed to remove user data", e);
18499                }
18500            }
18501            synchronized (mPackages) {
18502                removeUnusedPackagesLILPw(userManager, userHandle);
18503            }
18504        }
18505    }
18506
18507    /**
18508     * We're removing userHandle and would like to remove any downloaded packages
18509     * that are no longer in use by any other user.
18510     * @param userHandle the user being removed
18511     */
18512    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18513        final boolean DEBUG_CLEAN_APKS = false;
18514        int [] users = userManager.getUserIds();
18515        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18516        while (psit.hasNext()) {
18517            PackageSetting ps = psit.next();
18518            if (ps.pkg == null) {
18519                continue;
18520            }
18521            final String packageName = ps.pkg.packageName;
18522            // Skip over if system app
18523            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18524                continue;
18525            }
18526            if (DEBUG_CLEAN_APKS) {
18527                Slog.i(TAG, "Checking package " + packageName);
18528            }
18529            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18530            if (keep) {
18531                if (DEBUG_CLEAN_APKS) {
18532                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18533                }
18534            } else {
18535                for (int i = 0; i < users.length; i++) {
18536                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18537                        keep = true;
18538                        if (DEBUG_CLEAN_APKS) {
18539                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18540                                    + users[i]);
18541                        }
18542                        break;
18543                    }
18544                }
18545            }
18546            if (!keep) {
18547                if (DEBUG_CLEAN_APKS) {
18548                    Slog.i(TAG, "  Removing package " + packageName);
18549                }
18550                mHandler.post(new Runnable() {
18551                    public void run() {
18552                        deletePackageX(packageName, userHandle, 0);
18553                    } //end run
18554                });
18555            }
18556        }
18557    }
18558
18559    /** Called by UserManagerService */
18560    void createNewUser(int userHandle) {
18561        synchronized (mInstallLock) {
18562            try {
18563                mInstaller.createUserConfig(userHandle);
18564            } catch (InstallerException e) {
18565                Slog.w(TAG, "Failed to create user config", e);
18566            }
18567            mSettings.createNewUserLI(this, mInstaller, userHandle);
18568        }
18569        synchronized (mPackages) {
18570            applyFactoryDefaultBrowserLPw(userHandle);
18571            primeDomainVerificationsLPw(userHandle);
18572        }
18573    }
18574
18575    void newUserCreated(final int userHandle) {
18576        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18577        // If permission review for legacy apps is required, we represent
18578        // dagerous permissions for such apps as always granted runtime
18579        // permissions to keep per user flag state whether review is needed.
18580        // Hence, if a new user is added we have to propagate dangerous
18581        // permission grants for these legacy apps.
18582        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18583            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18584                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18585        }
18586    }
18587
18588    @Override
18589    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18590        mContext.enforceCallingOrSelfPermission(
18591                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18592                "Only package verification agents can read the verifier device identity");
18593
18594        synchronized (mPackages) {
18595            return mSettings.getVerifierDeviceIdentityLPw();
18596        }
18597    }
18598
18599    @Override
18600    public void setPermissionEnforced(String permission, boolean enforced) {
18601        // TODO: Now that we no longer change GID for storage, this should to away.
18602        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18603                "setPermissionEnforced");
18604        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18605            synchronized (mPackages) {
18606                if (mSettings.mReadExternalStorageEnforced == null
18607                        || mSettings.mReadExternalStorageEnforced != enforced) {
18608                    mSettings.mReadExternalStorageEnforced = enforced;
18609                    mSettings.writeLPr();
18610                }
18611            }
18612            // kill any non-foreground processes so we restart them and
18613            // grant/revoke the GID.
18614            final IActivityManager am = ActivityManagerNative.getDefault();
18615            if (am != null) {
18616                final long token = Binder.clearCallingIdentity();
18617                try {
18618                    am.killProcessesBelowForeground("setPermissionEnforcement");
18619                } catch (RemoteException e) {
18620                } finally {
18621                    Binder.restoreCallingIdentity(token);
18622                }
18623            }
18624        } else {
18625            throw new IllegalArgumentException("No selective enforcement for " + permission);
18626        }
18627    }
18628
18629    @Override
18630    @Deprecated
18631    public boolean isPermissionEnforced(String permission) {
18632        return true;
18633    }
18634
18635    @Override
18636    public boolean isStorageLow() {
18637        final long token = Binder.clearCallingIdentity();
18638        try {
18639            final DeviceStorageMonitorInternal
18640                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18641            if (dsm != null) {
18642                return dsm.isMemoryLow();
18643            } else {
18644                return false;
18645            }
18646        } finally {
18647            Binder.restoreCallingIdentity(token);
18648        }
18649    }
18650
18651    @Override
18652    public IPackageInstaller getPackageInstaller() {
18653        return mInstallerService;
18654    }
18655
18656    private boolean userNeedsBadging(int userId) {
18657        int index = mUserNeedsBadging.indexOfKey(userId);
18658        if (index < 0) {
18659            final UserInfo userInfo;
18660            final long token = Binder.clearCallingIdentity();
18661            try {
18662                userInfo = sUserManager.getUserInfo(userId);
18663            } finally {
18664                Binder.restoreCallingIdentity(token);
18665            }
18666            final boolean b;
18667            if (userInfo != null && userInfo.isManagedProfile()) {
18668                b = true;
18669            } else {
18670                b = false;
18671            }
18672            mUserNeedsBadging.put(userId, b);
18673            return b;
18674        }
18675        return mUserNeedsBadging.valueAt(index);
18676    }
18677
18678    @Override
18679    public KeySet getKeySetByAlias(String packageName, String alias) {
18680        if (packageName == null || alias == null) {
18681            return null;
18682        }
18683        synchronized(mPackages) {
18684            final PackageParser.Package pkg = mPackages.get(packageName);
18685            if (pkg == null) {
18686                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18687                throw new IllegalArgumentException("Unknown package: " + packageName);
18688            }
18689            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18690            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18691        }
18692    }
18693
18694    @Override
18695    public KeySet getSigningKeySet(String packageName) {
18696        if (packageName == null) {
18697            return null;
18698        }
18699        synchronized(mPackages) {
18700            final PackageParser.Package pkg = mPackages.get(packageName);
18701            if (pkg == null) {
18702                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18703                throw new IllegalArgumentException("Unknown package: " + packageName);
18704            }
18705            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18706                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18707                throw new SecurityException("May not access signing KeySet of other apps.");
18708            }
18709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18710            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18711        }
18712    }
18713
18714    @Override
18715    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18716        if (packageName == null || ks == null) {
18717            return false;
18718        }
18719        synchronized(mPackages) {
18720            final PackageParser.Package pkg = mPackages.get(packageName);
18721            if (pkg == null) {
18722                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18723                throw new IllegalArgumentException("Unknown package: " + packageName);
18724            }
18725            IBinder ksh = ks.getToken();
18726            if (ksh instanceof KeySetHandle) {
18727                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18728                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18729            }
18730            return false;
18731        }
18732    }
18733
18734    @Override
18735    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18736        if (packageName == null || ks == null) {
18737            return false;
18738        }
18739        synchronized(mPackages) {
18740            final PackageParser.Package pkg = mPackages.get(packageName);
18741            if (pkg == null) {
18742                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18743                throw new IllegalArgumentException("Unknown package: " + packageName);
18744            }
18745            IBinder ksh = ks.getToken();
18746            if (ksh instanceof KeySetHandle) {
18747                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18748                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18749            }
18750            return false;
18751        }
18752    }
18753
18754    private void deletePackageIfUnusedLPr(final String packageName) {
18755        PackageSetting ps = mSettings.mPackages.get(packageName);
18756        if (ps == null) {
18757            return;
18758        }
18759        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18760            // TODO Implement atomic delete if package is unused
18761            // It is currently possible that the package will be deleted even if it is installed
18762            // after this method returns.
18763            mHandler.post(new Runnable() {
18764                public void run() {
18765                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18766                }
18767            });
18768        }
18769    }
18770
18771    /**
18772     * Check and throw if the given before/after packages would be considered a
18773     * downgrade.
18774     */
18775    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18776            throws PackageManagerException {
18777        if (after.versionCode < before.mVersionCode) {
18778            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18779                    "Update version code " + after.versionCode + " is older than current "
18780                    + before.mVersionCode);
18781        } else if (after.versionCode == before.mVersionCode) {
18782            if (after.baseRevisionCode < before.baseRevisionCode) {
18783                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18784                        "Update base revision code " + after.baseRevisionCode
18785                        + " is older than current " + before.baseRevisionCode);
18786            }
18787
18788            if (!ArrayUtils.isEmpty(after.splitNames)) {
18789                for (int i = 0; i < after.splitNames.length; i++) {
18790                    final String splitName = after.splitNames[i];
18791                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18792                    if (j != -1) {
18793                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18794                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18795                                    "Update split " + splitName + " revision code "
18796                                    + after.splitRevisionCodes[i] + " is older than current "
18797                                    + before.splitRevisionCodes[j]);
18798                        }
18799                    }
18800                }
18801            }
18802        }
18803    }
18804
18805    private static class MoveCallbacks extends Handler {
18806        private static final int MSG_CREATED = 1;
18807        private static final int MSG_STATUS_CHANGED = 2;
18808
18809        private final RemoteCallbackList<IPackageMoveObserver>
18810                mCallbacks = new RemoteCallbackList<>();
18811
18812        private final SparseIntArray mLastStatus = new SparseIntArray();
18813
18814        public MoveCallbacks(Looper looper) {
18815            super(looper);
18816        }
18817
18818        public void register(IPackageMoveObserver callback) {
18819            mCallbacks.register(callback);
18820        }
18821
18822        public void unregister(IPackageMoveObserver callback) {
18823            mCallbacks.unregister(callback);
18824        }
18825
18826        @Override
18827        public void handleMessage(Message msg) {
18828            final SomeArgs args = (SomeArgs) msg.obj;
18829            final int n = mCallbacks.beginBroadcast();
18830            for (int i = 0; i < n; i++) {
18831                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18832                try {
18833                    invokeCallback(callback, msg.what, args);
18834                } catch (RemoteException ignored) {
18835                }
18836            }
18837            mCallbacks.finishBroadcast();
18838            args.recycle();
18839        }
18840
18841        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18842                throws RemoteException {
18843            switch (what) {
18844                case MSG_CREATED: {
18845                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18846                    break;
18847                }
18848                case MSG_STATUS_CHANGED: {
18849                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18850                    break;
18851                }
18852            }
18853        }
18854
18855        private void notifyCreated(int moveId, Bundle extras) {
18856            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18857
18858            final SomeArgs args = SomeArgs.obtain();
18859            args.argi1 = moveId;
18860            args.arg2 = extras;
18861            obtainMessage(MSG_CREATED, args).sendToTarget();
18862        }
18863
18864        private void notifyStatusChanged(int moveId, int status) {
18865            notifyStatusChanged(moveId, status, -1);
18866        }
18867
18868        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18869            Slog.v(TAG, "Move " + moveId + " status " + status);
18870
18871            final SomeArgs args = SomeArgs.obtain();
18872            args.argi1 = moveId;
18873            args.argi2 = status;
18874            args.arg3 = estMillis;
18875            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18876
18877            synchronized (mLastStatus) {
18878                mLastStatus.put(moveId, status);
18879            }
18880        }
18881    }
18882
18883    private final static class OnPermissionChangeListeners extends Handler {
18884        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18885
18886        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18887                new RemoteCallbackList<>();
18888
18889        public OnPermissionChangeListeners(Looper looper) {
18890            super(looper);
18891        }
18892
18893        @Override
18894        public void handleMessage(Message msg) {
18895            switch (msg.what) {
18896                case MSG_ON_PERMISSIONS_CHANGED: {
18897                    final int uid = msg.arg1;
18898                    handleOnPermissionsChanged(uid);
18899                } break;
18900            }
18901        }
18902
18903        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18904            mPermissionListeners.register(listener);
18905
18906        }
18907
18908        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18909            mPermissionListeners.unregister(listener);
18910        }
18911
18912        public void onPermissionsChanged(int uid) {
18913            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18914                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18915            }
18916        }
18917
18918        private void handleOnPermissionsChanged(int uid) {
18919            final int count = mPermissionListeners.beginBroadcast();
18920            try {
18921                for (int i = 0; i < count; i++) {
18922                    IOnPermissionsChangeListener callback = mPermissionListeners
18923                            .getBroadcastItem(i);
18924                    try {
18925                        callback.onPermissionsChanged(uid);
18926                    } catch (RemoteException e) {
18927                        Log.e(TAG, "Permission listener is dead", e);
18928                    }
18929                }
18930            } finally {
18931                mPermissionListeners.finishBroadcast();
18932            }
18933        }
18934    }
18935
18936    private class PackageManagerInternalImpl extends PackageManagerInternal {
18937        @Override
18938        public void setLocationPackagesProvider(PackagesProvider provider) {
18939            synchronized (mPackages) {
18940                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18941            }
18942        }
18943
18944        @Override
18945        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18946            synchronized (mPackages) {
18947                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18948            }
18949        }
18950
18951        @Override
18952        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18953            synchronized (mPackages) {
18954                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18955            }
18956        }
18957
18958        @Override
18959        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18960            synchronized (mPackages) {
18961                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18962            }
18963        }
18964
18965        @Override
18966        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18967            synchronized (mPackages) {
18968                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18969            }
18970        }
18971
18972        @Override
18973        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18974            synchronized (mPackages) {
18975                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18976            }
18977        }
18978
18979        @Override
18980        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18981            synchronized (mPackages) {
18982                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18983                        packageName, userId);
18984            }
18985        }
18986
18987        @Override
18988        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18989            synchronized (mPackages) {
18990                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18991                        packageName, userId);
18992            }
18993        }
18994
18995        @Override
18996        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18997            synchronized (mPackages) {
18998                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18999                        packageName, userId);
19000            }
19001        }
19002
19003        @Override
19004        public void setKeepUninstalledPackages(final List<String> packageList) {
19005            Preconditions.checkNotNull(packageList);
19006            List<String> removedFromList = null;
19007            synchronized (mPackages) {
19008                if (mKeepUninstalledPackages != null) {
19009                    final int packagesCount = mKeepUninstalledPackages.size();
19010                    for (int i = 0; i < packagesCount; i++) {
19011                        String oldPackage = mKeepUninstalledPackages.get(i);
19012                        if (packageList != null && packageList.contains(oldPackage)) {
19013                            continue;
19014                        }
19015                        if (removedFromList == null) {
19016                            removedFromList = new ArrayList<>();
19017                        }
19018                        removedFromList.add(oldPackage);
19019                    }
19020                }
19021                mKeepUninstalledPackages = new ArrayList<>(packageList);
19022                if (removedFromList != null) {
19023                    final int removedCount = removedFromList.size();
19024                    for (int i = 0; i < removedCount; i++) {
19025                        deletePackageIfUnusedLPr(removedFromList.get(i));
19026                    }
19027                }
19028            }
19029        }
19030
19031        @Override
19032        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19033            synchronized (mPackages) {
19034                // If we do not support permission review, done.
19035                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19036                    return false;
19037                }
19038
19039                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19040                if (packageSetting == null) {
19041                    return false;
19042                }
19043
19044                // Permission review applies only to apps not supporting the new permission model.
19045                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19046                    return false;
19047                }
19048
19049                // Legacy apps have the permission and get user consent on launch.
19050                PermissionsState permissionsState = packageSetting.getPermissionsState();
19051                return permissionsState.isPermissionReviewRequired(userId);
19052            }
19053        }
19054    }
19055
19056    @Override
19057    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19058        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19059        synchronized (mPackages) {
19060            final long identity = Binder.clearCallingIdentity();
19061            try {
19062                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19063                        packageNames, userId);
19064            } finally {
19065                Binder.restoreCallingIdentity(identity);
19066            }
19067        }
19068    }
19069
19070    private static void enforceSystemOrPhoneCaller(String tag) {
19071        int callingUid = Binder.getCallingUid();
19072        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19073            throw new SecurityException(
19074                    "Cannot call " + tag + " from UID " + callingUid);
19075        }
19076    }
19077
19078    boolean isHistoricalPackageUsageAvailable() {
19079        return mPackageUsage.isHistoricalPackageUsageAvailable();
19080    }
19081}
19082