PackageManagerService.java revision e06b4d1d9f718b9fe02980fea794a36831a16db2
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
70import static android.content.pm.PackageManager.PERMISSION_DENIED;
71import static android.content.pm.PackageManager.PERMISSION_GRANTED;
72import static android.content.pm.PackageParser.isApkFile;
73import static android.os.Process.PACKAGE_INFO_GID;
74import static android.os.Process.SYSTEM_UID;
75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
76import static android.system.OsConstants.O_CREAT;
77import static android.system.OsConstants.O_RDWR;
78
79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
81import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
82import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
83import static com.android.internal.util.ArrayUtils.appendInt;
84import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
85import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
88import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
89import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
93
94import android.Manifest;
95import android.annotation.NonNull;
96import android.annotation.Nullable;
97import android.app.ActivityManager;
98import android.app.ActivityManagerNative;
99import android.app.AppGlobals;
100import android.app.IActivityManager;
101import android.app.admin.IDevicePolicyManager;
102import android.app.backup.IBackupManager;
103import android.content.BroadcastReceiver;
104import android.content.ComponentName;
105import android.content.Context;
106import android.content.IIntentReceiver;
107import android.content.Intent;
108import android.content.IntentFilter;
109import android.content.IntentSender;
110import android.content.IntentSender.SendIntentException;
111import android.content.ServiceConnection;
112import android.content.pm.ActivityInfo;
113import android.content.pm.ApplicationInfo;
114import android.content.pm.AppsQueryHelper;
115import android.content.pm.ComponentInfo;
116import android.content.pm.EphemeralApplicationInfo;
117import android.content.pm.EphemeralResolveInfo;
118import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
119import android.content.pm.FeatureInfo;
120import android.content.pm.IOnPermissionsChangeListener;
121import android.content.pm.IPackageDataObserver;
122import android.content.pm.IPackageDeleteObserver;
123import android.content.pm.IPackageDeleteObserver2;
124import android.content.pm.IPackageInstallObserver2;
125import android.content.pm.IPackageInstaller;
126import android.content.pm.IPackageManager;
127import android.content.pm.IPackageMoveObserver;
128import android.content.pm.IPackageStatsObserver;
129import android.content.pm.InstrumentationInfo;
130import android.content.pm.IntentFilterVerificationInfo;
131import android.content.pm.KeySet;
132import android.content.pm.PackageCleanItem;
133import android.content.pm.PackageInfo;
134import android.content.pm.PackageInfoLite;
135import android.content.pm.PackageInstaller;
136import android.content.pm.PackageManager;
137import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
138import android.content.pm.PackageManagerInternal;
139import android.content.pm.PackageParser;
140import android.content.pm.PackageParser.ActivityIntentInfo;
141import android.content.pm.PackageParser.PackageLite;
142import android.content.pm.PackageParser.PackageParserException;
143import android.content.pm.PackageStats;
144import android.content.pm.PackageUserState;
145import android.content.pm.ParceledListSlice;
146import android.content.pm.PermissionGroupInfo;
147import android.content.pm.PermissionInfo;
148import android.content.pm.ProviderInfo;
149import android.content.pm.ResolveInfo;
150import android.content.pm.ServiceInfo;
151import android.content.pm.Signature;
152import android.content.pm.UserInfo;
153import android.content.pm.VerificationParams;
154import android.content.pm.VerifierDeviceIdentity;
155import android.content.pm.VerifierInfo;
156import android.content.res.Resources;
157import android.graphics.Bitmap;
158import android.hardware.display.DisplayManager;
159import android.net.Uri;
160import android.os.Binder;
161import android.os.Build;
162import android.os.Bundle;
163import android.os.Debug;
164import android.os.Environment;
165import android.os.Environment.UserEnvironment;
166import android.os.FileUtils;
167import android.os.Handler;
168import android.os.IBinder;
169import android.os.Looper;
170import android.os.Message;
171import android.os.Parcel;
172import android.os.ParcelFileDescriptor;
173import android.os.Process;
174import android.os.RemoteCallbackList;
175import android.os.RemoteException;
176import android.os.ResultReceiver;
177import android.os.SELinux;
178import android.os.ServiceManager;
179import android.os.SystemClock;
180import android.os.SystemProperties;
181import android.os.Trace;
182import android.os.UserHandle;
183import android.os.UserManager;
184import android.os.storage.IMountService;
185import android.os.storage.MountServiceInternal;
186import android.os.storage.StorageEventListener;
187import android.os.storage.StorageManager;
188import android.os.storage.VolumeInfo;
189import android.os.storage.VolumeRecord;
190import android.security.KeyStore;
191import android.security.SystemKeyStore;
192import android.system.ErrnoException;
193import android.system.Os;
194import android.system.StructStat;
195import android.text.TextUtils;
196import android.text.format.DateUtils;
197import android.util.ArrayMap;
198import android.util.ArraySet;
199import android.util.AtomicFile;
200import android.util.DisplayMetrics;
201import android.util.EventLog;
202import android.util.ExceptionUtils;
203import android.util.Log;
204import android.util.LogPrinter;
205import android.util.MathUtils;
206import android.util.PrintStreamPrinter;
207import android.util.Slog;
208import android.util.SparseArray;
209import android.util.SparseBooleanArray;
210import android.util.SparseIntArray;
211import android.util.Xml;
212import android.view.Display;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.SomeArgs;
222import com.android.internal.os.Zygote;
223import com.android.internal.util.ArrayUtils;
224import com.android.internal.util.FastPrintWriter;
225import com.android.internal.util.FastXmlSerializer;
226import com.android.internal.util.IndentingPrintWriter;
227import com.android.internal.util.Preconditions;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.PermissionsState.PermissionState;
236import com.android.server.pm.Settings.DatabaseVersion;
237import com.android.server.pm.Settings.VersionInfo;
238import com.android.server.storage.DeviceStorageMonitorInternal;
239
240import dalvik.system.DexFile;
241import dalvik.system.VMRuntime;
242
243import libcore.io.IoUtils;
244import libcore.util.EmptyArray;
245
246import org.xmlpull.v1.XmlPullParser;
247import org.xmlpull.v1.XmlPullParserException;
248import org.xmlpull.v1.XmlSerializer;
249
250import java.io.BufferedInputStream;
251import java.io.BufferedOutputStream;
252import java.io.BufferedReader;
253import java.io.ByteArrayInputStream;
254import java.io.ByteArrayOutputStream;
255import java.io.File;
256import java.io.FileDescriptor;
257import java.io.FileNotFoundException;
258import java.io.FileOutputStream;
259import java.io.FileReader;
260import java.io.FilenameFilter;
261import java.io.IOException;
262import java.io.InputStream;
263import java.io.PrintWriter;
264import java.nio.charset.StandardCharsets;
265import java.security.MessageDigest;
266import java.security.NoSuchAlgorithmException;
267import java.security.PublicKey;
268import java.security.cert.CertificateEncodingException;
269import java.security.cert.CertificateException;
270import java.text.SimpleDateFormat;
271import java.util.ArrayList;
272import java.util.Arrays;
273import java.util.Collection;
274import java.util.Collections;
275import java.util.Comparator;
276import java.util.Date;
277import java.util.Iterator;
278import java.util.List;
279import java.util.Map;
280import java.util.Objects;
281import java.util.Set;
282import java.util.concurrent.CountDownLatch;
283import java.util.concurrent.TimeUnit;
284import java.util.concurrent.atomic.AtomicBoolean;
285import java.util.concurrent.atomic.AtomicInteger;
286import java.util.concurrent.atomic.AtomicLong;
287
288/**
289 * Keep track of all those .apks everywhere.
290 *
291 * This is very central to the platform's security; please run the unit
292 * tests whenever making modifications here:
293 *
294runtest -c android.content.pm.PackageManagerTests frameworks-core
295 *
296 * {@hide}
297 */
298public class PackageManagerService extends IPackageManager.Stub {
299    static final String TAG = "PackageManager";
300    static final boolean DEBUG_SETTINGS = false;
301    static final boolean DEBUG_PREFERRED = false;
302    static final boolean DEBUG_UPGRADE = false;
303    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
304    private static final boolean DEBUG_BACKUP = false;
305    private static final boolean DEBUG_INSTALL = false;
306    private static final boolean DEBUG_REMOVE = false;
307    private static final boolean DEBUG_BROADCASTS = false;
308    private static final boolean DEBUG_SHOW_INFO = false;
309    private static final boolean DEBUG_PACKAGE_INFO = false;
310    private static final boolean DEBUG_INTENT_MATCHING = false;
311    private static final boolean DEBUG_PACKAGE_SCANNING = false;
312    private static final boolean DEBUG_VERIFY = false;
313    private static final boolean DEBUG_DEXOPT = false;
314    private static final boolean DEBUG_ABI_SELECTION = false;
315    private static final boolean DEBUG_EPHEMERAL = false;
316    private static final boolean DEBUG_TRIAGED_MISSING = false;
317
318    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
319
320    private static final int RADIO_UID = Process.PHONE_UID;
321    private static final int LOG_UID = Process.LOG_UID;
322    private static final int NFC_UID = Process.NFC_UID;
323    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
324    private static final int SHELL_UID = Process.SHELL_UID;
325
326    // Cap the size of permission trees that 3rd party apps can define
327    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
328
329    // Suffix used during package installation when copying/moving
330    // package apks to install directory.
331    private static final String INSTALL_PACKAGE_SUFFIX = "-";
332
333    static final int SCAN_NO_DEX = 1<<1;
334    static final int SCAN_FORCE_DEX = 1<<2;
335    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
336    static final int SCAN_NEW_INSTALL = 1<<4;
337    static final int SCAN_NO_PATHS = 1<<5;
338    static final int SCAN_UPDATE_TIME = 1<<6;
339    static final int SCAN_DEFER_DEX = 1<<7;
340    static final int SCAN_BOOTING = 1<<8;
341    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
342    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
343    static final int SCAN_REPLACING = 1<<11;
344    static final int SCAN_REQUIRE_KNOWN = 1<<12;
345    static final int SCAN_MOVE = 1<<13;
346    static final int SCAN_INITIAL = 1<<14;
347
348    static final int REMOVE_CHATTY = 1<<16;
349
350    private static final int[] EMPTY_INT_ARRAY = new int[0];
351
352    /**
353     * Timeout (in milliseconds) after which the watchdog should declare that
354     * our handler thread is wedged.  The usual default for such things is one
355     * minute but we sometimes do very lengthy I/O operations on this thread,
356     * such as installing multi-gigabyte applications, so ours needs to be longer.
357     */
358    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
359
360    /**
361     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
362     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
363     * settings entry if available, otherwise we use the hardcoded default.  If it's been
364     * more than this long since the last fstrim, we force one during the boot sequence.
365     *
366     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
367     * one gets run at the next available charging+idle time.  This final mandatory
368     * no-fstrim check kicks in only of the other scheduling criteria is never met.
369     */
370    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
371
372    /**
373     * Whether verification is enabled by default.
374     */
375    private static final boolean DEFAULT_VERIFY_ENABLE = true;
376
377    /**
378     * The default maximum time to wait for the verification agent to return in
379     * milliseconds.
380     */
381    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
382
383    /**
384     * The default response for package verification timeout.
385     *
386     * This can be either PackageManager.VERIFICATION_ALLOW or
387     * PackageManager.VERIFICATION_REJECT.
388     */
389    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
390
391    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
392
393    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
394            DEFAULT_CONTAINER_PACKAGE,
395            "com.android.defcontainer.DefaultContainerService");
396
397    private static final String KILL_APP_REASON_GIDS_CHANGED =
398            "permission grant or revoke changed gids";
399
400    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
401            "permissions revoked";
402
403    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
404
405    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
406
407    /** Permission grant: not grant the permission. */
408    private static final int GRANT_DENIED = 1;
409
410    /** Permission grant: grant the permission as an install permission. */
411    private static final int GRANT_INSTALL = 2;
412
413    /** Permission grant: grant the permission as a runtime one. */
414    private static final int GRANT_RUNTIME = 3;
415
416    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
417    private static final int GRANT_UPGRADE = 4;
418
419    /** Canonical intent used to identify what counts as a "web browser" app */
420    private static final Intent sBrowserIntent;
421    static {
422        sBrowserIntent = new Intent();
423        sBrowserIntent.setAction(Intent.ACTION_VIEW);
424        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
425        sBrowserIntent.setData(Uri.parse("http:"));
426    }
427
428    final ServiceThread mHandlerThread;
429
430    final PackageHandler mHandler;
431
432    /**
433     * Messages for {@link #mHandler} that need to wait for system ready before
434     * being dispatched.
435     */
436    private ArrayList<Message> mPostSystemReadyMessages;
437
438    final int mSdkVersion = Build.VERSION.SDK_INT;
439
440    final Context mContext;
441    final boolean mFactoryTest;
442    final boolean mOnlyCore;
443    final DisplayMetrics mMetrics;
444    final int mDefParseFlags;
445    final String[] mSeparateProcesses;
446    final boolean mIsUpgrade;
447
448    /** The location for ASEC container files on internal storage. */
449    final String mAsecInternalPath;
450
451    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
452    // LOCK HELD.  Can be called with mInstallLock held.
453    @GuardedBy("mInstallLock")
454    final Installer mInstaller;
455
456    /** Directory where installed third-party apps stored */
457    final File mAppInstallDir;
458    final File mEphemeralInstallDir;
459
460    /**
461     * Directory to which applications installed internally have their
462     * 32 bit native libraries copied.
463     */
464    private File mAppLib32InstallDir;
465
466    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
467    // apps.
468    final File mDrmAppPrivateInstallDir;
469
470    // ----------------------------------------------------------------
471
472    // Lock for state used when installing and doing other long running
473    // operations.  Methods that must be called with this lock held have
474    // the suffix "LI".
475    final Object mInstallLock = new Object();
476
477    // ----------------------------------------------------------------
478
479    // Keys are String (package name), values are Package.  This also serves
480    // as the lock for the global state.  Methods that must be called with
481    // this lock held have the prefix "LP".
482    @GuardedBy("mPackages")
483    final ArrayMap<String, PackageParser.Package> mPackages =
484            new ArrayMap<String, PackageParser.Package>();
485
486    // Tracks available target package names -> overlay package paths.
487    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
488        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
489
490    /**
491     * Tracks new system packages [received in an OTA] that we expect to
492     * find updated user-installed versions. Keys are package name, values
493     * are package location.
494     */
495    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
496
497    /**
498     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
499     */
500    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
501    /**
502     * Whether or not system app permissions should be promoted from install to runtime.
503     */
504    boolean mPromoteSystemApps;
505
506    final Settings mSettings;
507    boolean mRestoredSettings;
508
509    // System configuration read by SystemConfig.
510    final int[] mGlobalGids;
511    final SparseArray<ArraySet<String>> mSystemPermissions;
512    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
513
514    // If mac_permissions.xml was found for seinfo labeling.
515    boolean mFoundPolicyFile;
516
517    // If a recursive restorecon of /data/data/<pkg> is needed.
518    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
519
520    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
521
522    public static final class SharedLibraryEntry {
523        public final String path;
524        public final String apk;
525
526        SharedLibraryEntry(String _path, String _apk) {
527            path = _path;
528            apk = _apk;
529        }
530    }
531
532    // Currently known shared libraries.
533    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
534            new ArrayMap<String, SharedLibraryEntry>();
535
536    // All available activities, for your resolving pleasure.
537    final ActivityIntentResolver mActivities =
538            new ActivityIntentResolver();
539
540    // All available receivers, for your resolving pleasure.
541    final ActivityIntentResolver mReceivers =
542            new ActivityIntentResolver();
543
544    // All available services, for your resolving pleasure.
545    final ServiceIntentResolver mServices = new ServiceIntentResolver();
546
547    // All available providers, for your resolving pleasure.
548    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
549
550    // Mapping from provider base names (first directory in content URI codePath)
551    // to the provider information.
552    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
553            new ArrayMap<String, PackageParser.Provider>();
554
555    // Mapping from instrumentation class names to info about them.
556    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
557            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
558
559    // Mapping from permission names to info about them.
560    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
561            new ArrayMap<String, PackageParser.PermissionGroup>();
562
563    // Packages whose data we have transfered into another package, thus
564    // should no longer exist.
565    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
566
567    // Broadcast actions that are only available to the system.
568    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
569
570    /** List of packages waiting for verification. */
571    final SparseArray<PackageVerificationState> mPendingVerification
572            = new SparseArray<PackageVerificationState>();
573
574    /** Set of packages associated with each app op permission. */
575    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
576
577    final PackageInstallerService mInstallerService;
578
579    private final PackageDexOptimizer mPackageDexOptimizer;
580
581    private AtomicInteger mNextMoveId = new AtomicInteger();
582    private final MoveCallbacks mMoveCallbacks;
583
584    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
585
586    // Cache of users who need badging.
587    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
588
589    /** Token for keys in mPendingVerification. */
590    private int mPendingVerificationToken = 0;
591
592    volatile boolean mSystemReady;
593    volatile boolean mSafeMode;
594    volatile boolean mHasSystemUidErrors;
595
596    ApplicationInfo mAndroidApplication;
597    final ActivityInfo mResolveActivity = new ActivityInfo();
598    final ResolveInfo mResolveInfo = new ResolveInfo();
599    ComponentName mResolveComponentName;
600    PackageParser.Package mPlatformPackage;
601    ComponentName mCustomResolverComponentName;
602
603    boolean mResolverReplaced = false;
604
605    private final ComponentName mIntentFilterVerifierComponent;
606    private int mIntentFilterVerificationToken = 0;
607
608    /** Component that knows whether or not an ephemeral application exists */
609    final ComponentName mEphemeralResolverComponent;
610    /** The service connection to the ephemeral resolver */
611    final EphemeralResolverConnection mEphemeralResolverConnection;
612
613    /** Component used to install ephemeral applications */
614    final ComponentName mEphemeralInstallerComponent;
615    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
616    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
617
618    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
619            = new SparseArray<IntentFilterVerificationState>();
620
621    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
622            new DefaultPermissionGrantPolicy(this);
623
624    // List of packages names to keep cached, even if they are uninstalled for all users
625    private List<String> mKeepUninstalledPackages;
626
627    private static class IFVerificationParams {
628        PackageParser.Package pkg;
629        boolean replacing;
630        int userId;
631        int verifierUid;
632
633        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
634                int _userId, int _verifierUid) {
635            pkg = _pkg;
636            replacing = _replacing;
637            userId = _userId;
638            replacing = _replacing;
639            verifierUid = _verifierUid;
640        }
641    }
642
643    private interface IntentFilterVerifier<T extends IntentFilter> {
644        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
645                                               T filter, String packageName);
646        void startVerifications(int userId);
647        void receiveVerificationResponse(int verificationId);
648    }
649
650    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
651        private Context mContext;
652        private ComponentName mIntentFilterVerifierComponent;
653        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
654
655        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
656            mContext = context;
657            mIntentFilterVerifierComponent = verifierComponent;
658        }
659
660        private String getDefaultScheme() {
661            return IntentFilter.SCHEME_HTTPS;
662        }
663
664        @Override
665        public void startVerifications(int userId) {
666            // Launch verifications requests
667            int count = mCurrentIntentFilterVerifications.size();
668            for (int n=0; n<count; n++) {
669                int verificationId = mCurrentIntentFilterVerifications.get(n);
670                final IntentFilterVerificationState ivs =
671                        mIntentFilterVerificationStates.get(verificationId);
672
673                String packageName = ivs.getPackageName();
674
675                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
676                final int filterCount = filters.size();
677                ArraySet<String> domainsSet = new ArraySet<>();
678                for (int m=0; m<filterCount; m++) {
679                    PackageParser.ActivityIntentInfo filter = filters.get(m);
680                    domainsSet.addAll(filter.getHostsList());
681                }
682                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
683                synchronized (mPackages) {
684                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
685                            packageName, domainsList) != null) {
686                        scheduleWriteSettingsLocked();
687                    }
688                }
689                sendVerificationRequest(userId, verificationId, ivs);
690            }
691            mCurrentIntentFilterVerifications.clear();
692        }
693
694        private void sendVerificationRequest(int userId, int verificationId,
695                IntentFilterVerificationState ivs) {
696
697            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
698            verificationIntent.putExtra(
699                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
700                    verificationId);
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
703                    getDefaultScheme());
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
706                    ivs.getHostsString());
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
709                    ivs.getPackageName());
710            verificationIntent.setComponent(mIntentFilterVerifierComponent);
711            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
712
713            UserHandle user = new UserHandle(userId);
714            mContext.sendBroadcastAsUser(verificationIntent, user);
715            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
716                    "Sending IntentFilter verification broadcast");
717        }
718
719        public void receiveVerificationResponse(int verificationId) {
720            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
721
722            final boolean verified = ivs.isVerified();
723
724            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
725            final int count = filters.size();
726            if (DEBUG_DOMAIN_VERIFICATION) {
727                Slog.i(TAG, "Received verification response " + verificationId
728                        + " for " + count + " filters, verified=" + verified);
729            }
730            for (int n=0; n<count; n++) {
731                PackageParser.ActivityIntentInfo filter = filters.get(n);
732                filter.setVerified(verified);
733
734                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
735                        + " verified with result:" + verified + " and hosts:"
736                        + ivs.getHostsString());
737            }
738
739            mIntentFilterVerificationStates.remove(verificationId);
740
741            final String packageName = ivs.getPackageName();
742            IntentFilterVerificationInfo ivi = null;
743
744            synchronized (mPackages) {
745                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
746            }
747            if (ivi == null) {
748                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
749                        + verificationId + " packageName:" + packageName);
750                return;
751            }
752            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
753                    "Updating IntentFilterVerificationInfo for package " + packageName
754                            +" verificationId:" + verificationId);
755
756            synchronized (mPackages) {
757                if (verified) {
758                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
759                } else {
760                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
761                }
762                scheduleWriteSettingsLocked();
763
764                final int userId = ivs.getUserId();
765                if (userId != UserHandle.USER_ALL) {
766                    final int userStatus =
767                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
768
769                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
770                    boolean needUpdate = false;
771
772                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
773                    // already been set by the User thru the Disambiguation dialog
774                    switch (userStatus) {
775                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
776                            if (verified) {
777                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
778                            } else {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
780                            }
781                            needUpdate = true;
782                            break;
783
784                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
785                            if (verified) {
786                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
787                                needUpdate = true;
788                            }
789                            break;
790
791                        default:
792                            // Nothing to do
793                    }
794
795                    if (needUpdate) {
796                        mSettings.updateIntentFilterVerificationStatusLPw(
797                                packageName, updatedStatus, userId);
798                        scheduleWritePackageRestrictionsLocked(userId);
799                    }
800                }
801            }
802        }
803
804        @Override
805        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
806                    ActivityIntentInfo filter, String packageName) {
807            if (!hasValidDomains(filter)) {
808                return false;
809            }
810            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
811            if (ivs == null) {
812                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
813                        packageName);
814            }
815            if (DEBUG_DOMAIN_VERIFICATION) {
816                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
817            }
818            ivs.addFilter(filter);
819            return true;
820        }
821
822        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
823                int userId, int verificationId, String packageName) {
824            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
825                    verifierUid, userId, packageName);
826            ivs.setPendingState();
827            synchronized (mPackages) {
828                mIntentFilterVerificationStates.append(verificationId, ivs);
829                mCurrentIntentFilterVerifications.add(verificationId);
830            }
831            return ivs;
832        }
833    }
834
835    private static boolean hasValidDomains(ActivityIntentInfo filter) {
836        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
837                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
838                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
839    }
840
841    private IntentFilterVerifier mIntentFilterVerifier;
842
843    // Set of pending broadcasts for aggregating enable/disable of components.
844    static class PendingPackageBroadcasts {
845        // for each user id, a map of <package name -> components within that package>
846        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
847
848        public PendingPackageBroadcasts() {
849            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
850        }
851
852        public ArrayList<String> get(int userId, String packageName) {
853            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
854            return packages.get(packageName);
855        }
856
857        public void put(int userId, String packageName, ArrayList<String> components) {
858            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
859            packages.put(packageName, components);
860        }
861
862        public void remove(int userId, String packageName) {
863            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
864            if (packages != null) {
865                packages.remove(packageName);
866            }
867        }
868
869        public void remove(int userId) {
870            mUidMap.remove(userId);
871        }
872
873        public int userIdCount() {
874            return mUidMap.size();
875        }
876
877        public int userIdAt(int n) {
878            return mUidMap.keyAt(n);
879        }
880
881        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
882            return mUidMap.get(userId);
883        }
884
885        public int size() {
886            // total number of pending broadcast entries across all userIds
887            int num = 0;
888            for (int i = 0; i< mUidMap.size(); i++) {
889                num += mUidMap.valueAt(i).size();
890            }
891            return num;
892        }
893
894        public void clear() {
895            mUidMap.clear();
896        }
897
898        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
899            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
900            if (map == null) {
901                map = new ArrayMap<String, ArrayList<String>>();
902                mUidMap.put(userId, map);
903            }
904            return map;
905        }
906    }
907    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
908
909    // Service Connection to remote media container service to copy
910    // package uri's from external media onto secure containers
911    // or internal storage.
912    private IMediaContainerService mContainerService = null;
913
914    static final int SEND_PENDING_BROADCAST = 1;
915    static final int MCS_BOUND = 3;
916    static final int END_COPY = 4;
917    static final int INIT_COPY = 5;
918    static final int MCS_UNBIND = 6;
919    static final int START_CLEANING_PACKAGE = 7;
920    static final int FIND_INSTALL_LOC = 8;
921    static final int POST_INSTALL = 9;
922    static final int MCS_RECONNECT = 10;
923    static final int MCS_GIVE_UP = 11;
924    static final int UPDATED_MEDIA_STATUS = 12;
925    static final int WRITE_SETTINGS = 13;
926    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
927    static final int PACKAGE_VERIFIED = 15;
928    static final int CHECK_PENDING_VERIFICATION = 16;
929    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
930    static final int INTENT_FILTER_VERIFIED = 18;
931
932    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
933
934    // Delay time in millisecs
935    static final int BROADCAST_DELAY = 10 * 1000;
936
937    static UserManagerService sUserManager;
938
939    // Stores a list of users whose package restrictions file needs to be updated
940    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
941
942    final private DefaultContainerConnection mDefContainerConn =
943            new DefaultContainerConnection();
944    class DefaultContainerConnection implements ServiceConnection {
945        public void onServiceConnected(ComponentName name, IBinder service) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
947            IMediaContainerService imcs =
948                IMediaContainerService.Stub.asInterface(service);
949            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
950        }
951
952        public void onServiceDisconnected(ComponentName name) {
953            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
954        }
955    }
956
957    // Recordkeeping of restore-after-install operations that are currently in flight
958    // between the Package Manager and the Backup Manager
959    static class PostInstallData {
960        public InstallArgs args;
961        public PackageInstalledInfo res;
962
963        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
964            args = _a;
965            res = _r;
966        }
967    }
968
969    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
970    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
971
972    // XML tags for backup/restore of various bits of state
973    private static final String TAG_PREFERRED_BACKUP = "pa";
974    private static final String TAG_DEFAULT_APPS = "da";
975    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
976
977    final String mRequiredVerifierPackage;
978    final String mRequiredInstallerPackage;
979
980    private final PackageUsage mPackageUsage = new PackageUsage();
981
982    private class PackageUsage {
983        private static final int WRITE_INTERVAL
984            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
985
986        private final Object mFileLock = new Object();
987        private final AtomicLong mLastWritten = new AtomicLong(0);
988        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
989
990        private boolean mIsHistoricalPackageUsageAvailable = true;
991
992        boolean isHistoricalPackageUsageAvailable() {
993            return mIsHistoricalPackageUsageAvailable;
994        }
995
996        void write(boolean force) {
997            if (force) {
998                writeInternal();
999                return;
1000            }
1001            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1002                && !DEBUG_DEXOPT) {
1003                return;
1004            }
1005            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1006                new Thread("PackageUsage_DiskWriter") {
1007                    @Override
1008                    public void run() {
1009                        try {
1010                            writeInternal();
1011                        } finally {
1012                            mBackgroundWriteRunning.set(false);
1013                        }
1014                    }
1015                }.start();
1016            }
1017        }
1018
1019        private void writeInternal() {
1020            synchronized (mPackages) {
1021                synchronized (mFileLock) {
1022                    AtomicFile file = getFile();
1023                    FileOutputStream f = null;
1024                    try {
1025                        f = file.startWrite();
1026                        BufferedOutputStream out = new BufferedOutputStream(f);
1027                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1028                        StringBuilder sb = new StringBuilder();
1029                        for (PackageParser.Package pkg : mPackages.values()) {
1030                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1031                                continue;
1032                            }
1033                            sb.setLength(0);
1034                            sb.append(pkg.packageName);
1035                            sb.append(' ');
1036                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1037                            sb.append('\n');
1038                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1039                        }
1040                        out.flush();
1041                        file.finishWrite(f);
1042                    } catch (IOException e) {
1043                        if (f != null) {
1044                            file.failWrite(f);
1045                        }
1046                        Log.e(TAG, "Failed to write package usage times", e);
1047                    }
1048                }
1049            }
1050            mLastWritten.set(SystemClock.elapsedRealtime());
1051        }
1052
1053        void readLP() {
1054            synchronized (mFileLock) {
1055                AtomicFile file = getFile();
1056                BufferedInputStream in = null;
1057                try {
1058                    in = new BufferedInputStream(file.openRead());
1059                    StringBuffer sb = new StringBuffer();
1060                    while (true) {
1061                        String packageName = readToken(in, sb, ' ');
1062                        if (packageName == null) {
1063                            break;
1064                        }
1065                        String timeInMillisString = readToken(in, sb, '\n');
1066                        if (timeInMillisString == null) {
1067                            throw new IOException("Failed to find last usage time for package "
1068                                                  + packageName);
1069                        }
1070                        PackageParser.Package pkg = mPackages.get(packageName);
1071                        if (pkg == null) {
1072                            continue;
1073                        }
1074                        long timeInMillis;
1075                        try {
1076                            timeInMillis = Long.parseLong(timeInMillisString);
1077                        } catch (NumberFormatException e) {
1078                            throw new IOException("Failed to parse " + timeInMillisString
1079                                                  + " as a long.", e);
1080                        }
1081                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1082                    }
1083                } catch (FileNotFoundException expected) {
1084                    mIsHistoricalPackageUsageAvailable = false;
1085                } catch (IOException e) {
1086                    Log.w(TAG, "Failed to read package usage times", e);
1087                } finally {
1088                    IoUtils.closeQuietly(in);
1089                }
1090            }
1091            mLastWritten.set(SystemClock.elapsedRealtime());
1092        }
1093
1094        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1095                throws IOException {
1096            sb.setLength(0);
1097            while (true) {
1098                int ch = in.read();
1099                if (ch == -1) {
1100                    if (sb.length() == 0) {
1101                        return null;
1102                    }
1103                    throw new IOException("Unexpected EOF");
1104                }
1105                if (ch == endOfToken) {
1106                    return sb.toString();
1107                }
1108                sb.append((char)ch);
1109            }
1110        }
1111
1112        private AtomicFile getFile() {
1113            File dataDir = Environment.getDataDirectory();
1114            File systemDir = new File(dataDir, "system");
1115            File fname = new File(systemDir, "package-usage.list");
1116            return new AtomicFile(fname);
1117        }
1118    }
1119
1120    class PackageHandler extends Handler {
1121        private boolean mBound = false;
1122        final ArrayList<HandlerParams> mPendingInstalls =
1123            new ArrayList<HandlerParams>();
1124
1125        private boolean connectToService() {
1126            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1127                    " DefaultContainerService");
1128            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1130            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1131                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1132                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1133                mBound = true;
1134                return true;
1135            }
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137            return false;
1138        }
1139
1140        private void disconnectService() {
1141            mContainerService = null;
1142            mBound = false;
1143            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1144            mContext.unbindService(mDefContainerConn);
1145            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1146        }
1147
1148        PackageHandler(Looper looper) {
1149            super(looper);
1150        }
1151
1152        public void handleMessage(Message msg) {
1153            try {
1154                doHandleMessage(msg);
1155            } finally {
1156                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157            }
1158        }
1159
1160        void doHandleMessage(Message msg) {
1161            switch (msg.what) {
1162                case INIT_COPY: {
1163                    HandlerParams params = (HandlerParams) msg.obj;
1164                    int idx = mPendingInstalls.size();
1165                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1166                    // If a bind was already initiated we dont really
1167                    // need to do anything. The pending install
1168                    // will be processed later on.
1169                    if (!mBound) {
1170                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                System.identityHashCode(mHandler));
1172                        // If this is the only one pending we might
1173                        // have to bind to the service again.
1174                        if (!connectToService()) {
1175                            Slog.e(TAG, "Failed to bind to media container service");
1176                            params.serviceError();
1177                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1178                                    System.identityHashCode(mHandler));
1179                            if (params.traceMethod != null) {
1180                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1181                                        params.traceCookie);
1182                            }
1183                            return;
1184                        } else {
1185                            // Once we bind to the service, the first
1186                            // pending request will be processed.
1187                            mPendingInstalls.add(idx, params);
1188                        }
1189                    } else {
1190                        mPendingInstalls.add(idx, params);
1191                        // Already bound to the service. Just make
1192                        // sure we trigger off processing the first request.
1193                        if (idx == 0) {
1194                            mHandler.sendEmptyMessage(MCS_BOUND);
1195                        }
1196                    }
1197                    break;
1198                }
1199                case MCS_BOUND: {
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1201                    if (msg.obj != null) {
1202                        mContainerService = (IMediaContainerService) msg.obj;
1203                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1204                                System.identityHashCode(mHandler));
1205                    }
1206                    if (mContainerService == null) {
1207                        if (!mBound) {
1208                            // Something seriously wrong since we are not bound and we are not
1209                            // waiting for connection. Bail out.
1210                            Slog.e(TAG, "Cannot bind to media container service");
1211                            for (HandlerParams params : mPendingInstalls) {
1212                                // Indicate service bind error
1213                                params.serviceError();
1214                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1215                                        System.identityHashCode(params));
1216                                if (params.traceMethod != null) {
1217                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1218                                            params.traceMethod, params.traceCookie);
1219                                }
1220                                return;
1221                            }
1222                            mPendingInstalls.clear();
1223                        } else {
1224                            Slog.w(TAG, "Waiting to connect to media container service");
1225                        }
1226                    } else if (mPendingInstalls.size() > 0) {
1227                        HandlerParams params = mPendingInstalls.get(0);
1228                        if (params != null) {
1229                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1230                                    System.identityHashCode(params));
1231                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1232                            if (params.startCopy()) {
1233                                // We are done...  look for more work or to
1234                                // go idle.
1235                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1236                                        "Checking for more work or unbind...");
1237                                // Delete pending install
1238                                if (mPendingInstalls.size() > 0) {
1239                                    mPendingInstalls.remove(0);
1240                                }
1241                                if (mPendingInstalls.size() == 0) {
1242                                    if (mBound) {
1243                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1244                                                "Posting delayed MCS_UNBIND");
1245                                        removeMessages(MCS_UNBIND);
1246                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1247                                        // Unbind after a little delay, to avoid
1248                                        // continual thrashing.
1249                                        sendMessageDelayed(ubmsg, 10000);
1250                                    }
1251                                } else {
1252                                    // There are more pending requests in queue.
1253                                    // Just post MCS_BOUND message to trigger processing
1254                                    // of next pending install.
1255                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1256                                            "Posting MCS_BOUND for next work");
1257                                    mHandler.sendEmptyMessage(MCS_BOUND);
1258                                }
1259                            }
1260                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1261                        }
1262                    } else {
1263                        // Should never happen ideally.
1264                        Slog.w(TAG, "Empty queue");
1265                    }
1266                    break;
1267                }
1268                case MCS_RECONNECT: {
1269                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1270                    if (mPendingInstalls.size() > 0) {
1271                        if (mBound) {
1272                            disconnectService();
1273                        }
1274                        if (!connectToService()) {
1275                            Slog.e(TAG, "Failed to bind to media container service");
1276                            for (HandlerParams params : mPendingInstalls) {
1277                                // Indicate service bind error
1278                                params.serviceError();
1279                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1280                                        System.identityHashCode(params));
1281                            }
1282                            mPendingInstalls.clear();
1283                        }
1284                    }
1285                    break;
1286                }
1287                case MCS_UNBIND: {
1288                    // If there is no actual work left, then time to unbind.
1289                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1290
1291                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1292                        if (mBound) {
1293                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1294
1295                            disconnectService();
1296                        }
1297                    } else if (mPendingInstalls.size() > 0) {
1298                        // There are more pending requests in queue.
1299                        // Just post MCS_BOUND message to trigger processing
1300                        // of next pending install.
1301                        mHandler.sendEmptyMessage(MCS_BOUND);
1302                    }
1303
1304                    break;
1305                }
1306                case MCS_GIVE_UP: {
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1308                    HandlerParams params = mPendingInstalls.remove(0);
1309                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1310                            System.identityHashCode(params));
1311                    break;
1312                }
1313                case SEND_PENDING_BROADCAST: {
1314                    String packages[];
1315                    ArrayList<String> components[];
1316                    int size = 0;
1317                    int uids[];
1318                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1319                    synchronized (mPackages) {
1320                        if (mPendingBroadcasts == null) {
1321                            return;
1322                        }
1323                        size = mPendingBroadcasts.size();
1324                        if (size <= 0) {
1325                            // Nothing to be done. Just return
1326                            return;
1327                        }
1328                        packages = new String[size];
1329                        components = new ArrayList[size];
1330                        uids = new int[size];
1331                        int i = 0;  // filling out the above arrays
1332
1333                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1334                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1335                            Iterator<Map.Entry<String, ArrayList<String>>> it
1336                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1337                                            .entrySet().iterator();
1338                            while (it.hasNext() && i < size) {
1339                                Map.Entry<String, ArrayList<String>> ent = it.next();
1340                                packages[i] = ent.getKey();
1341                                components[i] = ent.getValue();
1342                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1343                                uids[i] = (ps != null)
1344                                        ? UserHandle.getUid(packageUserId, ps.appId)
1345                                        : -1;
1346                                i++;
1347                            }
1348                        }
1349                        size = i;
1350                        mPendingBroadcasts.clear();
1351                    }
1352                    // Send broadcasts
1353                    for (int i = 0; i < size; i++) {
1354                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1355                    }
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357                    break;
1358                }
1359                case START_CLEANING_PACKAGE: {
1360                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1361                    final String packageName = (String)msg.obj;
1362                    final int userId = msg.arg1;
1363                    final boolean andCode = msg.arg2 != 0;
1364                    synchronized (mPackages) {
1365                        if (userId == UserHandle.USER_ALL) {
1366                            int[] users = sUserManager.getUserIds();
1367                            for (int user : users) {
1368                                mSettings.addPackageToCleanLPw(
1369                                        new PackageCleanItem(user, packageName, andCode));
1370                            }
1371                        } else {
1372                            mSettings.addPackageToCleanLPw(
1373                                    new PackageCleanItem(userId, packageName, andCode));
1374                        }
1375                    }
1376                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1377                    startCleaningPackages();
1378                } break;
1379                case POST_INSTALL: {
1380                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1381
1382                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1383                    mRunningInstalls.delete(msg.arg1);
1384                    boolean deleteOld = false;
1385
1386                    if (data != null) {
1387                        InstallArgs args = data.args;
1388                        PackageInstalledInfo res = data.res;
1389
1390                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1391                            final String packageName = res.pkg.applicationInfo.packageName;
1392                            res.removedInfo.sendBroadcast(false, true, false);
1393                            Bundle extras = new Bundle(1);
1394                            extras.putInt(Intent.EXTRA_UID, res.uid);
1395
1396                            // Now that we successfully installed the package, grant runtime
1397                            // permissions if requested before broadcasting the install.
1398                            if ((args.installFlags
1399                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1400                                    && res.pkg.applicationInfo.targetSdkVersion
1401                                            >= Build.VERSION_CODES.M) {
1402                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1403                                        args.installGrantPermissions);
1404                            }
1405
1406                            synchronized (mPackages) {
1407                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1408                            }
1409
1410                            // Determine the set of users who are adding this
1411                            // package for the first time vs. those who are seeing
1412                            // an update.
1413                            int[] firstUsers;
1414                            int[] updateUsers = new int[0];
1415                            if (res.origUsers == null || res.origUsers.length == 0) {
1416                                firstUsers = res.newUsers;
1417                            } else {
1418                                firstUsers = new int[0];
1419                                for (int i=0; i<res.newUsers.length; i++) {
1420                                    int user = res.newUsers[i];
1421                                    boolean isNew = true;
1422                                    for (int j=0; j<res.origUsers.length; j++) {
1423                                        if (res.origUsers[j] == user) {
1424                                            isNew = false;
1425                                            break;
1426                                        }
1427                                    }
1428                                    if (isNew) {
1429                                        int[] newFirst = new int[firstUsers.length+1];
1430                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1431                                                firstUsers.length);
1432                                        newFirst[firstUsers.length] = user;
1433                                        firstUsers = newFirst;
1434                                    } else {
1435                                        int[] newUpdate = new int[updateUsers.length+1];
1436                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1437                                                updateUsers.length);
1438                                        newUpdate[updateUsers.length] = user;
1439                                        updateUsers = newUpdate;
1440                                    }
1441                                }
1442                            }
1443                            // don't broadcast for ephemeral installs/updates
1444                            final boolean isEphemeral = isEphemeral(res.pkg);
1445                            if (!isEphemeral) {
1446                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1447                                        extras, 0 /*flags*/, null /*targetPackage*/,
1448                                        null /*finishedReceiver*/, firstUsers);
1449                            }
1450                            final boolean update = res.removedInfo.removedPackage != null;
1451                            if (update) {
1452                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1453                            }
1454                            if (!isEphemeral) {
1455                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1456                                        extras, 0 /*flags*/, null /*targetPackage*/,
1457                                        null /*finishedReceiver*/, updateUsers);
1458                            }
1459                            if (update) {
1460                                if (!isEphemeral) {
1461                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1462                                            packageName, extras, 0 /*flags*/,
1463                                            null /*targetPackage*/, null /*finishedReceiver*/,
1464                                            updateUsers);
1465                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1466                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1467                                            packageName /*targetPackage*/,
1468                                            null /*finishedReceiver*/, updateUsers);
1469                                }
1470
1471                                // treat asec-hosted packages like removable media on upgrade
1472                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1473                                    if (DEBUG_INSTALL) {
1474                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1475                                                + " is ASEC-hosted -> AVAILABLE");
1476                                    }
1477                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1478                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1479                                    pkgList.add(packageName);
1480                                    sendResourcesChangedBroadcast(true, true,
1481                                            pkgList,uidArray, null);
1482                                }
1483                            }
1484                            if (res.removedInfo.args != null) {
1485                                // Remove the replaced package's older resources safely now
1486                                deleteOld = true;
1487                            }
1488
1489                            // If this app is a browser and it's newly-installed for some
1490                            // users, clear any default-browser state in those users
1491                            if (firstUsers.length > 0) {
1492                                // the app's nature doesn't depend on the user, so we can just
1493                                // check its browser nature in any user and generalize.
1494                                if (packageIsBrowser(packageName, firstUsers[0])) {
1495                                    synchronized (mPackages) {
1496                                        for (int userId : firstUsers) {
1497                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1498                                        }
1499                                    }
1500                                }
1501                            }
1502                            // Log current value of "unknown sources" setting
1503                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1504                                getUnknownSourcesSettings());
1505                        }
1506                        // Force a gc to clear up things
1507                        Runtime.getRuntime().gc();
1508                        // We delete after a gc for applications  on sdcard.
1509                        if (deleteOld) {
1510                            synchronized (mInstallLock) {
1511                                res.removedInfo.args.doPostDeleteLI(true);
1512                            }
1513                        }
1514                        if (args.observer != null) {
1515                            try {
1516                                Bundle extras = extrasForInstallResult(res);
1517                                args.observer.onPackageInstalled(res.name, res.returnCode,
1518                                        res.returnMsg, extras);
1519                            } catch (RemoteException e) {
1520                                Slog.i(TAG, "Observer no longer exists.");
1521                            }
1522                        }
1523                        if (args.traceMethod != null) {
1524                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1525                                    args.traceCookie);
1526                        }
1527                        return;
1528                    } else {
1529                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1530                    }
1531
1532                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1533                } break;
1534                case UPDATED_MEDIA_STATUS: {
1535                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1536                    boolean reportStatus = msg.arg1 == 1;
1537                    boolean doGc = msg.arg2 == 1;
1538                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1539                    if (doGc) {
1540                        // Force a gc to clear up stale containers.
1541                        Runtime.getRuntime().gc();
1542                    }
1543                    if (msg.obj != null) {
1544                        @SuppressWarnings("unchecked")
1545                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1546                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1547                        // Unload containers
1548                        unloadAllContainers(args);
1549                    }
1550                    if (reportStatus) {
1551                        try {
1552                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1553                            PackageHelper.getMountService().finishMediaUpdate();
1554                        } catch (RemoteException e) {
1555                            Log.e(TAG, "MountService not running?");
1556                        }
1557                    }
1558                } break;
1559                case WRITE_SETTINGS: {
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1561                    synchronized (mPackages) {
1562                        removeMessages(WRITE_SETTINGS);
1563                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1564                        mSettings.writeLPr();
1565                        mDirtyUsers.clear();
1566                    }
1567                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1568                } break;
1569                case WRITE_PACKAGE_RESTRICTIONS: {
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1571                    synchronized (mPackages) {
1572                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1573                        for (int userId : mDirtyUsers) {
1574                            mSettings.writePackageRestrictionsLPr(userId);
1575                        }
1576                        mDirtyUsers.clear();
1577                    }
1578                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1579                } break;
1580                case CHECK_PENDING_VERIFICATION: {
1581                    final int verificationId = msg.arg1;
1582                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1583
1584                    if ((state != null) && !state.timeoutExtended()) {
1585                        final InstallArgs args = state.getInstallArgs();
1586                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1587
1588                        Slog.i(TAG, "Verification timed out for " + originUri);
1589                        mPendingVerification.remove(verificationId);
1590
1591                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1592
1593                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1594                            Slog.i(TAG, "Continuing with installation of " + originUri);
1595                            state.setVerifierResponse(Binder.getCallingUid(),
1596                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1597                            broadcastPackageVerified(verificationId, originUri,
1598                                    PackageManager.VERIFICATION_ALLOW,
1599                                    state.getInstallArgs().getUser());
1600                            try {
1601                                ret = args.copyApk(mContainerService, true);
1602                            } catch (RemoteException e) {
1603                                Slog.e(TAG, "Could not contact the ContainerService");
1604                            }
1605                        } else {
1606                            broadcastPackageVerified(verificationId, originUri,
1607                                    PackageManager.VERIFICATION_REJECT,
1608                                    state.getInstallArgs().getUser());
1609                        }
1610
1611                        Trace.asyncTraceEnd(
1612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613
1614                        processPendingInstall(args, ret);
1615                        mHandler.sendEmptyMessage(MCS_UNBIND);
1616                    }
1617                    break;
1618                }
1619                case PACKAGE_VERIFIED: {
1620                    final int verificationId = msg.arg1;
1621
1622                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1623                    if (state == null) {
1624                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1625                        break;
1626                    }
1627
1628                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1629
1630                    state.setVerifierResponse(response.callerUid, response.code);
1631
1632                    if (state.isVerificationComplete()) {
1633                        mPendingVerification.remove(verificationId);
1634
1635                        final InstallArgs args = state.getInstallArgs();
1636                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1637
1638                        int ret;
1639                        if (state.isInstallAllowed()) {
1640                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1641                            broadcastPackageVerified(verificationId, originUri,
1642                                    response.code, state.getInstallArgs().getUser());
1643                            try {
1644                                ret = args.copyApk(mContainerService, true);
1645                            } catch (RemoteException e) {
1646                                Slog.e(TAG, "Could not contact the ContainerService");
1647                            }
1648                        } else {
1649                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1650                        }
1651
1652                        Trace.asyncTraceEnd(
1653                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1654
1655                        processPendingInstall(args, ret);
1656                        mHandler.sendEmptyMessage(MCS_UNBIND);
1657                    }
1658
1659                    break;
1660                }
1661                case START_INTENT_FILTER_VERIFICATIONS: {
1662                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1663                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1664                            params.replacing, params.pkg);
1665                    break;
1666                }
1667                case INTENT_FILTER_VERIFIED: {
1668                    final int verificationId = msg.arg1;
1669
1670                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1671                            verificationId);
1672                    if (state == null) {
1673                        Slog.w(TAG, "Invalid IntentFilter verification token "
1674                                + verificationId + " received");
1675                        break;
1676                    }
1677
1678                    final int userId = state.getUserId();
1679
1680                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1681                            "Processing IntentFilter verification with token:"
1682                            + verificationId + " and userId:" + userId);
1683
1684                    final IntentFilterVerificationResponse response =
1685                            (IntentFilterVerificationResponse) msg.obj;
1686
1687                    state.setVerifierResponse(response.callerUid, response.code);
1688
1689                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1690                            "IntentFilter verification with token:" + verificationId
1691                            + " and userId:" + userId
1692                            + " is settings verifier response with response code:"
1693                            + response.code);
1694
1695                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1696                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1697                                + response.getFailedDomainsString());
1698                    }
1699
1700                    if (state.isVerificationComplete()) {
1701                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1702                    } else {
1703                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1704                                "IntentFilter verification with token:" + verificationId
1705                                + " was not said to be complete");
1706                    }
1707
1708                    break;
1709                }
1710            }
1711        }
1712    }
1713
1714    private StorageEventListener mStorageListener = new StorageEventListener() {
1715        @Override
1716        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1717            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1718                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1719                    final String volumeUuid = vol.getFsUuid();
1720
1721                    // Clean up any users or apps that were removed or recreated
1722                    // while this volume was missing
1723                    reconcileUsers(volumeUuid);
1724                    reconcileApps(volumeUuid);
1725
1726                    // Clean up any install sessions that expired or were
1727                    // cancelled while this volume was missing
1728                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1729
1730                    loadPrivatePackages(vol);
1731
1732                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1733                    unloadPrivatePackages(vol);
1734                }
1735            }
1736
1737            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1738                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1739                    updateExternalMediaStatus(true, false);
1740                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1741                    updateExternalMediaStatus(false, false);
1742                }
1743            }
1744        }
1745
1746        @Override
1747        public void onVolumeForgotten(String fsUuid) {
1748            if (TextUtils.isEmpty(fsUuid)) {
1749                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1750                return;
1751            }
1752
1753            // Remove any apps installed on the forgotten volume
1754            synchronized (mPackages) {
1755                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1756                for (PackageSetting ps : packages) {
1757                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1758                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1759                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1760                }
1761
1762                mSettings.onVolumeForgotten(fsUuid);
1763                mSettings.writeLPr();
1764            }
1765        }
1766    };
1767
1768    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1769            String[] grantedPermissions) {
1770        if (userId >= UserHandle.USER_SYSTEM) {
1771            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1772        } else if (userId == UserHandle.USER_ALL) {
1773            final int[] userIds;
1774            synchronized (mPackages) {
1775                userIds = UserManagerService.getInstance().getUserIds();
1776            }
1777            for (int someUserId : userIds) {
1778                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1779            }
1780        }
1781
1782        // We could have touched GID membership, so flush out packages.list
1783        synchronized (mPackages) {
1784            mSettings.writePackageListLPr();
1785        }
1786    }
1787
1788    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1789            String[] grantedPermissions) {
1790        SettingBase sb = (SettingBase) pkg.mExtras;
1791        if (sb == null) {
1792            return;
1793        }
1794
1795        PermissionsState permissionsState = sb.getPermissionsState();
1796
1797        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1798                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1799
1800        synchronized (mPackages) {
1801            for (String permission : pkg.requestedPermissions) {
1802                BasePermission bp = mSettings.mPermissions.get(permission);
1803                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1804                        && (grantedPermissions == null
1805                               || ArrayUtils.contains(grantedPermissions, permission))) {
1806                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1807                    // Installer cannot change immutable permissions.
1808                    if ((flags & immutableFlags) == 0) {
1809                        grantRuntimePermission(pkg.packageName, permission, userId);
1810                    }
1811                }
1812            }
1813        }
1814    }
1815
1816    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1817        Bundle extras = null;
1818        switch (res.returnCode) {
1819            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1820                extras = new Bundle();
1821                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1822                        res.origPermission);
1823                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1824                        res.origPackage);
1825                break;
1826            }
1827            case PackageManager.INSTALL_SUCCEEDED: {
1828                extras = new Bundle();
1829                extras.putBoolean(Intent.EXTRA_REPLACING,
1830                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1831                break;
1832            }
1833        }
1834        return extras;
1835    }
1836
1837    void scheduleWriteSettingsLocked() {
1838        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1839            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1840        }
1841    }
1842
1843    void scheduleWritePackageRestrictionsLocked(int userId) {
1844        if (!sUserManager.exists(userId)) return;
1845        mDirtyUsers.add(userId);
1846        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1847            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1848        }
1849    }
1850
1851    public static PackageManagerService main(Context context, Installer installer,
1852            boolean factoryTest, boolean onlyCore) {
1853        PackageManagerService m = new PackageManagerService(context, installer,
1854                factoryTest, onlyCore);
1855        m.enableSystemUserPackages();
1856        ServiceManager.addService("package", m);
1857        return m;
1858    }
1859
1860    private void enableSystemUserPackages() {
1861        if (!UserManager.isSplitSystemUser()) {
1862            return;
1863        }
1864        // For system user, enable apps based on the following conditions:
1865        // - app is whitelisted or belong to one of these groups:
1866        //   -- system app which has no launcher icons
1867        //   -- system app which has INTERACT_ACROSS_USERS permission
1868        //   -- system IME app
1869        // - app is not in the blacklist
1870        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1871        Set<String> enableApps = new ArraySet<>();
1872        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1873                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1874                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1875        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1876        enableApps.addAll(wlApps);
1877        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1878                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1879        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1880        enableApps.removeAll(blApps);
1881        Log.i(TAG, "Applications installed for system user: " + enableApps);
1882        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1883                UserHandle.SYSTEM);
1884        final int allAppsSize = allAps.size();
1885        synchronized (mPackages) {
1886            for (int i = 0; i < allAppsSize; i++) {
1887                String pName = allAps.get(i);
1888                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1889                // Should not happen, but we shouldn't be failing if it does
1890                if (pkgSetting == null) {
1891                    continue;
1892                }
1893                boolean install = enableApps.contains(pName);
1894                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1895                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1896                            + " for system user");
1897                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1898                }
1899            }
1900        }
1901    }
1902
1903    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1904        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1905                Context.DISPLAY_SERVICE);
1906        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1907    }
1908
1909    public PackageManagerService(Context context, Installer installer,
1910            boolean factoryTest, boolean onlyCore) {
1911        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1912                SystemClock.uptimeMillis());
1913
1914        if (mSdkVersion <= 0) {
1915            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1916        }
1917
1918        mContext = context;
1919        mFactoryTest = factoryTest;
1920        mOnlyCore = onlyCore;
1921        mMetrics = new DisplayMetrics();
1922        mSettings = new Settings(mPackages);
1923        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1924                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1925        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1926                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1927        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1928                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1929        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1930                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1931        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1932                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1933        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1934                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1935
1936        String separateProcesses = SystemProperties.get("debug.separate_processes");
1937        if (separateProcesses != null && separateProcesses.length() > 0) {
1938            if ("*".equals(separateProcesses)) {
1939                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1940                mSeparateProcesses = null;
1941                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1942            } else {
1943                mDefParseFlags = 0;
1944                mSeparateProcesses = separateProcesses.split(",");
1945                Slog.w(TAG, "Running with debug.separate_processes: "
1946                        + separateProcesses);
1947            }
1948        } else {
1949            mDefParseFlags = 0;
1950            mSeparateProcesses = null;
1951        }
1952
1953        mInstaller = installer;
1954        mPackageDexOptimizer = new PackageDexOptimizer(this);
1955        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1956
1957        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1958                FgThread.get().getLooper());
1959
1960        getDefaultDisplayMetrics(context, mMetrics);
1961
1962        SystemConfig systemConfig = SystemConfig.getInstance();
1963        mGlobalGids = systemConfig.getGlobalGids();
1964        mSystemPermissions = systemConfig.getSystemPermissions();
1965        mAvailableFeatures = systemConfig.getAvailableFeatures();
1966
1967        synchronized (mInstallLock) {
1968        // writer
1969        synchronized (mPackages) {
1970            mHandlerThread = new ServiceThread(TAG,
1971                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1972            mHandlerThread.start();
1973            mHandler = new PackageHandler(mHandlerThread.getLooper());
1974            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1975
1976            File dataDir = Environment.getDataDirectory();
1977            mAppInstallDir = new File(dataDir, "app");
1978            mAppLib32InstallDir = new File(dataDir, "app-lib");
1979            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1980            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1981            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1982
1983            sUserManager = new UserManagerService(context, this, mPackages);
1984
1985            // Propagate permission configuration in to package manager.
1986            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1987                    = systemConfig.getPermissions();
1988            for (int i=0; i<permConfig.size(); i++) {
1989                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1990                BasePermission bp = mSettings.mPermissions.get(perm.name);
1991                if (bp == null) {
1992                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1993                    mSettings.mPermissions.put(perm.name, bp);
1994                }
1995                if (perm.gids != null) {
1996                    bp.setGids(perm.gids, perm.perUser);
1997                }
1998            }
1999
2000            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2001            for (int i=0; i<libConfig.size(); i++) {
2002                mSharedLibraries.put(libConfig.keyAt(i),
2003                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2004            }
2005
2006            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2007
2008            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2009
2010            String customResolverActivity = Resources.getSystem().getString(
2011                    R.string.config_customResolverActivity);
2012            if (TextUtils.isEmpty(customResolverActivity)) {
2013                customResolverActivity = null;
2014            } else {
2015                mCustomResolverComponentName = ComponentName.unflattenFromString(
2016                        customResolverActivity);
2017            }
2018
2019            long startTime = SystemClock.uptimeMillis();
2020
2021            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2022                    startTime);
2023
2024            // Set flag to monitor and not change apk file paths when
2025            // scanning install directories.
2026            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2027
2028            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2029            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2030
2031            if (bootClassPath == null) {
2032                Slog.w(TAG, "No BOOTCLASSPATH found!");
2033            }
2034
2035            if (systemServerClassPath == null) {
2036                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2037            }
2038
2039            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2040            final String[] dexCodeInstructionSets =
2041                    getDexCodeInstructionSets(
2042                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2043
2044            /**
2045             * Ensure all external libraries have had dexopt run on them.
2046             */
2047            if (mSharedLibraries.size() > 0) {
2048                // NOTE: For now, we're compiling these system "shared libraries"
2049                // (and framework jars) into all available architectures. It's possible
2050                // to compile them only when we come across an app that uses them (there's
2051                // already logic for that in scanPackageLI) but that adds some complexity.
2052                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2053                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2054                        final String lib = libEntry.path;
2055                        if (lib == null) {
2056                            continue;
2057                        }
2058
2059                        try {
2060                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2061                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2062                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2063                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2064                            }
2065                        } catch (FileNotFoundException e) {
2066                            Slog.w(TAG, "Library not found: " + lib);
2067                        } catch (IOException e) {
2068                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2069                                    + e.getMessage());
2070                        }
2071                    }
2072                }
2073            }
2074
2075            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2076
2077            final VersionInfo ver = mSettings.getInternalVersion();
2078            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2079            // when upgrading from pre-M, promote system app permissions from install to runtime
2080            mPromoteSystemApps =
2081                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2082
2083            // save off the names of pre-existing system packages prior to scanning; we don't
2084            // want to automatically grant runtime permissions for new system apps
2085            if (mPromoteSystemApps) {
2086                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2087                while (pkgSettingIter.hasNext()) {
2088                    PackageSetting ps = pkgSettingIter.next();
2089                    if (isSystemApp(ps)) {
2090                        mExistingSystemPackages.add(ps.name);
2091                    }
2092                }
2093            }
2094
2095            // Collect vendor overlay packages.
2096            // (Do this before scanning any apps.)
2097            // For security and version matching reason, only consider
2098            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2099            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2100            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2101                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2102
2103            // Find base frameworks (resource packages without code).
2104            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2105                    | PackageParser.PARSE_IS_SYSTEM_DIR
2106                    | PackageParser.PARSE_IS_PRIVILEGED,
2107                    scanFlags | SCAN_NO_DEX, 0);
2108
2109            // Collected privileged system packages.
2110            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2111            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2112                    | PackageParser.PARSE_IS_SYSTEM_DIR
2113                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2114
2115            // Collect ordinary system packages.
2116            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2117            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2118                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2119
2120            // Collect all vendor packages.
2121            File vendorAppDir = new File("/vendor/app");
2122            try {
2123                vendorAppDir = vendorAppDir.getCanonicalFile();
2124            } catch (IOException e) {
2125                // failed to look up canonical path, continue with original one
2126            }
2127            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2128                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2129
2130            // Collect all OEM packages.
2131            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2132            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2133                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2134
2135            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2136            mInstaller.moveFiles();
2137
2138            // Prune any system packages that no longer exist.
2139            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2140            if (!mOnlyCore) {
2141                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2142                while (psit.hasNext()) {
2143                    PackageSetting ps = psit.next();
2144
2145                    /*
2146                     * If this is not a system app, it can't be a
2147                     * disable system app.
2148                     */
2149                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2150                        continue;
2151                    }
2152
2153                    /*
2154                     * If the package is scanned, it's not erased.
2155                     */
2156                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2157                    if (scannedPkg != null) {
2158                        /*
2159                         * If the system app is both scanned and in the
2160                         * disabled packages list, then it must have been
2161                         * added via OTA. Remove it from the currently
2162                         * scanned package so the previously user-installed
2163                         * application can be scanned.
2164                         */
2165                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2166                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2167                                    + ps.name + "; removing system app.  Last known codePath="
2168                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2169                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2170                                    + scannedPkg.mVersionCode);
2171                            removePackageLI(ps, true);
2172                            mExpectingBetter.put(ps.name, ps.codePath);
2173                        }
2174
2175                        continue;
2176                    }
2177
2178                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2179                        psit.remove();
2180                        logCriticalInfo(Log.WARN, "System package " + ps.name
2181                                + " no longer exists; wiping its data");
2182                        removeDataDirsLI(null, ps.name);
2183                    } else {
2184                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2185                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2186                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2187                        }
2188                    }
2189                }
2190            }
2191
2192            //look for any incomplete package installations
2193            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2194            //clean up list
2195            for(int i = 0; i < deletePkgsList.size(); i++) {
2196                //clean up here
2197                cleanupInstallFailedPackage(deletePkgsList.get(i));
2198            }
2199            //delete tmp files
2200            deleteTempPackageFiles();
2201
2202            // Remove any shared userIDs that have no associated packages
2203            mSettings.pruneSharedUsersLPw();
2204
2205            if (!mOnlyCore) {
2206                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2207                        SystemClock.uptimeMillis());
2208                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2209
2210                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2211                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2212
2213                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2214                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2215
2216                /**
2217                 * Remove disable package settings for any updated system
2218                 * apps that were removed via an OTA. If they're not a
2219                 * previously-updated app, remove them completely.
2220                 * Otherwise, just revoke their system-level permissions.
2221                 */
2222                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2223                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2224                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2225
2226                    String msg;
2227                    if (deletedPkg == null) {
2228                        msg = "Updated system package " + deletedAppName
2229                                + " no longer exists; wiping its data";
2230                        removeDataDirsLI(null, deletedAppName);
2231                    } else {
2232                        msg = "Updated system app + " + deletedAppName
2233                                + " no longer present; removing system privileges for "
2234                                + deletedAppName;
2235
2236                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2237
2238                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2239                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2240                    }
2241                    logCriticalInfo(Log.WARN, msg);
2242                }
2243
2244                /**
2245                 * Make sure all system apps that we expected to appear on
2246                 * the userdata partition actually showed up. If they never
2247                 * appeared, crawl back and revive the system version.
2248                 */
2249                for (int i = 0; i < mExpectingBetter.size(); i++) {
2250                    final String packageName = mExpectingBetter.keyAt(i);
2251                    if (!mPackages.containsKey(packageName)) {
2252                        final File scanFile = mExpectingBetter.valueAt(i);
2253
2254                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2255                                + " but never showed up; reverting to system");
2256
2257                        final int reparseFlags;
2258                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2259                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2260                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2261                                    | PackageParser.PARSE_IS_PRIVILEGED;
2262                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2269                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2270                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2271                        } else {
2272                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2273                            continue;
2274                        }
2275
2276                        mSettings.enableSystemPackageLPw(packageName);
2277
2278                        try {
2279                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2280                        } catch (PackageManagerException e) {
2281                            Slog.e(TAG, "Failed to parse original system package: "
2282                                    + e.getMessage());
2283                        }
2284                    }
2285                }
2286            }
2287            mExpectingBetter.clear();
2288
2289            // Now that we know all of the shared libraries, update all clients to have
2290            // the correct library paths.
2291            updateAllSharedLibrariesLPw();
2292
2293            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2294                // NOTE: We ignore potential failures here during a system scan (like
2295                // the rest of the commands above) because there's precious little we
2296                // can do about it. A settings error is reported, though.
2297                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2298                        false /* boot complete */);
2299            }
2300
2301            // Now that we know all the packages we are keeping,
2302            // read and update their last usage times.
2303            mPackageUsage.readLP();
2304
2305            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2306                    SystemClock.uptimeMillis());
2307            Slog.i(TAG, "Time to scan packages: "
2308                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2309                    + " seconds");
2310
2311            // If the platform SDK has changed since the last time we booted,
2312            // we need to re-grant app permission to catch any new ones that
2313            // appear.  This is really a hack, and means that apps can in some
2314            // cases get permissions that the user didn't initially explicitly
2315            // allow...  it would be nice to have some better way to handle
2316            // this situation.
2317            int updateFlags = UPDATE_PERMISSIONS_ALL;
2318            if (ver.sdkVersion != mSdkVersion) {
2319                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2320                        + mSdkVersion + "; regranting permissions for internal storage");
2321                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2322            }
2323            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2324            ver.sdkVersion = mSdkVersion;
2325
2326            // If this is the first boot or an update from pre-M, and it is a normal
2327            // boot, then we need to initialize the default preferred apps across
2328            // all defined users.
2329            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2330                for (UserInfo user : sUserManager.getUsers(true)) {
2331                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2332                    applyFactoryDefaultBrowserLPw(user.id);
2333                    primeDomainVerificationsLPw(user.id);
2334                }
2335            }
2336
2337            // If this is first boot after an OTA, and a normal boot, then
2338            // we need to clear code cache directories.
2339            if (mIsUpgrade && !onlyCore) {
2340                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2341                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2342                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2343                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2344                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2345                    }
2346                }
2347                ver.fingerprint = Build.FINGERPRINT;
2348            }
2349
2350            checkDefaultBrowser();
2351
2352            // clear only after permissions and other defaults have been updated
2353            mExistingSystemPackages.clear();
2354            mPromoteSystemApps = false;
2355
2356            // All the changes are done during package scanning.
2357            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2358
2359            // can downgrade to reader
2360            mSettings.writeLPr();
2361
2362            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2363                    SystemClock.uptimeMillis());
2364
2365            mRequiredVerifierPackage = getRequiredVerifierLPr();
2366            mRequiredInstallerPackage = getRequiredInstallerLPr();
2367
2368            mInstallerService = new PackageInstallerService(context, this);
2369
2370            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2371            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2372                    mIntentFilterVerifierComponent);
2373
2374            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2375            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2376            // both the installer and resolver must be present to enable ephemeral
2377            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2378                if (DEBUG_EPHEMERAL) {
2379                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2380                            + " installer:" + ephemeralInstallerComponent);
2381                }
2382                mEphemeralResolverComponent = ephemeralResolverComponent;
2383                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2384                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2385                mEphemeralResolverConnection =
2386                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2387            } else {
2388                if (DEBUG_EPHEMERAL) {
2389                    final String missingComponent =
2390                            (ephemeralResolverComponent == null)
2391                            ? (ephemeralInstallerComponent == null)
2392                                    ? "resolver and installer"
2393                                    : "resolver"
2394                            : "installer";
2395                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2396                }
2397                mEphemeralResolverComponent = null;
2398                mEphemeralInstallerComponent = null;
2399                mEphemeralResolverConnection = null;
2400            }
2401
2402            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2403        } // synchronized (mPackages)
2404        } // synchronized (mInstallLock)
2405
2406        // Now after opening every single application zip, make sure they
2407        // are all flushed.  Not really needed, but keeps things nice and
2408        // tidy.
2409        Runtime.getRuntime().gc();
2410
2411        // The initial scanning above does many calls into installd while
2412        // holding the mPackages lock, but we're mostly interested in yelling
2413        // once we have a booted system.
2414        mInstaller.setWarnIfHeld(mPackages);
2415
2416        // Expose private service for system components to use.
2417        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2418    }
2419
2420    @Override
2421    public boolean isFirstBoot() {
2422        return !mRestoredSettings;
2423    }
2424
2425    @Override
2426    public boolean isOnlyCoreApps() {
2427        return mOnlyCore;
2428    }
2429
2430    @Override
2431    public boolean isUpgrade() {
2432        return mIsUpgrade;
2433    }
2434
2435    private @NonNull String getRequiredVerifierLPr() {
2436        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2437
2438        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2439                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2440        if (matches.size() == 1) {
2441            return matches.get(0).getComponentInfo().packageName;
2442        } else {
2443            throw new RuntimeException("There must be exactly one verifier; found " + matches);
2444        }
2445    }
2446
2447    private @NonNull String getRequiredInstallerLPr() {
2448        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2449        intent.addCategory(Intent.CATEGORY_DEFAULT);
2450        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2451
2452        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2453                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2454        if (matches.size() == 1) {
2455            return matches.get(0).getComponentInfo().packageName;
2456        } else {
2457            throw new RuntimeException("There must be exactly one installer; found " + matches);
2458        }
2459    }
2460
2461    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2462        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2463
2464        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2465                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2466        ResolveInfo best = null;
2467        final int N = matches.size();
2468        for (int i = 0; i < N; i++) {
2469            final ResolveInfo cur = matches.get(i);
2470            final String packageName = cur.getComponentInfo().packageName;
2471            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2472                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2473                continue;
2474            }
2475
2476            if (best == null || cur.priority > best.priority) {
2477                best = cur;
2478            }
2479        }
2480
2481        if (best != null) {
2482            return best.getComponentInfo().getComponentName();
2483        } else {
2484            throw new RuntimeException("There must be at least one intent filter verifier");
2485        }
2486    }
2487
2488    private @Nullable ComponentName getEphemeralResolverLPr() {
2489        final String[] packageArray =
2490                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2491        if (packageArray.length == 0) {
2492            if (DEBUG_EPHEMERAL) {
2493                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2494            }
2495            return null;
2496        }
2497
2498        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2499        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2500                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2501
2502        final int N = resolvers.size();
2503        if (N == 0) {
2504            if (DEBUG_EPHEMERAL) {
2505                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2506            }
2507            return null;
2508        }
2509
2510        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2511        for (int i = 0; i < N; i++) {
2512            final ResolveInfo info = resolvers.get(i);
2513
2514            if (info.serviceInfo == null) {
2515                continue;
2516            }
2517
2518            final String packageName = info.serviceInfo.packageName;
2519            if (!possiblePackages.contains(packageName)) {
2520                if (DEBUG_EPHEMERAL) {
2521                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2522                            + " pkg: " + packageName + ", info:" + info);
2523                }
2524                continue;
2525            }
2526
2527            if (DEBUG_EPHEMERAL) {
2528                Slog.v(TAG, "Ephemeral resolver found;"
2529                        + " pkg: " + packageName + ", info:" + info);
2530            }
2531            return new ComponentName(packageName, info.serviceInfo.name);
2532        }
2533        if (DEBUG_EPHEMERAL) {
2534            Slog.v(TAG, "Ephemeral resolver NOT found");
2535        }
2536        return null;
2537    }
2538
2539    private @Nullable ComponentName getEphemeralInstallerLPr() {
2540        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2541        intent.addCategory(Intent.CATEGORY_DEFAULT);
2542        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2543
2544        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2545                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2546        if (matches.size() == 0) {
2547            return null;
2548        } else if (matches.size() == 1) {
2549            return matches.get(0).getComponentInfo().getComponentName();
2550        } else {
2551            throw new RuntimeException(
2552                    "There must be at most one ephemeral installer; found " + matches);
2553        }
2554    }
2555
2556    private void primeDomainVerificationsLPw(int userId) {
2557        if (DEBUG_DOMAIN_VERIFICATION) {
2558            Slog.d(TAG, "Priming domain verifications in user " + userId);
2559        }
2560
2561        SystemConfig systemConfig = SystemConfig.getInstance();
2562        ArraySet<String> packages = systemConfig.getLinkedApps();
2563        ArraySet<String> domains = new ArraySet<String>();
2564
2565        for (String packageName : packages) {
2566            PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg != null) {
2568                if (!pkg.isSystemApp()) {
2569                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2570                    continue;
2571                }
2572
2573                domains.clear();
2574                for (PackageParser.Activity a : pkg.activities) {
2575                    for (ActivityIntentInfo filter : a.intents) {
2576                        if (hasValidDomains(filter)) {
2577                            domains.addAll(filter.getHostsList());
2578                        }
2579                    }
2580                }
2581
2582                if (domains.size() > 0) {
2583                    if (DEBUG_DOMAIN_VERIFICATION) {
2584                        Slog.v(TAG, "      + " + packageName);
2585                    }
2586                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2587                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2588                    // and then 'always' in the per-user state actually used for intent resolution.
2589                    final IntentFilterVerificationInfo ivi;
2590                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2591                            new ArrayList<String>(domains));
2592                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2593                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2594                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2595                } else {
2596                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2597                            + "' does not handle web links");
2598                }
2599            } else {
2600                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2601            }
2602        }
2603
2604        scheduleWritePackageRestrictionsLocked(userId);
2605        scheduleWriteSettingsLocked();
2606    }
2607
2608    private void applyFactoryDefaultBrowserLPw(int userId) {
2609        // The default browser app's package name is stored in a string resource,
2610        // with a product-specific overlay used for vendor customization.
2611        String browserPkg = mContext.getResources().getString(
2612                com.android.internal.R.string.default_browser);
2613        if (!TextUtils.isEmpty(browserPkg)) {
2614            // non-empty string => required to be a known package
2615            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2616            if (ps == null) {
2617                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2618                browserPkg = null;
2619            } else {
2620                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2621            }
2622        }
2623
2624        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2625        // default.  If there's more than one, just leave everything alone.
2626        if (browserPkg == null) {
2627            calculateDefaultBrowserLPw(userId);
2628        }
2629    }
2630
2631    private void calculateDefaultBrowserLPw(int userId) {
2632        List<String> allBrowsers = resolveAllBrowserApps(userId);
2633        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2634        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2635    }
2636
2637    private List<String> resolveAllBrowserApps(int userId) {
2638        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2639        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2640                PackageManager.MATCH_ALL, userId);
2641
2642        final int count = list.size();
2643        List<String> result = new ArrayList<String>(count);
2644        for (int i=0; i<count; i++) {
2645            ResolveInfo info = list.get(i);
2646            if (info.activityInfo == null
2647                    || !info.handleAllWebDataURI
2648                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2649                    || result.contains(info.activityInfo.packageName)) {
2650                continue;
2651            }
2652            result.add(info.activityInfo.packageName);
2653        }
2654
2655        return result;
2656    }
2657
2658    private boolean packageIsBrowser(String packageName, int userId) {
2659        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2660                PackageManager.MATCH_ALL, userId);
2661        final int N = list.size();
2662        for (int i = 0; i < N; i++) {
2663            ResolveInfo info = list.get(i);
2664            if (packageName.equals(info.activityInfo.packageName)) {
2665                return true;
2666            }
2667        }
2668        return false;
2669    }
2670
2671    private void checkDefaultBrowser() {
2672        final int myUserId = UserHandle.myUserId();
2673        final String packageName = getDefaultBrowserPackageName(myUserId);
2674        if (packageName != null) {
2675            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2676            if (info == null) {
2677                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2678                synchronized (mPackages) {
2679                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2680                }
2681            }
2682        }
2683    }
2684
2685    @Override
2686    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2687            throws RemoteException {
2688        try {
2689            return super.onTransact(code, data, reply, flags);
2690        } catch (RuntimeException e) {
2691            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2692                Slog.wtf(TAG, "Package Manager Crash", e);
2693            }
2694            throw e;
2695        }
2696    }
2697
2698    void cleanupInstallFailedPackage(PackageSetting ps) {
2699        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2700
2701        removeDataDirsLI(ps.volumeUuid, ps.name);
2702        if (ps.codePath != null) {
2703            if (ps.codePath.isDirectory()) {
2704                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2705            } else {
2706                ps.codePath.delete();
2707            }
2708        }
2709        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2710            if (ps.resourcePath.isDirectory()) {
2711                FileUtils.deleteContents(ps.resourcePath);
2712            }
2713            ps.resourcePath.delete();
2714        }
2715        mSettings.removePackageLPw(ps.name);
2716    }
2717
2718    static int[] appendInts(int[] cur, int[] add) {
2719        if (add == null) return cur;
2720        if (cur == null) return add;
2721        final int N = add.length;
2722        for (int i=0; i<N; i++) {
2723            cur = appendInt(cur, add[i]);
2724        }
2725        return cur;
2726    }
2727
2728    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2729        if (!sUserManager.exists(userId)) return null;
2730        final PackageSetting ps = (PackageSetting) p.mExtras;
2731        if (ps == null) {
2732            return null;
2733        }
2734
2735        final PermissionsState permissionsState = ps.getPermissionsState();
2736
2737        final int[] gids = permissionsState.computeGids(userId);
2738        final Set<String> permissions = permissionsState.getPermissions(userId);
2739        final PackageUserState state = ps.readUserState(userId);
2740
2741        return PackageParser.generatePackageInfo(p, gids, flags,
2742                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2743    }
2744
2745    @Override
2746    public void checkPackageStartable(String packageName, int userId) {
2747        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2748
2749        synchronized (mPackages) {
2750            final PackageSetting ps = mSettings.mPackages.get(packageName);
2751            if (ps == null) {
2752                throw new SecurityException("Package " + packageName + " was not found!");
2753            }
2754
2755            if (ps.frozen) {
2756                throw new SecurityException("Package " + packageName + " is currently frozen!");
2757            }
2758
2759            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2760                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2761                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2762            }
2763        }
2764    }
2765
2766    @Override
2767    public boolean isPackageAvailable(String packageName, int userId) {
2768        if (!sUserManager.exists(userId)) return false;
2769        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2770        synchronized (mPackages) {
2771            PackageParser.Package p = mPackages.get(packageName);
2772            if (p != null) {
2773                final PackageSetting ps = (PackageSetting) p.mExtras;
2774                if (ps != null) {
2775                    final PackageUserState state = ps.readUserState(userId);
2776                    if (state != null) {
2777                        return PackageParser.isAvailable(state);
2778                    }
2779                }
2780            }
2781        }
2782        return false;
2783    }
2784
2785    @Override
2786    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2787        if (!sUserManager.exists(userId)) return null;
2788        flags = updateFlagsForPackage(flags, userId, packageName);
2789        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2790        // reader
2791        synchronized (mPackages) {
2792            PackageParser.Package p = mPackages.get(packageName);
2793            if (DEBUG_PACKAGE_INFO)
2794                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2795            if (p != null) {
2796                return generatePackageInfo(p, flags, userId);
2797            }
2798            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2799                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2800            }
2801        }
2802        return null;
2803    }
2804
2805    @Override
2806    public String[] currentToCanonicalPackageNames(String[] names) {
2807        String[] out = new String[names.length];
2808        // reader
2809        synchronized (mPackages) {
2810            for (int i=names.length-1; i>=0; i--) {
2811                PackageSetting ps = mSettings.mPackages.get(names[i]);
2812                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2813            }
2814        }
2815        return out;
2816    }
2817
2818    @Override
2819    public String[] canonicalToCurrentPackageNames(String[] names) {
2820        String[] out = new String[names.length];
2821        // reader
2822        synchronized (mPackages) {
2823            for (int i=names.length-1; i>=0; i--) {
2824                String cur = mSettings.mRenamedPackages.get(names[i]);
2825                out[i] = cur != null ? cur : names[i];
2826            }
2827        }
2828        return out;
2829    }
2830
2831    @Override
2832    public int getPackageUid(String packageName, int userId) {
2833        return getPackageUidEtc(packageName, 0, userId);
2834    }
2835
2836    @Override
2837    public int getPackageUidEtc(String packageName, int flags, int userId) {
2838        if (!sUserManager.exists(userId)) return -1;
2839        flags = updateFlagsForPackage(flags, userId, packageName);
2840        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2841
2842        // reader
2843        synchronized (mPackages) {
2844            final PackageParser.Package p = mPackages.get(packageName);
2845            if (p != null) {
2846                return UserHandle.getUid(userId, p.applicationInfo.uid);
2847            }
2848            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2849                final PackageSetting ps = mSettings.mPackages.get(packageName);
2850                if (ps != null) {
2851                    return UserHandle.getUid(userId, ps.appId);
2852                }
2853            }
2854        }
2855
2856        return -1;
2857    }
2858
2859    @Override
2860    public int[] getPackageGids(String packageName, int userId) {
2861        return getPackageGidsEtc(packageName, 0, userId);
2862    }
2863
2864    @Override
2865    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2866        if (!sUserManager.exists(userId)) return null;
2867        flags = updateFlagsForPackage(flags, userId, packageName);
2868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2869                "getPackageGids");
2870
2871        // reader
2872        synchronized (mPackages) {
2873            final PackageParser.Package p = mPackages.get(packageName);
2874            if (p != null) {
2875                PackageSetting ps = (PackageSetting) p.mExtras;
2876                return ps.getPermissionsState().computeGids(userId);
2877            }
2878            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2879                final PackageSetting ps = mSettings.mPackages.get(packageName);
2880                if (ps != null) {
2881                    return ps.getPermissionsState().computeGids(userId);
2882                }
2883            }
2884        }
2885
2886        return null;
2887    }
2888
2889    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2890        if (bp.perm != null) {
2891            return PackageParser.generatePermissionInfo(bp.perm, flags);
2892        }
2893        PermissionInfo pi = new PermissionInfo();
2894        pi.name = bp.name;
2895        pi.packageName = bp.sourcePackage;
2896        pi.nonLocalizedLabel = bp.name;
2897        pi.protectionLevel = bp.protectionLevel;
2898        return pi;
2899    }
2900
2901    @Override
2902    public PermissionInfo getPermissionInfo(String name, int flags) {
2903        // reader
2904        synchronized (mPackages) {
2905            final BasePermission p = mSettings.mPermissions.get(name);
2906            if (p != null) {
2907                return generatePermissionInfo(p, flags);
2908            }
2909            return null;
2910        }
2911    }
2912
2913    @Override
2914    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2915        // reader
2916        synchronized (mPackages) {
2917            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2918            for (BasePermission p : mSettings.mPermissions.values()) {
2919                if (group == null) {
2920                    if (p.perm == null || p.perm.info.group == null) {
2921                        out.add(generatePermissionInfo(p, flags));
2922                    }
2923                } else {
2924                    if (p.perm != null && group.equals(p.perm.info.group)) {
2925                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2926                    }
2927                }
2928            }
2929
2930            if (out.size() > 0) {
2931                return out;
2932            }
2933            return mPermissionGroups.containsKey(group) ? out : null;
2934        }
2935    }
2936
2937    @Override
2938    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2939        // reader
2940        synchronized (mPackages) {
2941            return PackageParser.generatePermissionGroupInfo(
2942                    mPermissionGroups.get(name), flags);
2943        }
2944    }
2945
2946    @Override
2947    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2948        // reader
2949        synchronized (mPackages) {
2950            final int N = mPermissionGroups.size();
2951            ArrayList<PermissionGroupInfo> out
2952                    = new ArrayList<PermissionGroupInfo>(N);
2953            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2954                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2955            }
2956            return out;
2957        }
2958    }
2959
2960    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2961            int userId) {
2962        if (!sUserManager.exists(userId)) return null;
2963        PackageSetting ps = mSettings.mPackages.get(packageName);
2964        if (ps != null) {
2965            if (ps.pkg == null) {
2966                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2967                        flags, userId);
2968                if (pInfo != null) {
2969                    return pInfo.applicationInfo;
2970                }
2971                return null;
2972            }
2973            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2974                    ps.readUserState(userId), userId);
2975        }
2976        return null;
2977    }
2978
2979    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2980            int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        PackageSetting ps = mSettings.mPackages.get(packageName);
2983        if (ps != null) {
2984            PackageParser.Package pkg = ps.pkg;
2985            if (pkg == null) {
2986                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2987                    return null;
2988                }
2989                // Only data remains, so we aren't worried about code paths
2990                pkg = new PackageParser.Package(packageName);
2991                pkg.applicationInfo.packageName = packageName;
2992                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2993                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2994                pkg.applicationInfo.uid = ps.appId;
2995                pkg.applicationInfo.initForUser(userId);
2996                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2997                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2998            }
2999            return generatePackageInfo(pkg, flags, userId);
3000        }
3001        return null;
3002    }
3003
3004    @Override
3005    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        flags = updateFlagsForApplication(flags, userId, packageName);
3008        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3009        // writer
3010        synchronized (mPackages) {
3011            PackageParser.Package p = mPackages.get(packageName);
3012            if (DEBUG_PACKAGE_INFO) Log.v(
3013                    TAG, "getApplicationInfo " + packageName
3014                    + ": " + p);
3015            if (p != null) {
3016                PackageSetting ps = mSettings.mPackages.get(packageName);
3017                if (ps == null) return null;
3018                // Note: isEnabledLP() does not apply here - always return info
3019                return PackageParser.generateApplicationInfo(
3020                        p, flags, ps.readUserState(userId), userId);
3021            }
3022            if ("android".equals(packageName)||"system".equals(packageName)) {
3023                return mAndroidApplication;
3024            }
3025            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3026                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3034            final IPackageDataObserver observer) {
3035        mContext.enforceCallingOrSelfPermission(
3036                android.Manifest.permission.CLEAR_APP_CACHE, null);
3037        // Queue up an async operation since clearing cache may take a little while.
3038        mHandler.post(new Runnable() {
3039            public void run() {
3040                mHandler.removeCallbacks(this);
3041                int retCode = -1;
3042                synchronized (mInstallLock) {
3043                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3044                    if (retCode < 0) {
3045                        Slog.w(TAG, "Couldn't clear application caches");
3046                    }
3047                }
3048                if (observer != null) {
3049                    try {
3050                        observer.onRemoveCompleted(null, (retCode >= 0));
3051                    } catch (RemoteException e) {
3052                        Slog.w(TAG, "RemoveException when invoking call back");
3053                    }
3054                }
3055            }
3056        });
3057    }
3058
3059    @Override
3060    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3061            final IntentSender pi) {
3062        mContext.enforceCallingOrSelfPermission(
3063                android.Manifest.permission.CLEAR_APP_CACHE, null);
3064        // Queue up an async operation since clearing cache may take a little while.
3065        mHandler.post(new Runnable() {
3066            public void run() {
3067                mHandler.removeCallbacks(this);
3068                int retCode = -1;
3069                synchronized (mInstallLock) {
3070                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3071                    if (retCode < 0) {
3072                        Slog.w(TAG, "Couldn't clear application caches");
3073                    }
3074                }
3075                if(pi != null) {
3076                    try {
3077                        // Callback via pending intent
3078                        int code = (retCode >= 0) ? 1 : 0;
3079                        pi.sendIntent(null, code, null,
3080                                null, null);
3081                    } catch (SendIntentException e1) {
3082                        Slog.i(TAG, "Failed to send pending intent");
3083                    }
3084                }
3085            }
3086        });
3087    }
3088
3089    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3090        synchronized (mInstallLock) {
3091            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3092                throw new IOException("Failed to free enough space");
3093            }
3094        }
3095    }
3096
3097    /**
3098     * Return if the user key is currently unlocked.
3099     */
3100    private boolean isUserKeyUnlocked(int userId) {
3101        if (StorageManager.isFileBasedEncryptionEnabled()) {
3102            final IMountService mount = IMountService.Stub
3103                    .asInterface(ServiceManager.getService("mount"));
3104            if (mount == null) {
3105                Slog.w(TAG, "Early during boot, assuming locked");
3106                return false;
3107            }
3108            final long token = Binder.clearCallingIdentity();
3109            try {
3110                return mount.isUserKeyUnlocked(userId);
3111            } catch (RemoteException e) {
3112                throw e.rethrowAsRuntimeException();
3113            } finally {
3114                Binder.restoreCallingIdentity(token);
3115            }
3116        } else {
3117            return true;
3118        }
3119    }
3120
3121    /**
3122     * Update given flags based on encryption status of current user.
3123     */
3124    private int updateFlagsForEncryption(int flags, int userId) {
3125        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3126                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3127            // Caller expressed an explicit opinion about what encryption
3128            // aware/unaware components they want to see, so fall through and
3129            // give them what they want
3130        } else {
3131            // Caller expressed no opinion, so match based on user state
3132            if (isUserKeyUnlocked(userId)) {
3133                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3134            } else {
3135                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3136            }
3137        }
3138        return flags;
3139    }
3140
3141    /**
3142     * Update given flags when being used to request {@link PackageInfo}.
3143     */
3144    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3145        boolean triaged = true;
3146        if ((flags & PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3147                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS) != 0) {
3148            // Caller is asking for component details, so they'd better be
3149            // asking for specific encryption matching behavior, or be triaged
3150            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3151                    | PackageManager.MATCH_ENCRYPTION_AWARE
3152                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3153                triaged = false;
3154            }
3155        }
3156        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3157                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3158            triaged = false;
3159        }
3160        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3161            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3162                    new Throwable());
3163        }
3164        return updateFlagsForEncryption(flags, userId);
3165    }
3166
3167    /**
3168     * Update given flags when being used to request {@link ApplicationInfo}.
3169     */
3170    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3171        return updateFlagsForPackage(flags, userId, cookie);
3172    }
3173
3174    /**
3175     * Update given flags when being used to request {@link ComponentInfo}.
3176     */
3177    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3178        boolean triaged = true;
3179        // Caller is asking for component details, so they'd better be
3180        // asking for specific encryption matching behavior, or be triaged
3181        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3182                | PackageManager.MATCH_ENCRYPTION_AWARE
3183                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3184            triaged = false;
3185        }
3186        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3187            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3188                    new Throwable());
3189        }
3190        return updateFlagsForEncryption(flags, userId);
3191    }
3192
3193    /**
3194     * Update given flags when being used to request {@link ResolveInfo}.
3195     */
3196    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3197        return updateFlagsForComponent(flags, userId, cookie);
3198    }
3199
3200    @Override
3201    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3202        if (!sUserManager.exists(userId)) return null;
3203        flags = updateFlagsForComponent(flags, userId, component);
3204        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3205        synchronized (mPackages) {
3206            PackageParser.Activity a = mActivities.mActivities.get(component);
3207
3208            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3209            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3210                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3211                if (ps == null) return null;
3212                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3213                        userId);
3214            }
3215            if (mResolveComponentName.equals(component)) {
3216                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3217                        new PackageUserState(), userId);
3218            }
3219        }
3220        return null;
3221    }
3222
3223    @Override
3224    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3225            String resolvedType) {
3226        synchronized (mPackages) {
3227            if (component.equals(mResolveComponentName)) {
3228                // The resolver supports EVERYTHING!
3229                return true;
3230            }
3231            PackageParser.Activity a = mActivities.mActivities.get(component);
3232            if (a == null) {
3233                return false;
3234            }
3235            for (int i=0; i<a.intents.size(); i++) {
3236                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3237                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3238                    return true;
3239                }
3240            }
3241            return false;
3242        }
3243    }
3244
3245    @Override
3246    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3247        if (!sUserManager.exists(userId)) return null;
3248        flags = updateFlagsForComponent(flags, userId, component);
3249        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3250        synchronized (mPackages) {
3251            PackageParser.Activity a = mReceivers.mActivities.get(component);
3252            if (DEBUG_PACKAGE_INFO) Log.v(
3253                TAG, "getReceiverInfo " + component + ": " + a);
3254            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3255                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3256                if (ps == null) return null;
3257                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3258                        userId);
3259            }
3260        }
3261        return null;
3262    }
3263
3264    @Override
3265    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3266        if (!sUserManager.exists(userId)) return null;
3267        flags = updateFlagsForComponent(flags, userId, component);
3268        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3269        synchronized (mPackages) {
3270            PackageParser.Service s = mServices.mServices.get(component);
3271            if (DEBUG_PACKAGE_INFO) Log.v(
3272                TAG, "getServiceInfo " + component + ": " + s);
3273            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3274                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3275                if (ps == null) return null;
3276                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3277                        userId);
3278            }
3279        }
3280        return null;
3281    }
3282
3283    @Override
3284    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3285        if (!sUserManager.exists(userId)) return null;
3286        flags = updateFlagsForComponent(flags, userId, component);
3287        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3288        synchronized (mPackages) {
3289            PackageParser.Provider p = mProviders.mProviders.get(component);
3290            if (DEBUG_PACKAGE_INFO) Log.v(
3291                TAG, "getProviderInfo " + component + ": " + p);
3292            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3293                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3294                if (ps == null) return null;
3295                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3296                        userId);
3297            }
3298        }
3299        return null;
3300    }
3301
3302    @Override
3303    public String[] getSystemSharedLibraryNames() {
3304        Set<String> libSet;
3305        synchronized (mPackages) {
3306            libSet = mSharedLibraries.keySet();
3307            int size = libSet.size();
3308            if (size > 0) {
3309                String[] libs = new String[size];
3310                libSet.toArray(libs);
3311                return libs;
3312            }
3313        }
3314        return null;
3315    }
3316
3317    /**
3318     * @hide
3319     */
3320    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3321        synchronized (mPackages) {
3322            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3323            if (lib != null && lib.apk != null) {
3324                return mPackages.get(lib.apk);
3325            }
3326        }
3327        return null;
3328    }
3329
3330    @Override
3331    public FeatureInfo[] getSystemAvailableFeatures() {
3332        Collection<FeatureInfo> featSet;
3333        synchronized (mPackages) {
3334            featSet = mAvailableFeatures.values();
3335            int size = featSet.size();
3336            if (size > 0) {
3337                FeatureInfo[] features = new FeatureInfo[size+1];
3338                featSet.toArray(features);
3339                FeatureInfo fi = new FeatureInfo();
3340                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3341                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3342                features[size] = fi;
3343                return features;
3344            }
3345        }
3346        return null;
3347    }
3348
3349    @Override
3350    public boolean hasSystemFeature(String name) {
3351        synchronized (mPackages) {
3352            return mAvailableFeatures.containsKey(name);
3353        }
3354    }
3355
3356    @Override
3357    public int checkPermission(String permName, String pkgName, int userId) {
3358        if (!sUserManager.exists(userId)) {
3359            return PackageManager.PERMISSION_DENIED;
3360        }
3361
3362        synchronized (mPackages) {
3363            final PackageParser.Package p = mPackages.get(pkgName);
3364            if (p != null && p.mExtras != null) {
3365                final PackageSetting ps = (PackageSetting) p.mExtras;
3366                final PermissionsState permissionsState = ps.getPermissionsState();
3367                if (permissionsState.hasPermission(permName, userId)) {
3368                    return PackageManager.PERMISSION_GRANTED;
3369                }
3370                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3371                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3372                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3373                    return PackageManager.PERMISSION_GRANTED;
3374                }
3375            }
3376        }
3377
3378        return PackageManager.PERMISSION_DENIED;
3379    }
3380
3381    @Override
3382    public int checkUidPermission(String permName, int uid) {
3383        final int userId = UserHandle.getUserId(uid);
3384
3385        if (!sUserManager.exists(userId)) {
3386            return PackageManager.PERMISSION_DENIED;
3387        }
3388
3389        synchronized (mPackages) {
3390            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3391            if (obj != null) {
3392                final SettingBase ps = (SettingBase) obj;
3393                final PermissionsState permissionsState = ps.getPermissionsState();
3394                if (permissionsState.hasPermission(permName, userId)) {
3395                    return PackageManager.PERMISSION_GRANTED;
3396                }
3397                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3398                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3399                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3400                    return PackageManager.PERMISSION_GRANTED;
3401                }
3402            } else {
3403                ArraySet<String> perms = mSystemPermissions.get(uid);
3404                if (perms != null) {
3405                    if (perms.contains(permName)) {
3406                        return PackageManager.PERMISSION_GRANTED;
3407                    }
3408                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3409                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3410                        return PackageManager.PERMISSION_GRANTED;
3411                    }
3412                }
3413            }
3414        }
3415
3416        return PackageManager.PERMISSION_DENIED;
3417    }
3418
3419    @Override
3420    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3421        if (UserHandle.getCallingUserId() != userId) {
3422            mContext.enforceCallingPermission(
3423                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3424                    "isPermissionRevokedByPolicy for user " + userId);
3425        }
3426
3427        if (checkPermission(permission, packageName, userId)
3428                == PackageManager.PERMISSION_GRANTED) {
3429            return false;
3430        }
3431
3432        final long identity = Binder.clearCallingIdentity();
3433        try {
3434            final int flags = getPermissionFlags(permission, packageName, userId);
3435            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3436        } finally {
3437            Binder.restoreCallingIdentity(identity);
3438        }
3439    }
3440
3441    @Override
3442    public String getPermissionControllerPackageName() {
3443        synchronized (mPackages) {
3444            return mRequiredInstallerPackage;
3445        }
3446    }
3447
3448    /**
3449     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3450     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3451     * @param checkShell TODO(yamasani):
3452     * @param message the message to log on security exception
3453     */
3454    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3455            boolean checkShell, String message) {
3456        if (userId < 0) {
3457            throw new IllegalArgumentException("Invalid userId " + userId);
3458        }
3459        if (checkShell) {
3460            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3461        }
3462        if (userId == UserHandle.getUserId(callingUid)) return;
3463        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3464            if (requireFullPermission) {
3465                mContext.enforceCallingOrSelfPermission(
3466                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3467            } else {
3468                try {
3469                    mContext.enforceCallingOrSelfPermission(
3470                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3471                } catch (SecurityException se) {
3472                    mContext.enforceCallingOrSelfPermission(
3473                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3474                }
3475            }
3476        }
3477    }
3478
3479    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3480        if (callingUid == Process.SHELL_UID) {
3481            if (userHandle >= 0
3482                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3483                throw new SecurityException("Shell does not have permission to access user "
3484                        + userHandle);
3485            } else if (userHandle < 0) {
3486                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3487                        + Debug.getCallers(3));
3488            }
3489        }
3490    }
3491
3492    private BasePermission findPermissionTreeLP(String permName) {
3493        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3494            if (permName.startsWith(bp.name) &&
3495                    permName.length() > bp.name.length() &&
3496                    permName.charAt(bp.name.length()) == '.') {
3497                return bp;
3498            }
3499        }
3500        return null;
3501    }
3502
3503    private BasePermission checkPermissionTreeLP(String permName) {
3504        if (permName != null) {
3505            BasePermission bp = findPermissionTreeLP(permName);
3506            if (bp != null) {
3507                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3508                    return bp;
3509                }
3510                throw new SecurityException("Calling uid "
3511                        + Binder.getCallingUid()
3512                        + " is not allowed to add to permission tree "
3513                        + bp.name + " owned by uid " + bp.uid);
3514            }
3515        }
3516        throw new SecurityException("No permission tree found for " + permName);
3517    }
3518
3519    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3520        if (s1 == null) {
3521            return s2 == null;
3522        }
3523        if (s2 == null) {
3524            return false;
3525        }
3526        if (s1.getClass() != s2.getClass()) {
3527            return false;
3528        }
3529        return s1.equals(s2);
3530    }
3531
3532    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3533        if (pi1.icon != pi2.icon) return false;
3534        if (pi1.logo != pi2.logo) return false;
3535        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3536        if (!compareStrings(pi1.name, pi2.name)) return false;
3537        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3538        // We'll take care of setting this one.
3539        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3540        // These are not currently stored in settings.
3541        //if (!compareStrings(pi1.group, pi2.group)) return false;
3542        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3543        //if (pi1.labelRes != pi2.labelRes) return false;
3544        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3545        return true;
3546    }
3547
3548    int permissionInfoFootprint(PermissionInfo info) {
3549        int size = info.name.length();
3550        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3551        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3552        return size;
3553    }
3554
3555    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3556        int size = 0;
3557        for (BasePermission perm : mSettings.mPermissions.values()) {
3558            if (perm.uid == tree.uid) {
3559                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3560            }
3561        }
3562        return size;
3563    }
3564
3565    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3566        // We calculate the max size of permissions defined by this uid and throw
3567        // if that plus the size of 'info' would exceed our stated maximum.
3568        if (tree.uid != Process.SYSTEM_UID) {
3569            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3570            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3571                throw new SecurityException("Permission tree size cap exceeded");
3572            }
3573        }
3574    }
3575
3576    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3577        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3578            throw new SecurityException("Label must be specified in permission");
3579        }
3580        BasePermission tree = checkPermissionTreeLP(info.name);
3581        BasePermission bp = mSettings.mPermissions.get(info.name);
3582        boolean added = bp == null;
3583        boolean changed = true;
3584        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3585        if (added) {
3586            enforcePermissionCapLocked(info, tree);
3587            bp = new BasePermission(info.name, tree.sourcePackage,
3588                    BasePermission.TYPE_DYNAMIC);
3589        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3590            throw new SecurityException(
3591                    "Not allowed to modify non-dynamic permission "
3592                    + info.name);
3593        } else {
3594            if (bp.protectionLevel == fixedLevel
3595                    && bp.perm.owner.equals(tree.perm.owner)
3596                    && bp.uid == tree.uid
3597                    && comparePermissionInfos(bp.perm.info, info)) {
3598                changed = false;
3599            }
3600        }
3601        bp.protectionLevel = fixedLevel;
3602        info = new PermissionInfo(info);
3603        info.protectionLevel = fixedLevel;
3604        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3605        bp.perm.info.packageName = tree.perm.info.packageName;
3606        bp.uid = tree.uid;
3607        if (added) {
3608            mSettings.mPermissions.put(info.name, bp);
3609        }
3610        if (changed) {
3611            if (!async) {
3612                mSettings.writeLPr();
3613            } else {
3614                scheduleWriteSettingsLocked();
3615            }
3616        }
3617        return added;
3618    }
3619
3620    @Override
3621    public boolean addPermission(PermissionInfo info) {
3622        synchronized (mPackages) {
3623            return addPermissionLocked(info, false);
3624        }
3625    }
3626
3627    @Override
3628    public boolean addPermissionAsync(PermissionInfo info) {
3629        synchronized (mPackages) {
3630            return addPermissionLocked(info, true);
3631        }
3632    }
3633
3634    @Override
3635    public void removePermission(String name) {
3636        synchronized (mPackages) {
3637            checkPermissionTreeLP(name);
3638            BasePermission bp = mSettings.mPermissions.get(name);
3639            if (bp != null) {
3640                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3641                    throw new SecurityException(
3642                            "Not allowed to modify non-dynamic permission "
3643                            + name);
3644                }
3645                mSettings.mPermissions.remove(name);
3646                mSettings.writeLPr();
3647            }
3648        }
3649    }
3650
3651    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3652            BasePermission bp) {
3653        int index = pkg.requestedPermissions.indexOf(bp.name);
3654        if (index == -1) {
3655            throw new SecurityException("Package " + pkg.packageName
3656                    + " has not requested permission " + bp.name);
3657        }
3658        if (!bp.isRuntime() && !bp.isDevelopment()) {
3659            throw new SecurityException("Permission " + bp.name
3660                    + " is not a changeable permission type");
3661        }
3662    }
3663
3664    @Override
3665    public void grantRuntimePermission(String packageName, String name, final int userId) {
3666        if (!sUserManager.exists(userId)) {
3667            Log.e(TAG, "No such user:" + userId);
3668            return;
3669        }
3670
3671        mContext.enforceCallingOrSelfPermission(
3672                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3673                "grantRuntimePermission");
3674
3675        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3676                "grantRuntimePermission");
3677
3678        final int uid;
3679        final SettingBase sb;
3680
3681        synchronized (mPackages) {
3682            final PackageParser.Package pkg = mPackages.get(packageName);
3683            if (pkg == null) {
3684                throw new IllegalArgumentException("Unknown package: " + packageName);
3685            }
3686
3687            final BasePermission bp = mSettings.mPermissions.get(name);
3688            if (bp == null) {
3689                throw new IllegalArgumentException("Unknown permission: " + name);
3690            }
3691
3692            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3693
3694            // If a permission review is required for legacy apps we represent
3695            // their permissions as always granted runtime ones since we need
3696            // to keep the review required permission flag per user while an
3697            // install permission's state is shared across all users.
3698            if (Build.PERMISSIONS_REVIEW_REQUIRED
3699                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3700                    && bp.isRuntime()) {
3701                return;
3702            }
3703
3704            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3705            sb = (SettingBase) pkg.mExtras;
3706            if (sb == null) {
3707                throw new IllegalArgumentException("Unknown package: " + packageName);
3708            }
3709
3710            final PermissionsState permissionsState = sb.getPermissionsState();
3711
3712            final int flags = permissionsState.getPermissionFlags(name, userId);
3713            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3714                throw new SecurityException("Cannot grant system fixed permission "
3715                        + name + " for package " + packageName);
3716            }
3717
3718            if (bp.isDevelopment()) {
3719                // Development permissions must be handled specially, since they are not
3720                // normal runtime permissions.  For now they apply to all users.
3721                if (permissionsState.grantInstallPermission(bp) !=
3722                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3723                    scheduleWriteSettingsLocked();
3724                }
3725                return;
3726            }
3727
3728            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3729                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3730                return;
3731            }
3732
3733            final int result = permissionsState.grantRuntimePermission(bp, userId);
3734            switch (result) {
3735                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3736                    return;
3737                }
3738
3739                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3740                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3741                    mHandler.post(new Runnable() {
3742                        @Override
3743                        public void run() {
3744                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3745                        }
3746                    });
3747                }
3748                break;
3749            }
3750
3751            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3752
3753            // Not critical if that is lost - app has to request again.
3754            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3755        }
3756
3757        // Only need to do this if user is initialized. Otherwise it's a new user
3758        // and there are no processes running as the user yet and there's no need
3759        // to make an expensive call to remount processes for the changed permissions.
3760        if (READ_EXTERNAL_STORAGE.equals(name)
3761                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3762            final long token = Binder.clearCallingIdentity();
3763            try {
3764                if (sUserManager.isInitialized(userId)) {
3765                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3766                            MountServiceInternal.class);
3767                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3768                }
3769            } finally {
3770                Binder.restoreCallingIdentity(token);
3771            }
3772        }
3773    }
3774
3775    @Override
3776    public void revokeRuntimePermission(String packageName, String name, int userId) {
3777        if (!sUserManager.exists(userId)) {
3778            Log.e(TAG, "No such user:" + userId);
3779            return;
3780        }
3781
3782        mContext.enforceCallingOrSelfPermission(
3783                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3784                "revokeRuntimePermission");
3785
3786        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3787                "revokeRuntimePermission");
3788
3789        final int appId;
3790
3791        synchronized (mPackages) {
3792            final PackageParser.Package pkg = mPackages.get(packageName);
3793            if (pkg == null) {
3794                throw new IllegalArgumentException("Unknown package: " + packageName);
3795            }
3796
3797            final BasePermission bp = mSettings.mPermissions.get(name);
3798            if (bp == null) {
3799                throw new IllegalArgumentException("Unknown permission: " + name);
3800            }
3801
3802            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3803
3804            // If a permission review is required for legacy apps we represent
3805            // their permissions as always granted runtime ones since we need
3806            // to keep the review required permission flag per user while an
3807            // install permission's state is shared across all users.
3808            if (Build.PERMISSIONS_REVIEW_REQUIRED
3809                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3810                    && bp.isRuntime()) {
3811                return;
3812            }
3813
3814            SettingBase sb = (SettingBase) pkg.mExtras;
3815            if (sb == null) {
3816                throw new IllegalArgumentException("Unknown package: " + packageName);
3817            }
3818
3819            final PermissionsState permissionsState = sb.getPermissionsState();
3820
3821            final int flags = permissionsState.getPermissionFlags(name, userId);
3822            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3823                throw new SecurityException("Cannot revoke system fixed permission "
3824                        + name + " for package " + packageName);
3825            }
3826
3827            if (bp.isDevelopment()) {
3828                // Development permissions must be handled specially, since they are not
3829                // normal runtime permissions.  For now they apply to all users.
3830                if (permissionsState.revokeInstallPermission(bp) !=
3831                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3832                    scheduleWriteSettingsLocked();
3833                }
3834                return;
3835            }
3836
3837            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3838                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3839                return;
3840            }
3841
3842            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3843
3844            // Critical, after this call app should never have the permission.
3845            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3846
3847            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3848        }
3849
3850        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3851    }
3852
3853    @Override
3854    public void resetRuntimePermissions() {
3855        mContext.enforceCallingOrSelfPermission(
3856                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3857                "revokeRuntimePermission");
3858
3859        int callingUid = Binder.getCallingUid();
3860        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3861            mContext.enforceCallingOrSelfPermission(
3862                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3863                    "resetRuntimePermissions");
3864        }
3865
3866        synchronized (mPackages) {
3867            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3868            for (int userId : UserManagerService.getInstance().getUserIds()) {
3869                final int packageCount = mPackages.size();
3870                for (int i = 0; i < packageCount; i++) {
3871                    PackageParser.Package pkg = mPackages.valueAt(i);
3872                    if (!(pkg.mExtras instanceof PackageSetting)) {
3873                        continue;
3874                    }
3875                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3876                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3877                }
3878            }
3879        }
3880    }
3881
3882    @Override
3883    public int getPermissionFlags(String name, String packageName, int userId) {
3884        if (!sUserManager.exists(userId)) {
3885            return 0;
3886        }
3887
3888        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3889
3890        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3891                "getPermissionFlags");
3892
3893        synchronized (mPackages) {
3894            final PackageParser.Package pkg = mPackages.get(packageName);
3895            if (pkg == null) {
3896                throw new IllegalArgumentException("Unknown package: " + packageName);
3897            }
3898
3899            final BasePermission bp = mSettings.mPermissions.get(name);
3900            if (bp == null) {
3901                throw new IllegalArgumentException("Unknown permission: " + name);
3902            }
3903
3904            SettingBase sb = (SettingBase) pkg.mExtras;
3905            if (sb == null) {
3906                throw new IllegalArgumentException("Unknown package: " + packageName);
3907            }
3908
3909            PermissionsState permissionsState = sb.getPermissionsState();
3910            return permissionsState.getPermissionFlags(name, userId);
3911        }
3912    }
3913
3914    @Override
3915    public void updatePermissionFlags(String name, String packageName, int flagMask,
3916            int flagValues, int userId) {
3917        if (!sUserManager.exists(userId)) {
3918            return;
3919        }
3920
3921        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3922
3923        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3924                "updatePermissionFlags");
3925
3926        // Only the system can change these flags and nothing else.
3927        if (getCallingUid() != Process.SYSTEM_UID) {
3928            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3929            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3930            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3931            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3932            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3933        }
3934
3935        synchronized (mPackages) {
3936            final PackageParser.Package pkg = mPackages.get(packageName);
3937            if (pkg == null) {
3938                throw new IllegalArgumentException("Unknown package: " + packageName);
3939            }
3940
3941            final BasePermission bp = mSettings.mPermissions.get(name);
3942            if (bp == null) {
3943                throw new IllegalArgumentException("Unknown permission: " + name);
3944            }
3945
3946            SettingBase sb = (SettingBase) pkg.mExtras;
3947            if (sb == null) {
3948                throw new IllegalArgumentException("Unknown package: " + packageName);
3949            }
3950
3951            PermissionsState permissionsState = sb.getPermissionsState();
3952
3953            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3954
3955            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3956                // Install and runtime permissions are stored in different places,
3957                // so figure out what permission changed and persist the change.
3958                if (permissionsState.getInstallPermissionState(name) != null) {
3959                    scheduleWriteSettingsLocked();
3960                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3961                        || hadState) {
3962                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3963                }
3964            }
3965        }
3966    }
3967
3968    /**
3969     * Update the permission flags for all packages and runtime permissions of a user in order
3970     * to allow device or profile owner to remove POLICY_FIXED.
3971     */
3972    @Override
3973    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3974        if (!sUserManager.exists(userId)) {
3975            return;
3976        }
3977
3978        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3979
3980        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3981                "updatePermissionFlagsForAllApps");
3982
3983        // Only the system can change system fixed flags.
3984        if (getCallingUid() != Process.SYSTEM_UID) {
3985            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3986            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3987        }
3988
3989        synchronized (mPackages) {
3990            boolean changed = false;
3991            final int packageCount = mPackages.size();
3992            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3993                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3994                SettingBase sb = (SettingBase) pkg.mExtras;
3995                if (sb == null) {
3996                    continue;
3997                }
3998                PermissionsState permissionsState = sb.getPermissionsState();
3999                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4000                        userId, flagMask, flagValues);
4001            }
4002            if (changed) {
4003                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4004            }
4005        }
4006    }
4007
4008    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4009        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4010                != PackageManager.PERMISSION_GRANTED
4011            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4012                != PackageManager.PERMISSION_GRANTED) {
4013            throw new SecurityException(message + " requires "
4014                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4015                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4016        }
4017    }
4018
4019    @Override
4020    public boolean shouldShowRequestPermissionRationale(String permissionName,
4021            String packageName, int userId) {
4022        if (UserHandle.getCallingUserId() != userId) {
4023            mContext.enforceCallingPermission(
4024                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4025                    "canShowRequestPermissionRationale for user " + userId);
4026        }
4027
4028        final int uid = getPackageUid(packageName, userId);
4029        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4030            return false;
4031        }
4032
4033        if (checkPermission(permissionName, packageName, userId)
4034                == PackageManager.PERMISSION_GRANTED) {
4035            return false;
4036        }
4037
4038        final int flags;
4039
4040        final long identity = Binder.clearCallingIdentity();
4041        try {
4042            flags = getPermissionFlags(permissionName,
4043                    packageName, userId);
4044        } finally {
4045            Binder.restoreCallingIdentity(identity);
4046        }
4047
4048        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4049                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4050                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4051
4052        if ((flags & fixedFlags) != 0) {
4053            return false;
4054        }
4055
4056        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4057    }
4058
4059    @Override
4060    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4061        mContext.enforceCallingOrSelfPermission(
4062                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4063                "addOnPermissionsChangeListener");
4064
4065        synchronized (mPackages) {
4066            mOnPermissionChangeListeners.addListenerLocked(listener);
4067        }
4068    }
4069
4070    @Override
4071    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4072        synchronized (mPackages) {
4073            mOnPermissionChangeListeners.removeListenerLocked(listener);
4074        }
4075    }
4076
4077    @Override
4078    public boolean isProtectedBroadcast(String actionName) {
4079        synchronized (mPackages) {
4080            if (mProtectedBroadcasts.contains(actionName)) {
4081                return true;
4082            } else if (actionName != null) {
4083                // TODO: remove these terrible hacks
4084                if (actionName.startsWith("android.net.netmon.lingerExpired")
4085                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4086                    return true;
4087                }
4088            }
4089        }
4090        return false;
4091    }
4092
4093    @Override
4094    public int checkSignatures(String pkg1, String pkg2) {
4095        synchronized (mPackages) {
4096            final PackageParser.Package p1 = mPackages.get(pkg1);
4097            final PackageParser.Package p2 = mPackages.get(pkg2);
4098            if (p1 == null || p1.mExtras == null
4099                    || p2 == null || p2.mExtras == null) {
4100                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4101            }
4102            return compareSignatures(p1.mSignatures, p2.mSignatures);
4103        }
4104    }
4105
4106    @Override
4107    public int checkUidSignatures(int uid1, int uid2) {
4108        // Map to base uids.
4109        uid1 = UserHandle.getAppId(uid1);
4110        uid2 = UserHandle.getAppId(uid2);
4111        // reader
4112        synchronized (mPackages) {
4113            Signature[] s1;
4114            Signature[] s2;
4115            Object obj = mSettings.getUserIdLPr(uid1);
4116            if (obj != null) {
4117                if (obj instanceof SharedUserSetting) {
4118                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4119                } else if (obj instanceof PackageSetting) {
4120                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4121                } else {
4122                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4123                }
4124            } else {
4125                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4126            }
4127            obj = mSettings.getUserIdLPr(uid2);
4128            if (obj != null) {
4129                if (obj instanceof SharedUserSetting) {
4130                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4131                } else if (obj instanceof PackageSetting) {
4132                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4133                } else {
4134                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4135                }
4136            } else {
4137                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4138            }
4139            return compareSignatures(s1, s2);
4140        }
4141    }
4142
4143    private void killUid(int appId, int userId, String reason) {
4144        final long identity = Binder.clearCallingIdentity();
4145        try {
4146            IActivityManager am = ActivityManagerNative.getDefault();
4147            if (am != null) {
4148                try {
4149                    am.killUid(appId, userId, reason);
4150                } catch (RemoteException e) {
4151                    /* ignore - same process */
4152                }
4153            }
4154        } finally {
4155            Binder.restoreCallingIdentity(identity);
4156        }
4157    }
4158
4159    /**
4160     * Compares two sets of signatures. Returns:
4161     * <br />
4162     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4163     * <br />
4164     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4165     * <br />
4166     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4167     * <br />
4168     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4169     * <br />
4170     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4171     */
4172    static int compareSignatures(Signature[] s1, Signature[] s2) {
4173        if (s1 == null) {
4174            return s2 == null
4175                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4176                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4177        }
4178
4179        if (s2 == null) {
4180            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4181        }
4182
4183        if (s1.length != s2.length) {
4184            return PackageManager.SIGNATURE_NO_MATCH;
4185        }
4186
4187        // Since both signature sets are of size 1, we can compare without HashSets.
4188        if (s1.length == 1) {
4189            return s1[0].equals(s2[0]) ?
4190                    PackageManager.SIGNATURE_MATCH :
4191                    PackageManager.SIGNATURE_NO_MATCH;
4192        }
4193
4194        ArraySet<Signature> set1 = new ArraySet<Signature>();
4195        for (Signature sig : s1) {
4196            set1.add(sig);
4197        }
4198        ArraySet<Signature> set2 = new ArraySet<Signature>();
4199        for (Signature sig : s2) {
4200            set2.add(sig);
4201        }
4202        // Make sure s2 contains all signatures in s1.
4203        if (set1.equals(set2)) {
4204            return PackageManager.SIGNATURE_MATCH;
4205        }
4206        return PackageManager.SIGNATURE_NO_MATCH;
4207    }
4208
4209    /**
4210     * If the database version for this type of package (internal storage or
4211     * external storage) is less than the version where package signatures
4212     * were updated, return true.
4213     */
4214    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4215        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4216        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4217    }
4218
4219    /**
4220     * Used for backward compatibility to make sure any packages with
4221     * certificate chains get upgraded to the new style. {@code existingSigs}
4222     * will be in the old format (since they were stored on disk from before the
4223     * system upgrade) and {@code scannedSigs} will be in the newer format.
4224     */
4225    private int compareSignaturesCompat(PackageSignatures existingSigs,
4226            PackageParser.Package scannedPkg) {
4227        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4228            return PackageManager.SIGNATURE_NO_MATCH;
4229        }
4230
4231        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4232        for (Signature sig : existingSigs.mSignatures) {
4233            existingSet.add(sig);
4234        }
4235        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4236        for (Signature sig : scannedPkg.mSignatures) {
4237            try {
4238                Signature[] chainSignatures = sig.getChainSignatures();
4239                for (Signature chainSig : chainSignatures) {
4240                    scannedCompatSet.add(chainSig);
4241                }
4242            } catch (CertificateEncodingException e) {
4243                scannedCompatSet.add(sig);
4244            }
4245        }
4246        /*
4247         * Make sure the expanded scanned set contains all signatures in the
4248         * existing one.
4249         */
4250        if (scannedCompatSet.equals(existingSet)) {
4251            // Migrate the old signatures to the new scheme.
4252            existingSigs.assignSignatures(scannedPkg.mSignatures);
4253            // The new KeySets will be re-added later in the scanning process.
4254            synchronized (mPackages) {
4255                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4256            }
4257            return PackageManager.SIGNATURE_MATCH;
4258        }
4259        return PackageManager.SIGNATURE_NO_MATCH;
4260    }
4261
4262    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4263        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4264        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4265    }
4266
4267    private int compareSignaturesRecover(PackageSignatures existingSigs,
4268            PackageParser.Package scannedPkg) {
4269        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4270            return PackageManager.SIGNATURE_NO_MATCH;
4271        }
4272
4273        String msg = null;
4274        try {
4275            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4276                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4277                        + scannedPkg.packageName);
4278                return PackageManager.SIGNATURE_MATCH;
4279            }
4280        } catch (CertificateException e) {
4281            msg = e.getMessage();
4282        }
4283
4284        logCriticalInfo(Log.INFO,
4285                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4286        return PackageManager.SIGNATURE_NO_MATCH;
4287    }
4288
4289    @Override
4290    public String[] getPackagesForUid(int uid) {
4291        uid = UserHandle.getAppId(uid);
4292        // reader
4293        synchronized (mPackages) {
4294            Object obj = mSettings.getUserIdLPr(uid);
4295            if (obj instanceof SharedUserSetting) {
4296                final SharedUserSetting sus = (SharedUserSetting) obj;
4297                final int N = sus.packages.size();
4298                final String[] res = new String[N];
4299                final Iterator<PackageSetting> it = sus.packages.iterator();
4300                int i = 0;
4301                while (it.hasNext()) {
4302                    res[i++] = it.next().name;
4303                }
4304                return res;
4305            } else if (obj instanceof PackageSetting) {
4306                final PackageSetting ps = (PackageSetting) obj;
4307                return new String[] { ps.name };
4308            }
4309        }
4310        return null;
4311    }
4312
4313    @Override
4314    public String getNameForUid(int uid) {
4315        // reader
4316        synchronized (mPackages) {
4317            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4318            if (obj instanceof SharedUserSetting) {
4319                final SharedUserSetting sus = (SharedUserSetting) obj;
4320                return sus.name + ":" + sus.userId;
4321            } else if (obj instanceof PackageSetting) {
4322                final PackageSetting ps = (PackageSetting) obj;
4323                return ps.name;
4324            }
4325        }
4326        return null;
4327    }
4328
4329    @Override
4330    public int getUidForSharedUser(String sharedUserName) {
4331        if(sharedUserName == null) {
4332            return -1;
4333        }
4334        // reader
4335        synchronized (mPackages) {
4336            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4337            if (suid == null) {
4338                return -1;
4339            }
4340            return suid.userId;
4341        }
4342    }
4343
4344    @Override
4345    public int getFlagsForUid(int uid) {
4346        synchronized (mPackages) {
4347            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4348            if (obj instanceof SharedUserSetting) {
4349                final SharedUserSetting sus = (SharedUserSetting) obj;
4350                return sus.pkgFlags;
4351            } else if (obj instanceof PackageSetting) {
4352                final PackageSetting ps = (PackageSetting) obj;
4353                return ps.pkgFlags;
4354            }
4355        }
4356        return 0;
4357    }
4358
4359    @Override
4360    public int getPrivateFlagsForUid(int uid) {
4361        synchronized (mPackages) {
4362            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4363            if (obj instanceof SharedUserSetting) {
4364                final SharedUserSetting sus = (SharedUserSetting) obj;
4365                return sus.pkgPrivateFlags;
4366            } else if (obj instanceof PackageSetting) {
4367                final PackageSetting ps = (PackageSetting) obj;
4368                return ps.pkgPrivateFlags;
4369            }
4370        }
4371        return 0;
4372    }
4373
4374    @Override
4375    public boolean isUidPrivileged(int uid) {
4376        uid = UserHandle.getAppId(uid);
4377        // reader
4378        synchronized (mPackages) {
4379            Object obj = mSettings.getUserIdLPr(uid);
4380            if (obj instanceof SharedUserSetting) {
4381                final SharedUserSetting sus = (SharedUserSetting) obj;
4382                final Iterator<PackageSetting> it = sus.packages.iterator();
4383                while (it.hasNext()) {
4384                    if (it.next().isPrivileged()) {
4385                        return true;
4386                    }
4387                }
4388            } else if (obj instanceof PackageSetting) {
4389                final PackageSetting ps = (PackageSetting) obj;
4390                return ps.isPrivileged();
4391            }
4392        }
4393        return false;
4394    }
4395
4396    @Override
4397    public String[] getAppOpPermissionPackages(String permissionName) {
4398        synchronized (mPackages) {
4399            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4400            if (pkgs == null) {
4401                return null;
4402            }
4403            return pkgs.toArray(new String[pkgs.size()]);
4404        }
4405    }
4406
4407    @Override
4408    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4409            int flags, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        flags = updateFlagsForResolve(flags, userId, intent);
4412        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4413        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4414        final ResolveInfo bestChoice =
4415                chooseBestActivity(intent, resolvedType, flags, query, userId);
4416
4417        if (isEphemeralAllowed(intent, query, userId)) {
4418            final EphemeralResolveInfo ai =
4419                    getEphemeralResolveInfo(intent, resolvedType, userId);
4420            if (ai != null) {
4421                if (DEBUG_EPHEMERAL) {
4422                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4423                }
4424                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4425                bestChoice.ephemeralResolveInfo = ai;
4426            }
4427        }
4428        return bestChoice;
4429    }
4430
4431    @Override
4432    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4433            IntentFilter filter, int match, ComponentName activity) {
4434        final int userId = UserHandle.getCallingUserId();
4435        if (DEBUG_PREFERRED) {
4436            Log.v(TAG, "setLastChosenActivity intent=" + intent
4437                + " resolvedType=" + resolvedType
4438                + " flags=" + flags
4439                + " filter=" + filter
4440                + " match=" + match
4441                + " activity=" + activity);
4442            filter.dump(new PrintStreamPrinter(System.out), "    ");
4443        }
4444        intent.setComponent(null);
4445        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4446        // Find any earlier preferred or last chosen entries and nuke them
4447        findPreferredActivity(intent, resolvedType,
4448                flags, query, 0, false, true, false, userId);
4449        // Add the new activity as the last chosen for this filter
4450        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4451                "Setting last chosen");
4452    }
4453
4454    @Override
4455    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4456        final int userId = UserHandle.getCallingUserId();
4457        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4458        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4459        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4460                false, false, false, userId);
4461    }
4462
4463
4464    private boolean isEphemeralAllowed(
4465            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4466        // Short circuit and return early if possible.
4467        final int callingUser = UserHandle.getCallingUserId();
4468        if (callingUser != UserHandle.USER_SYSTEM) {
4469            return false;
4470        }
4471        if (mEphemeralResolverConnection == null) {
4472            return false;
4473        }
4474        if (intent.getComponent() != null) {
4475            return false;
4476        }
4477        if (intent.getPackage() != null) {
4478            return false;
4479        }
4480        final boolean isWebUri = hasWebURI(intent);
4481        if (!isWebUri) {
4482            return false;
4483        }
4484        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4485        synchronized (mPackages) {
4486            final int count = resolvedActivites.size();
4487            for (int n = 0; n < count; n++) {
4488                ResolveInfo info = resolvedActivites.get(n);
4489                String packageName = info.activityInfo.packageName;
4490                PackageSetting ps = mSettings.mPackages.get(packageName);
4491                if (ps != null) {
4492                    // Try to get the status from User settings first
4493                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4494                    int status = (int) (packedStatus >> 32);
4495                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4496                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4497                        if (DEBUG_EPHEMERAL) {
4498                            Slog.v(TAG, "DENY ephemeral apps;"
4499                                + " pkg: " + packageName + ", status: " + status);
4500                        }
4501                        return false;
4502                    }
4503                }
4504            }
4505        }
4506        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4507        return true;
4508    }
4509
4510    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4511            int userId) {
4512        MessageDigest digest = null;
4513        try {
4514            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4515        } catch (NoSuchAlgorithmException e) {
4516            // If we can't create a digest, ignore ephemeral apps.
4517            return null;
4518        }
4519
4520        final byte[] hostBytes = intent.getData().getHost().getBytes();
4521        final byte[] digestBytes = digest.digest(hostBytes);
4522        int shaPrefix =
4523                digestBytes[0] << 24
4524                | digestBytes[1] << 16
4525                | digestBytes[2] << 8
4526                | digestBytes[3] << 0;
4527        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4528                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4529        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4530            // No hash prefix match; there are no ephemeral apps for this domain.
4531            return null;
4532        }
4533        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4534            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4535            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4536                continue;
4537            }
4538            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4539            // No filters; this should never happen.
4540            if (filters.isEmpty()) {
4541                continue;
4542            }
4543            // We have a domain match; resolve the filters to see if anything matches.
4544            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4545            for (int j = filters.size() - 1; j >= 0; --j) {
4546                final EphemeralResolveIntentInfo intentInfo =
4547                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4548                ephemeralResolver.addFilter(intentInfo);
4549            }
4550            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4551                    intent, resolvedType, false /*defaultOnly*/, userId);
4552            if (!matchedResolveInfoList.isEmpty()) {
4553                return matchedResolveInfoList.get(0);
4554            }
4555        }
4556        // Hash or filter mis-match; no ephemeral apps for this domain.
4557        return null;
4558    }
4559
4560    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4561            int flags, List<ResolveInfo> query, int userId) {
4562        if (query != null) {
4563            final int N = query.size();
4564            if (N == 1) {
4565                return query.get(0);
4566            } else if (N > 1) {
4567                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4568                // If there is more than one activity with the same priority,
4569                // then let the user decide between them.
4570                ResolveInfo r0 = query.get(0);
4571                ResolveInfo r1 = query.get(1);
4572                if (DEBUG_INTENT_MATCHING || debug) {
4573                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4574                            + r1.activityInfo.name + "=" + r1.priority);
4575                }
4576                // If the first activity has a higher priority, or a different
4577                // default, then it is always desirable to pick it.
4578                if (r0.priority != r1.priority
4579                        || r0.preferredOrder != r1.preferredOrder
4580                        || r0.isDefault != r1.isDefault) {
4581                    return query.get(0);
4582                }
4583                // If we have saved a preference for a preferred activity for
4584                // this Intent, use that.
4585                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4586                        flags, query, r0.priority, true, false, debug, userId);
4587                if (ri != null) {
4588                    return ri;
4589                }
4590                ri = new ResolveInfo(mResolveInfo);
4591                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4592                ri.activityInfo.applicationInfo = new ApplicationInfo(
4593                        ri.activityInfo.applicationInfo);
4594                if (userId != 0) {
4595                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4596                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4597                }
4598                // Make sure that the resolver is displayable in car mode
4599                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4600                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4601                return ri;
4602            }
4603        }
4604        return null;
4605    }
4606
4607    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4608            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4609        final int N = query.size();
4610        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4611                .get(userId);
4612        // Get the list of persistent preferred activities that handle the intent
4613        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4614        List<PersistentPreferredActivity> pprefs = ppir != null
4615                ? ppir.queryIntent(intent, resolvedType,
4616                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4617                : null;
4618        if (pprefs != null && pprefs.size() > 0) {
4619            final int M = pprefs.size();
4620            for (int i=0; i<M; i++) {
4621                final PersistentPreferredActivity ppa = pprefs.get(i);
4622                if (DEBUG_PREFERRED || debug) {
4623                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4624                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4625                            + "\n  component=" + ppa.mComponent);
4626                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4627                }
4628                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4629                        flags | MATCH_DISABLED_COMPONENTS, userId);
4630                if (DEBUG_PREFERRED || debug) {
4631                    Slog.v(TAG, "Found persistent preferred activity:");
4632                    if (ai != null) {
4633                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4634                    } else {
4635                        Slog.v(TAG, "  null");
4636                    }
4637                }
4638                if (ai == null) {
4639                    // This previously registered persistent preferred activity
4640                    // component is no longer known. Ignore it and do NOT remove it.
4641                    continue;
4642                }
4643                for (int j=0; j<N; j++) {
4644                    final ResolveInfo ri = query.get(j);
4645                    if (!ri.activityInfo.applicationInfo.packageName
4646                            .equals(ai.applicationInfo.packageName)) {
4647                        continue;
4648                    }
4649                    if (!ri.activityInfo.name.equals(ai.name)) {
4650                        continue;
4651                    }
4652                    //  Found a persistent preference that can handle the intent.
4653                    if (DEBUG_PREFERRED || debug) {
4654                        Slog.v(TAG, "Returning persistent preferred activity: " +
4655                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4656                    }
4657                    return ri;
4658                }
4659            }
4660        }
4661        return null;
4662    }
4663
4664    // TODO: handle preferred activities missing while user has amnesia
4665    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4666            List<ResolveInfo> query, int priority, boolean always,
4667            boolean removeMatches, boolean debug, int userId) {
4668        if (!sUserManager.exists(userId)) return null;
4669        flags = updateFlagsForResolve(flags, userId, intent);
4670        // writer
4671        synchronized (mPackages) {
4672            if (intent.getSelector() != null) {
4673                intent = intent.getSelector();
4674            }
4675            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4676
4677            // Try to find a matching persistent preferred activity.
4678            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4679                    debug, userId);
4680
4681            // If a persistent preferred activity matched, use it.
4682            if (pri != null) {
4683                return pri;
4684            }
4685
4686            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4687            // Get the list of preferred activities that handle the intent
4688            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4689            List<PreferredActivity> prefs = pir != null
4690                    ? pir.queryIntent(intent, resolvedType,
4691                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4692                    : null;
4693            if (prefs != null && prefs.size() > 0) {
4694                boolean changed = false;
4695                try {
4696                    // First figure out how good the original match set is.
4697                    // We will only allow preferred activities that came
4698                    // from the same match quality.
4699                    int match = 0;
4700
4701                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4702
4703                    final int N = query.size();
4704                    for (int j=0; j<N; j++) {
4705                        final ResolveInfo ri = query.get(j);
4706                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4707                                + ": 0x" + Integer.toHexString(match));
4708                        if (ri.match > match) {
4709                            match = ri.match;
4710                        }
4711                    }
4712
4713                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4714                            + Integer.toHexString(match));
4715
4716                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4717                    final int M = prefs.size();
4718                    for (int i=0; i<M; i++) {
4719                        final PreferredActivity pa = prefs.get(i);
4720                        if (DEBUG_PREFERRED || debug) {
4721                            Slog.v(TAG, "Checking PreferredActivity ds="
4722                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4723                                    + "\n  component=" + pa.mPref.mComponent);
4724                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4725                        }
4726                        if (pa.mPref.mMatch != match) {
4727                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4728                                    + Integer.toHexString(pa.mPref.mMatch));
4729                            continue;
4730                        }
4731                        // If it's not an "always" type preferred activity and that's what we're
4732                        // looking for, skip it.
4733                        if (always && !pa.mPref.mAlways) {
4734                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4735                            continue;
4736                        }
4737                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4738                                flags | MATCH_DISABLED_COMPONENTS, userId);
4739                        if (DEBUG_PREFERRED || debug) {
4740                            Slog.v(TAG, "Found preferred activity:");
4741                            if (ai != null) {
4742                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4743                            } else {
4744                                Slog.v(TAG, "  null");
4745                            }
4746                        }
4747                        if (ai == null) {
4748                            // This previously registered preferred activity
4749                            // component is no longer known.  Most likely an update
4750                            // to the app was installed and in the new version this
4751                            // component no longer exists.  Clean it up by removing
4752                            // it from the preferred activities list, and skip it.
4753                            Slog.w(TAG, "Removing dangling preferred activity: "
4754                                    + pa.mPref.mComponent);
4755                            pir.removeFilter(pa);
4756                            changed = true;
4757                            continue;
4758                        }
4759                        for (int j=0; j<N; j++) {
4760                            final ResolveInfo ri = query.get(j);
4761                            if (!ri.activityInfo.applicationInfo.packageName
4762                                    .equals(ai.applicationInfo.packageName)) {
4763                                continue;
4764                            }
4765                            if (!ri.activityInfo.name.equals(ai.name)) {
4766                                continue;
4767                            }
4768
4769                            if (removeMatches) {
4770                                pir.removeFilter(pa);
4771                                changed = true;
4772                                if (DEBUG_PREFERRED) {
4773                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4774                                }
4775                                break;
4776                            }
4777
4778                            // Okay we found a previously set preferred or last chosen app.
4779                            // If the result set is different from when this
4780                            // was created, we need to clear it and re-ask the
4781                            // user their preference, if we're looking for an "always" type entry.
4782                            if (always && !pa.mPref.sameSet(query)) {
4783                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4784                                        + intent + " type " + resolvedType);
4785                                if (DEBUG_PREFERRED) {
4786                                    Slog.v(TAG, "Removing preferred activity since set changed "
4787                                            + pa.mPref.mComponent);
4788                                }
4789                                pir.removeFilter(pa);
4790                                // Re-add the filter as a "last chosen" entry (!always)
4791                                PreferredActivity lastChosen = new PreferredActivity(
4792                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4793                                pir.addFilter(lastChosen);
4794                                changed = true;
4795                                return null;
4796                            }
4797
4798                            // Yay! Either the set matched or we're looking for the last chosen
4799                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4800                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4801                            return ri;
4802                        }
4803                    }
4804                } finally {
4805                    if (changed) {
4806                        if (DEBUG_PREFERRED) {
4807                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4808                        }
4809                        scheduleWritePackageRestrictionsLocked(userId);
4810                    }
4811                }
4812            }
4813        }
4814        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4815        return null;
4816    }
4817
4818    /*
4819     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4820     */
4821    @Override
4822    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4823            int targetUserId) {
4824        mContext.enforceCallingOrSelfPermission(
4825                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4826        List<CrossProfileIntentFilter> matches =
4827                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4828        if (matches != null) {
4829            int size = matches.size();
4830            for (int i = 0; i < size; i++) {
4831                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4832            }
4833        }
4834        if (hasWebURI(intent)) {
4835            // cross-profile app linking works only towards the parent.
4836            final UserInfo parent = getProfileParent(sourceUserId);
4837            synchronized(mPackages) {
4838                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4839                        intent, resolvedType, 0, sourceUserId, parent.id);
4840                return xpDomainInfo != null;
4841            }
4842        }
4843        return false;
4844    }
4845
4846    private UserInfo getProfileParent(int userId) {
4847        final long identity = Binder.clearCallingIdentity();
4848        try {
4849            return sUserManager.getProfileParent(userId);
4850        } finally {
4851            Binder.restoreCallingIdentity(identity);
4852        }
4853    }
4854
4855    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4856            String resolvedType, int userId) {
4857        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4858        if (resolver != null) {
4859            return resolver.queryIntent(intent, resolvedType, false, userId);
4860        }
4861        return null;
4862    }
4863
4864    @Override
4865    public List<ResolveInfo> queryIntentActivities(Intent intent,
4866            String resolvedType, int flags, int userId) {
4867        if (!sUserManager.exists(userId)) return Collections.emptyList();
4868        flags = updateFlagsForResolve(flags, userId, intent);
4869        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4870        ComponentName comp = intent.getComponent();
4871        if (comp == null) {
4872            if (intent.getSelector() != null) {
4873                intent = intent.getSelector();
4874                comp = intent.getComponent();
4875            }
4876        }
4877
4878        if (comp != null) {
4879            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4880            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4881            if (ai != null) {
4882                final ResolveInfo ri = new ResolveInfo();
4883                ri.activityInfo = ai;
4884                list.add(ri);
4885            }
4886            return list;
4887        }
4888
4889        // reader
4890        synchronized (mPackages) {
4891            final String pkgName = intent.getPackage();
4892            if (pkgName == null) {
4893                List<CrossProfileIntentFilter> matchingFilters =
4894                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4895                // Check for results that need to skip the current profile.
4896                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4897                        resolvedType, flags, userId);
4898                if (xpResolveInfo != null) {
4899                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4900                    result.add(xpResolveInfo);
4901                    return filterIfNotSystemUser(result, userId);
4902                }
4903
4904                // Check for results in the current profile.
4905                List<ResolveInfo> result = mActivities.queryIntent(
4906                        intent, resolvedType, flags, userId);
4907                result = filterIfNotSystemUser(result, userId);
4908
4909                // Check for cross profile results.
4910                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4911                xpResolveInfo = queryCrossProfileIntents(
4912                        matchingFilters, intent, resolvedType, flags, userId,
4913                        hasNonNegativePriorityResult);
4914                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4915                    boolean isVisibleToUser = filterIfNotSystemUser(
4916                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4917                    if (isVisibleToUser) {
4918                        result.add(xpResolveInfo);
4919                        Collections.sort(result, mResolvePrioritySorter);
4920                    }
4921                }
4922                if (hasWebURI(intent)) {
4923                    CrossProfileDomainInfo xpDomainInfo = null;
4924                    final UserInfo parent = getProfileParent(userId);
4925                    if (parent != null) {
4926                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4927                                flags, userId, parent.id);
4928                    }
4929                    if (xpDomainInfo != null) {
4930                        if (xpResolveInfo != null) {
4931                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4932                            // in the result.
4933                            result.remove(xpResolveInfo);
4934                        }
4935                        if (result.size() == 0) {
4936                            result.add(xpDomainInfo.resolveInfo);
4937                            return result;
4938                        }
4939                    } else if (result.size() <= 1) {
4940                        return result;
4941                    }
4942                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4943                            xpDomainInfo, userId);
4944                    Collections.sort(result, mResolvePrioritySorter);
4945                }
4946                return result;
4947            }
4948            final PackageParser.Package pkg = mPackages.get(pkgName);
4949            if (pkg != null) {
4950                return filterIfNotSystemUser(
4951                        mActivities.queryIntentForPackage(
4952                                intent, resolvedType, flags, pkg.activities, userId),
4953                        userId);
4954            }
4955            return new ArrayList<ResolveInfo>();
4956        }
4957    }
4958
4959    private static class CrossProfileDomainInfo {
4960        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4961        ResolveInfo resolveInfo;
4962        /* Best domain verification status of the activities found in the other profile */
4963        int bestDomainVerificationStatus;
4964    }
4965
4966    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4967            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4968        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4969                sourceUserId)) {
4970            return null;
4971        }
4972        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4973                resolvedType, flags, parentUserId);
4974
4975        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4976            return null;
4977        }
4978        CrossProfileDomainInfo result = null;
4979        int size = resultTargetUser.size();
4980        for (int i = 0; i < size; i++) {
4981            ResolveInfo riTargetUser = resultTargetUser.get(i);
4982            // Intent filter verification is only for filters that specify a host. So don't return
4983            // those that handle all web uris.
4984            if (riTargetUser.handleAllWebDataURI) {
4985                continue;
4986            }
4987            String packageName = riTargetUser.activityInfo.packageName;
4988            PackageSetting ps = mSettings.mPackages.get(packageName);
4989            if (ps == null) {
4990                continue;
4991            }
4992            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4993            int status = (int)(verificationState >> 32);
4994            if (result == null) {
4995                result = new CrossProfileDomainInfo();
4996                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4997                        sourceUserId, parentUserId);
4998                result.bestDomainVerificationStatus = status;
4999            } else {
5000                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5001                        result.bestDomainVerificationStatus);
5002            }
5003        }
5004        // Don't consider matches with status NEVER across profiles.
5005        if (result != null && result.bestDomainVerificationStatus
5006                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5007            return null;
5008        }
5009        return result;
5010    }
5011
5012    /**
5013     * Verification statuses are ordered from the worse to the best, except for
5014     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5015     */
5016    private int bestDomainVerificationStatus(int status1, int status2) {
5017        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5018            return status2;
5019        }
5020        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5021            return status1;
5022        }
5023        return (int) MathUtils.max(status1, status2);
5024    }
5025
5026    private boolean isUserEnabled(int userId) {
5027        long callingId = Binder.clearCallingIdentity();
5028        try {
5029            UserInfo userInfo = sUserManager.getUserInfo(userId);
5030            return userInfo != null && userInfo.isEnabled();
5031        } finally {
5032            Binder.restoreCallingIdentity(callingId);
5033        }
5034    }
5035
5036    /**
5037     * Filter out activities with systemUserOnly flag set, when current user is not System.
5038     *
5039     * @return filtered list
5040     */
5041    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5042        if (userId == UserHandle.USER_SYSTEM) {
5043            return resolveInfos;
5044        }
5045        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5046            ResolveInfo info = resolveInfos.get(i);
5047            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5048                resolveInfos.remove(i);
5049            }
5050        }
5051        return resolveInfos;
5052    }
5053
5054    /**
5055     * @param resolveInfos list of resolve infos in descending priority order
5056     * @return if the list contains a resolve info with non-negative priority
5057     */
5058    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5059        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5060    }
5061
5062    private static boolean hasWebURI(Intent intent) {
5063        if (intent.getData() == null) {
5064            return false;
5065        }
5066        final String scheme = intent.getScheme();
5067        if (TextUtils.isEmpty(scheme)) {
5068            return false;
5069        }
5070        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5071    }
5072
5073    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5074            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5075            int userId) {
5076        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5077
5078        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5079            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5080                    candidates.size());
5081        }
5082
5083        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5084        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5085        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5086        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5087        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5088        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5089
5090        synchronized (mPackages) {
5091            final int count = candidates.size();
5092            // First, try to use linked apps. Partition the candidates into four lists:
5093            // one for the final results, one for the "do not use ever", one for "undefined status"
5094            // and finally one for "browser app type".
5095            for (int n=0; n<count; n++) {
5096                ResolveInfo info = candidates.get(n);
5097                String packageName = info.activityInfo.packageName;
5098                PackageSetting ps = mSettings.mPackages.get(packageName);
5099                if (ps != null) {
5100                    // Add to the special match all list (Browser use case)
5101                    if (info.handleAllWebDataURI) {
5102                        matchAllList.add(info);
5103                        continue;
5104                    }
5105                    // Try to get the status from User settings first
5106                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5107                    int status = (int)(packedStatus >> 32);
5108                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5109                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5110                        if (DEBUG_DOMAIN_VERIFICATION) {
5111                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5112                                    + " : linkgen=" + linkGeneration);
5113                        }
5114                        // Use link-enabled generation as preferredOrder, i.e.
5115                        // prefer newly-enabled over earlier-enabled.
5116                        info.preferredOrder = linkGeneration;
5117                        alwaysList.add(info);
5118                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5119                        if (DEBUG_DOMAIN_VERIFICATION) {
5120                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5121                        }
5122                        neverList.add(info);
5123                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5124                        if (DEBUG_DOMAIN_VERIFICATION) {
5125                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5126                        }
5127                        alwaysAskList.add(info);
5128                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5129                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5130                        if (DEBUG_DOMAIN_VERIFICATION) {
5131                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5132                        }
5133                        undefinedList.add(info);
5134                    }
5135                }
5136            }
5137
5138            // We'll want to include browser possibilities in a few cases
5139            boolean includeBrowser = false;
5140
5141            // First try to add the "always" resolution(s) for the current user, if any
5142            if (alwaysList.size() > 0) {
5143                result.addAll(alwaysList);
5144            } else {
5145                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5146                result.addAll(undefinedList);
5147                // Maybe add one for the other profile.
5148                if (xpDomainInfo != null && (
5149                        xpDomainInfo.bestDomainVerificationStatus
5150                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5151                    result.add(xpDomainInfo.resolveInfo);
5152                }
5153                includeBrowser = true;
5154            }
5155
5156            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5157            // If there were 'always' entries their preferred order has been set, so we also
5158            // back that off to make the alternatives equivalent
5159            if (alwaysAskList.size() > 0) {
5160                for (ResolveInfo i : result) {
5161                    i.preferredOrder = 0;
5162                }
5163                result.addAll(alwaysAskList);
5164                includeBrowser = true;
5165            }
5166
5167            if (includeBrowser) {
5168                // Also add browsers (all of them or only the default one)
5169                if (DEBUG_DOMAIN_VERIFICATION) {
5170                    Slog.v(TAG, "   ...including browsers in candidate set");
5171                }
5172                if ((matchFlags & MATCH_ALL) != 0) {
5173                    result.addAll(matchAllList);
5174                } else {
5175                    // Browser/generic handling case.  If there's a default browser, go straight
5176                    // to that (but only if there is no other higher-priority match).
5177                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5178                    int maxMatchPrio = 0;
5179                    ResolveInfo defaultBrowserMatch = null;
5180                    final int numCandidates = matchAllList.size();
5181                    for (int n = 0; n < numCandidates; n++) {
5182                        ResolveInfo info = matchAllList.get(n);
5183                        // track the highest overall match priority...
5184                        if (info.priority > maxMatchPrio) {
5185                            maxMatchPrio = info.priority;
5186                        }
5187                        // ...and the highest-priority default browser match
5188                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5189                            if (defaultBrowserMatch == null
5190                                    || (defaultBrowserMatch.priority < info.priority)) {
5191                                if (debug) {
5192                                    Slog.v(TAG, "Considering default browser match " + info);
5193                                }
5194                                defaultBrowserMatch = info;
5195                            }
5196                        }
5197                    }
5198                    if (defaultBrowserMatch != null
5199                            && defaultBrowserMatch.priority >= maxMatchPrio
5200                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5201                    {
5202                        if (debug) {
5203                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5204                        }
5205                        result.add(defaultBrowserMatch);
5206                    } else {
5207                        result.addAll(matchAllList);
5208                    }
5209                }
5210
5211                // If there is nothing selected, add all candidates and remove the ones that the user
5212                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5213                if (result.size() == 0) {
5214                    result.addAll(candidates);
5215                    result.removeAll(neverList);
5216                }
5217            }
5218        }
5219        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5220            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5221                    result.size());
5222            for (ResolveInfo info : result) {
5223                Slog.v(TAG, "  + " + info.activityInfo);
5224            }
5225        }
5226        return result;
5227    }
5228
5229    // Returns a packed value as a long:
5230    //
5231    // high 'int'-sized word: link status: undefined/ask/never/always.
5232    // low 'int'-sized word: relative priority among 'always' results.
5233    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5234        long result = ps.getDomainVerificationStatusForUser(userId);
5235        // if none available, get the master status
5236        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5237            if (ps.getIntentFilterVerificationInfo() != null) {
5238                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5239            }
5240        }
5241        return result;
5242    }
5243
5244    private ResolveInfo querySkipCurrentProfileIntents(
5245            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5246            int flags, int sourceUserId) {
5247        if (matchingFilters != null) {
5248            int size = matchingFilters.size();
5249            for (int i = 0; i < size; i ++) {
5250                CrossProfileIntentFilter filter = matchingFilters.get(i);
5251                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5252                    // Checking if there are activities in the target user that can handle the
5253                    // intent.
5254                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5255                            resolvedType, flags, sourceUserId);
5256                    if (resolveInfo != null) {
5257                        return resolveInfo;
5258                    }
5259                }
5260            }
5261        }
5262        return null;
5263    }
5264
5265    // Return matching ResolveInfo in target user if any.
5266    private ResolveInfo queryCrossProfileIntents(
5267            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5268            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5269        if (matchingFilters != null) {
5270            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5271            // match the same intent. For performance reasons, it is better not to
5272            // run queryIntent twice for the same userId
5273            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5274            int size = matchingFilters.size();
5275            for (int i = 0; i < size; i++) {
5276                CrossProfileIntentFilter filter = matchingFilters.get(i);
5277                int targetUserId = filter.getTargetUserId();
5278                boolean skipCurrentProfile =
5279                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5280                boolean skipCurrentProfileIfNoMatchFound =
5281                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5282                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5283                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5284                    // Checking if there are activities in the target user that can handle the
5285                    // intent.
5286                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5287                            resolvedType, flags, sourceUserId);
5288                    if (resolveInfo != null) return resolveInfo;
5289                    alreadyTriedUserIds.put(targetUserId, true);
5290                }
5291            }
5292        }
5293        return null;
5294    }
5295
5296    /**
5297     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5298     * will forward the intent to the filter's target user.
5299     * Otherwise, returns null.
5300     */
5301    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5302            String resolvedType, int flags, int sourceUserId) {
5303        int targetUserId = filter.getTargetUserId();
5304        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5305                resolvedType, flags, targetUserId);
5306        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5307                && isUserEnabled(targetUserId)) {
5308            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5309        }
5310        return null;
5311    }
5312
5313    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5314            int sourceUserId, int targetUserId) {
5315        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5316        long ident = Binder.clearCallingIdentity();
5317        boolean targetIsProfile;
5318        try {
5319            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5320        } finally {
5321            Binder.restoreCallingIdentity(ident);
5322        }
5323        String className;
5324        if (targetIsProfile) {
5325            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5326        } else {
5327            className = FORWARD_INTENT_TO_PARENT;
5328        }
5329        ComponentName forwardingActivityComponentName = new ComponentName(
5330                mAndroidApplication.packageName, className);
5331        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5332                sourceUserId);
5333        if (!targetIsProfile) {
5334            forwardingActivityInfo.showUserIcon = targetUserId;
5335            forwardingResolveInfo.noResourceId = true;
5336        }
5337        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5338        forwardingResolveInfo.priority = 0;
5339        forwardingResolveInfo.preferredOrder = 0;
5340        forwardingResolveInfo.match = 0;
5341        forwardingResolveInfo.isDefault = true;
5342        forwardingResolveInfo.filter = filter;
5343        forwardingResolveInfo.targetUserId = targetUserId;
5344        return forwardingResolveInfo;
5345    }
5346
5347    @Override
5348    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5349            Intent[] specifics, String[] specificTypes, Intent intent,
5350            String resolvedType, int flags, int userId) {
5351        if (!sUserManager.exists(userId)) return Collections.emptyList();
5352        flags = updateFlagsForResolve(flags, userId, intent);
5353        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5354                false, "query intent activity options");
5355        final String resultsAction = intent.getAction();
5356
5357        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5358                | PackageManager.GET_RESOLVED_FILTER, userId);
5359
5360        if (DEBUG_INTENT_MATCHING) {
5361            Log.v(TAG, "Query " + intent + ": " + results);
5362        }
5363
5364        int specificsPos = 0;
5365        int N;
5366
5367        // todo: note that the algorithm used here is O(N^2).  This
5368        // isn't a problem in our current environment, but if we start running
5369        // into situations where we have more than 5 or 10 matches then this
5370        // should probably be changed to something smarter...
5371
5372        // First we go through and resolve each of the specific items
5373        // that were supplied, taking care of removing any corresponding
5374        // duplicate items in the generic resolve list.
5375        if (specifics != null) {
5376            for (int i=0; i<specifics.length; i++) {
5377                final Intent sintent = specifics[i];
5378                if (sintent == null) {
5379                    continue;
5380                }
5381
5382                if (DEBUG_INTENT_MATCHING) {
5383                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5384                }
5385
5386                String action = sintent.getAction();
5387                if (resultsAction != null && resultsAction.equals(action)) {
5388                    // If this action was explicitly requested, then don't
5389                    // remove things that have it.
5390                    action = null;
5391                }
5392
5393                ResolveInfo ri = null;
5394                ActivityInfo ai = null;
5395
5396                ComponentName comp = sintent.getComponent();
5397                if (comp == null) {
5398                    ri = resolveIntent(
5399                        sintent,
5400                        specificTypes != null ? specificTypes[i] : null,
5401                            flags, userId);
5402                    if (ri == null) {
5403                        continue;
5404                    }
5405                    if (ri == mResolveInfo) {
5406                        // ACK!  Must do something better with this.
5407                    }
5408                    ai = ri.activityInfo;
5409                    comp = new ComponentName(ai.applicationInfo.packageName,
5410                            ai.name);
5411                } else {
5412                    ai = getActivityInfo(comp, flags, userId);
5413                    if (ai == null) {
5414                        continue;
5415                    }
5416                }
5417
5418                // Look for any generic query activities that are duplicates
5419                // of this specific one, and remove them from the results.
5420                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5421                N = results.size();
5422                int j;
5423                for (j=specificsPos; j<N; j++) {
5424                    ResolveInfo sri = results.get(j);
5425                    if ((sri.activityInfo.name.equals(comp.getClassName())
5426                            && sri.activityInfo.applicationInfo.packageName.equals(
5427                                    comp.getPackageName()))
5428                        || (action != null && sri.filter.matchAction(action))) {
5429                        results.remove(j);
5430                        if (DEBUG_INTENT_MATCHING) Log.v(
5431                            TAG, "Removing duplicate item from " + j
5432                            + " due to specific " + specificsPos);
5433                        if (ri == null) {
5434                            ri = sri;
5435                        }
5436                        j--;
5437                        N--;
5438                    }
5439                }
5440
5441                // Add this specific item to its proper place.
5442                if (ri == null) {
5443                    ri = new ResolveInfo();
5444                    ri.activityInfo = ai;
5445                }
5446                results.add(specificsPos, ri);
5447                ri.specificIndex = i;
5448                specificsPos++;
5449            }
5450        }
5451
5452        // Now we go through the remaining generic results and remove any
5453        // duplicate actions that are found here.
5454        N = results.size();
5455        for (int i=specificsPos; i<N-1; i++) {
5456            final ResolveInfo rii = results.get(i);
5457            if (rii.filter == null) {
5458                continue;
5459            }
5460
5461            // Iterate over all of the actions of this result's intent
5462            // filter...  typically this should be just one.
5463            final Iterator<String> it = rii.filter.actionsIterator();
5464            if (it == null) {
5465                continue;
5466            }
5467            while (it.hasNext()) {
5468                final String action = it.next();
5469                if (resultsAction != null && resultsAction.equals(action)) {
5470                    // If this action was explicitly requested, then don't
5471                    // remove things that have it.
5472                    continue;
5473                }
5474                for (int j=i+1; j<N; j++) {
5475                    final ResolveInfo rij = results.get(j);
5476                    if (rij.filter != null && rij.filter.hasAction(action)) {
5477                        results.remove(j);
5478                        if (DEBUG_INTENT_MATCHING) Log.v(
5479                            TAG, "Removing duplicate item from " + j
5480                            + " due to action " + action + " at " + i);
5481                        j--;
5482                        N--;
5483                    }
5484                }
5485            }
5486
5487            // If the caller didn't request filter information, drop it now
5488            // so we don't have to marshall/unmarshall it.
5489            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5490                rii.filter = null;
5491            }
5492        }
5493
5494        // Filter out the caller activity if so requested.
5495        if (caller != null) {
5496            N = results.size();
5497            for (int i=0; i<N; i++) {
5498                ActivityInfo ainfo = results.get(i).activityInfo;
5499                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5500                        && caller.getClassName().equals(ainfo.name)) {
5501                    results.remove(i);
5502                    break;
5503                }
5504            }
5505        }
5506
5507        // If the caller didn't request filter information,
5508        // drop them now so we don't have to
5509        // marshall/unmarshall it.
5510        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5511            N = results.size();
5512            for (int i=0; i<N; i++) {
5513                results.get(i).filter = null;
5514            }
5515        }
5516
5517        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5518        return results;
5519    }
5520
5521    @Override
5522    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5523            int userId) {
5524        if (!sUserManager.exists(userId)) return Collections.emptyList();
5525        flags = updateFlagsForResolve(flags, userId, intent);
5526        ComponentName comp = intent.getComponent();
5527        if (comp == null) {
5528            if (intent.getSelector() != null) {
5529                intent = intent.getSelector();
5530                comp = intent.getComponent();
5531            }
5532        }
5533        if (comp != null) {
5534            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5535            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5536            if (ai != null) {
5537                ResolveInfo ri = new ResolveInfo();
5538                ri.activityInfo = ai;
5539                list.add(ri);
5540            }
5541            return list;
5542        }
5543
5544        // reader
5545        synchronized (mPackages) {
5546            String pkgName = intent.getPackage();
5547            if (pkgName == null) {
5548                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5549            }
5550            final PackageParser.Package pkg = mPackages.get(pkgName);
5551            if (pkg != null) {
5552                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5553                        userId);
5554            }
5555            return null;
5556        }
5557    }
5558
5559    @Override
5560    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5561        if (!sUserManager.exists(userId)) return null;
5562        flags = updateFlagsForResolve(flags, userId, intent);
5563        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5564        if (query != null) {
5565            if (query.size() >= 1) {
5566                // If there is more than one service with the same priority,
5567                // just arbitrarily pick the first one.
5568                return query.get(0);
5569            }
5570        }
5571        return null;
5572    }
5573
5574    @Override
5575    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5576            int userId) {
5577        if (!sUserManager.exists(userId)) return Collections.emptyList();
5578        flags = updateFlagsForResolve(flags, userId, intent);
5579        ComponentName comp = intent.getComponent();
5580        if (comp == null) {
5581            if (intent.getSelector() != null) {
5582                intent = intent.getSelector();
5583                comp = intent.getComponent();
5584            }
5585        }
5586        if (comp != null) {
5587            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5588            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5589            if (si != null) {
5590                final ResolveInfo ri = new ResolveInfo();
5591                ri.serviceInfo = si;
5592                list.add(ri);
5593            }
5594            return list;
5595        }
5596
5597        // reader
5598        synchronized (mPackages) {
5599            String pkgName = intent.getPackage();
5600            if (pkgName == null) {
5601                return mServices.queryIntent(intent, resolvedType, flags, userId);
5602            }
5603            final PackageParser.Package pkg = mPackages.get(pkgName);
5604            if (pkg != null) {
5605                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5606                        userId);
5607            }
5608            return null;
5609        }
5610    }
5611
5612    @Override
5613    public List<ResolveInfo> queryIntentContentProviders(
5614            Intent intent, String resolvedType, int flags, int userId) {
5615        if (!sUserManager.exists(userId)) return Collections.emptyList();
5616        flags = updateFlagsForResolve(flags, userId, intent);
5617        ComponentName comp = intent.getComponent();
5618        if (comp == null) {
5619            if (intent.getSelector() != null) {
5620                intent = intent.getSelector();
5621                comp = intent.getComponent();
5622            }
5623        }
5624        if (comp != null) {
5625            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5626            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5627            if (pi != null) {
5628                final ResolveInfo ri = new ResolveInfo();
5629                ri.providerInfo = pi;
5630                list.add(ri);
5631            }
5632            return list;
5633        }
5634
5635        // reader
5636        synchronized (mPackages) {
5637            String pkgName = intent.getPackage();
5638            if (pkgName == null) {
5639                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5640            }
5641            final PackageParser.Package pkg = mPackages.get(pkgName);
5642            if (pkg != null) {
5643                return mProviders.queryIntentForPackage(
5644                        intent, resolvedType, flags, pkg.providers, userId);
5645            }
5646            return null;
5647        }
5648    }
5649
5650    @Override
5651    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5652        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5653        flags = updateFlagsForPackage(flags, userId, null);
5654        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5655        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5656
5657        // writer
5658        synchronized (mPackages) {
5659            ArrayList<PackageInfo> list;
5660            if (listUninstalled) {
5661                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5662                for (PackageSetting ps : mSettings.mPackages.values()) {
5663                    PackageInfo pi;
5664                    if (ps.pkg != null) {
5665                        pi = generatePackageInfo(ps.pkg, flags, userId);
5666                    } else {
5667                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5668                    }
5669                    if (pi != null) {
5670                        list.add(pi);
5671                    }
5672                }
5673            } else {
5674                list = new ArrayList<PackageInfo>(mPackages.size());
5675                for (PackageParser.Package p : mPackages.values()) {
5676                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5677                    if (pi != null) {
5678                        list.add(pi);
5679                    }
5680                }
5681            }
5682
5683            return new ParceledListSlice<PackageInfo>(list);
5684        }
5685    }
5686
5687    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5688            String[] permissions, boolean[] tmp, int flags, int userId) {
5689        int numMatch = 0;
5690        final PermissionsState permissionsState = ps.getPermissionsState();
5691        for (int i=0; i<permissions.length; i++) {
5692            final String permission = permissions[i];
5693            if (permissionsState.hasPermission(permission, userId)) {
5694                tmp[i] = true;
5695                numMatch++;
5696            } else {
5697                tmp[i] = false;
5698            }
5699        }
5700        if (numMatch == 0) {
5701            return;
5702        }
5703        PackageInfo pi;
5704        if (ps.pkg != null) {
5705            pi = generatePackageInfo(ps.pkg, flags, userId);
5706        } else {
5707            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5708        }
5709        // The above might return null in cases of uninstalled apps or install-state
5710        // skew across users/profiles.
5711        if (pi != null) {
5712            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5713                if (numMatch == permissions.length) {
5714                    pi.requestedPermissions = permissions;
5715                } else {
5716                    pi.requestedPermissions = new String[numMatch];
5717                    numMatch = 0;
5718                    for (int i=0; i<permissions.length; i++) {
5719                        if (tmp[i]) {
5720                            pi.requestedPermissions[numMatch] = permissions[i];
5721                            numMatch++;
5722                        }
5723                    }
5724                }
5725            }
5726            list.add(pi);
5727        }
5728    }
5729
5730    @Override
5731    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5732            String[] permissions, int flags, int userId) {
5733        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5734        flags = updateFlagsForPackage(flags, userId, permissions);
5735        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5736
5737        // writer
5738        synchronized (mPackages) {
5739            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5740            boolean[] tmpBools = new boolean[permissions.length];
5741            if (listUninstalled) {
5742                for (PackageSetting ps : mSettings.mPackages.values()) {
5743                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5744                }
5745            } else {
5746                for (PackageParser.Package pkg : mPackages.values()) {
5747                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5748                    if (ps != null) {
5749                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5750                                userId);
5751                    }
5752                }
5753            }
5754
5755            return new ParceledListSlice<PackageInfo>(list);
5756        }
5757    }
5758
5759    @Override
5760    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5761        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5762        flags = updateFlagsForApplication(flags, userId, null);
5763        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5764
5765        // writer
5766        synchronized (mPackages) {
5767            ArrayList<ApplicationInfo> list;
5768            if (listUninstalled) {
5769                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5770                for (PackageSetting ps : mSettings.mPackages.values()) {
5771                    ApplicationInfo ai;
5772                    if (ps.pkg != null) {
5773                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5774                                ps.readUserState(userId), userId);
5775                    } else {
5776                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5777                    }
5778                    if (ai != null) {
5779                        list.add(ai);
5780                    }
5781                }
5782            } else {
5783                list = new ArrayList<ApplicationInfo>(mPackages.size());
5784                for (PackageParser.Package p : mPackages.values()) {
5785                    if (p.mExtras != null) {
5786                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5787                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5788                        if (ai != null) {
5789                            list.add(ai);
5790                        }
5791                    }
5792                }
5793            }
5794
5795            return new ParceledListSlice<ApplicationInfo>(list);
5796        }
5797    }
5798
5799    @Override
5800    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5801        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5802                "getEphemeralApplications");
5803        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5804                "getEphemeralApplications");
5805        synchronized (mPackages) {
5806            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5807                    .getEphemeralApplicationsLPw(userId);
5808            if (ephemeralApps != null) {
5809                return new ParceledListSlice<>(ephemeralApps);
5810            }
5811        }
5812        return null;
5813    }
5814
5815    @Override
5816    public boolean isEphemeralApplication(String packageName, int userId) {
5817        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5818                "isEphemeral");
5819        if (!isCallerSameApp(packageName)) {
5820            return false;
5821        }
5822        synchronized (mPackages) {
5823            PackageParser.Package pkg = mPackages.get(packageName);
5824            if (pkg != null) {
5825                return pkg.applicationInfo.isEphemeralApp();
5826            }
5827        }
5828        return false;
5829    }
5830
5831    @Override
5832    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5833        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5834                "getCookie");
5835        if (!isCallerSameApp(packageName)) {
5836            return null;
5837        }
5838        synchronized (mPackages) {
5839            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5840                    packageName, userId);
5841        }
5842    }
5843
5844    @Override
5845    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5846        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5847                "setCookie");
5848        if (!isCallerSameApp(packageName)) {
5849            return false;
5850        }
5851        synchronized (mPackages) {
5852            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5853                    packageName, cookie, userId);
5854        }
5855    }
5856
5857    @Override
5858    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5859        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5860                "getEphemeralApplicationIcon");
5861        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5862                "getEphemeralApplicationIcon");
5863        synchronized (mPackages) {
5864            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5865                    packageName, userId);
5866        }
5867    }
5868
5869    private boolean isCallerSameApp(String packageName) {
5870        PackageParser.Package pkg = mPackages.get(packageName);
5871        return pkg != null
5872                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5873    }
5874
5875    public List<ApplicationInfo> getPersistentApplications(int flags) {
5876        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5877
5878        // reader
5879        synchronized (mPackages) {
5880            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5881            final int userId = UserHandle.getCallingUserId();
5882            while (i.hasNext()) {
5883                final PackageParser.Package p = i.next();
5884                if (p.applicationInfo != null
5885                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5886                        && (!mSafeMode || isSystemApp(p))) {
5887                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5888                    if (ps != null) {
5889                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5890                                ps.readUserState(userId), userId);
5891                        if (ai != null) {
5892                            finalList.add(ai);
5893                        }
5894                    }
5895                }
5896            }
5897        }
5898
5899        return finalList;
5900    }
5901
5902    @Override
5903    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5904        if (!sUserManager.exists(userId)) return null;
5905        flags = updateFlagsForComponent(flags, userId, name);
5906        // reader
5907        synchronized (mPackages) {
5908            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5909            PackageSetting ps = provider != null
5910                    ? mSettings.mPackages.get(provider.owner.packageName)
5911                    : null;
5912            return ps != null
5913                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5914                    && (!mSafeMode || (provider.info.applicationInfo.flags
5915                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5916                    ? PackageParser.generateProviderInfo(provider, flags,
5917                            ps.readUserState(userId), userId)
5918                    : null;
5919        }
5920    }
5921
5922    /**
5923     * @deprecated
5924     */
5925    @Deprecated
5926    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5927        // reader
5928        synchronized (mPackages) {
5929            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5930                    .entrySet().iterator();
5931            final int userId = UserHandle.getCallingUserId();
5932            while (i.hasNext()) {
5933                Map.Entry<String, PackageParser.Provider> entry = i.next();
5934                PackageParser.Provider p = entry.getValue();
5935                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5936
5937                if (ps != null && p.syncable
5938                        && (!mSafeMode || (p.info.applicationInfo.flags
5939                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5940                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5941                            ps.readUserState(userId), userId);
5942                    if (info != null) {
5943                        outNames.add(entry.getKey());
5944                        outInfo.add(info);
5945                    }
5946                }
5947            }
5948        }
5949    }
5950
5951    @Override
5952    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5953            int uid, int flags) {
5954        final int userId = processName != null ? UserHandle.getUserId(uid)
5955                : UserHandle.getCallingUserId();
5956        if (!sUserManager.exists(userId)) return null;
5957        flags = updateFlagsForComponent(flags, userId, processName);
5958
5959        ArrayList<ProviderInfo> finalList = null;
5960        // reader
5961        synchronized (mPackages) {
5962            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5963            while (i.hasNext()) {
5964                final PackageParser.Provider p = i.next();
5965                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5966                if (ps != null && p.info.authority != null
5967                        && (processName == null
5968                                || (p.info.processName.equals(processName)
5969                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5970                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
5971                        && (!mSafeMode
5972                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5973                    if (finalList == null) {
5974                        finalList = new ArrayList<ProviderInfo>(3);
5975                    }
5976                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5977                            ps.readUserState(userId), userId);
5978                    if (info != null) {
5979                        finalList.add(info);
5980                    }
5981                }
5982            }
5983        }
5984
5985        if (finalList != null) {
5986            Collections.sort(finalList, mProviderInitOrderSorter);
5987            return new ParceledListSlice<ProviderInfo>(finalList);
5988        }
5989
5990        return null;
5991    }
5992
5993    @Override
5994    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
5995        // reader
5996        synchronized (mPackages) {
5997            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5998            return PackageParser.generateInstrumentationInfo(i, flags);
5999        }
6000    }
6001
6002    @Override
6003    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6004            int flags) {
6005        ArrayList<InstrumentationInfo> finalList =
6006            new ArrayList<InstrumentationInfo>();
6007
6008        // reader
6009        synchronized (mPackages) {
6010            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6011            while (i.hasNext()) {
6012                final PackageParser.Instrumentation p = i.next();
6013                if (targetPackage == null
6014                        || targetPackage.equals(p.info.targetPackage)) {
6015                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6016                            flags);
6017                    if (ii != null) {
6018                        finalList.add(ii);
6019                    }
6020                }
6021            }
6022        }
6023
6024        return finalList;
6025    }
6026
6027    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6028        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6029        if (overlays == null) {
6030            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6031            return;
6032        }
6033        for (PackageParser.Package opkg : overlays.values()) {
6034            // Not much to do if idmap fails: we already logged the error
6035            // and we certainly don't want to abort installation of pkg simply
6036            // because an overlay didn't fit properly. For these reasons,
6037            // ignore the return value of createIdmapForPackagePairLI.
6038            createIdmapForPackagePairLI(pkg, opkg);
6039        }
6040    }
6041
6042    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6043            PackageParser.Package opkg) {
6044        if (!opkg.mTrustedOverlay) {
6045            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6046                    opkg.baseCodePath + ": overlay not trusted");
6047            return false;
6048        }
6049        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6050        if (overlaySet == null) {
6051            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6052                    opkg.baseCodePath + " but target package has no known overlays");
6053            return false;
6054        }
6055        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6056        // TODO: generate idmap for split APKs
6057        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6058            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6059                    + opkg.baseCodePath);
6060            return false;
6061        }
6062        PackageParser.Package[] overlayArray =
6063            overlaySet.values().toArray(new PackageParser.Package[0]);
6064        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6065            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6066                return p1.mOverlayPriority - p2.mOverlayPriority;
6067            }
6068        };
6069        Arrays.sort(overlayArray, cmp);
6070
6071        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6072        int i = 0;
6073        for (PackageParser.Package p : overlayArray) {
6074            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6075        }
6076        return true;
6077    }
6078
6079    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6080        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6081        try {
6082            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6083        } finally {
6084            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6085        }
6086    }
6087
6088    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6089        final File[] files = dir.listFiles();
6090        if (ArrayUtils.isEmpty(files)) {
6091            Log.d(TAG, "No files in app dir " + dir);
6092            return;
6093        }
6094
6095        if (DEBUG_PACKAGE_SCANNING) {
6096            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6097                    + " flags=0x" + Integer.toHexString(parseFlags));
6098        }
6099
6100        for (File file : files) {
6101            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6102                    && !PackageInstallerService.isStageName(file.getName());
6103            if (!isPackage) {
6104                // Ignore entries which are not packages
6105                continue;
6106            }
6107            try {
6108                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6109                        scanFlags, currentTime, null);
6110            } catch (PackageManagerException e) {
6111                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6112
6113                // Delete invalid userdata apps
6114                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6115                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6116                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6117                    if (file.isDirectory()) {
6118                        mInstaller.rmPackageDir(file.getAbsolutePath());
6119                    } else {
6120                        file.delete();
6121                    }
6122                }
6123            }
6124        }
6125    }
6126
6127    private static File getSettingsProblemFile() {
6128        File dataDir = Environment.getDataDirectory();
6129        File systemDir = new File(dataDir, "system");
6130        File fname = new File(systemDir, "uiderrors.txt");
6131        return fname;
6132    }
6133
6134    static void reportSettingsProblem(int priority, String msg) {
6135        logCriticalInfo(priority, msg);
6136    }
6137
6138    static void logCriticalInfo(int priority, String msg) {
6139        Slog.println(priority, TAG, msg);
6140        EventLogTags.writePmCriticalInfo(msg);
6141        try {
6142            File fname = getSettingsProblemFile();
6143            FileOutputStream out = new FileOutputStream(fname, true);
6144            PrintWriter pw = new FastPrintWriter(out);
6145            SimpleDateFormat formatter = new SimpleDateFormat();
6146            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6147            pw.println(dateString + ": " + msg);
6148            pw.close();
6149            FileUtils.setPermissions(
6150                    fname.toString(),
6151                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6152                    -1, -1);
6153        } catch (java.io.IOException e) {
6154        }
6155    }
6156
6157    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6158            PackageParser.Package pkg, File srcFile, int parseFlags)
6159            throws PackageManagerException {
6160        if (ps != null
6161                && ps.codePath.equals(srcFile)
6162                && ps.timeStamp == srcFile.lastModified()
6163                && !isCompatSignatureUpdateNeeded(pkg)
6164                && !isRecoverSignatureUpdateNeeded(pkg)) {
6165            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6166            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6167            ArraySet<PublicKey> signingKs;
6168            synchronized (mPackages) {
6169                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6170            }
6171            if (ps.signatures.mSignatures != null
6172                    && ps.signatures.mSignatures.length != 0
6173                    && signingKs != null) {
6174                // Optimization: reuse the existing cached certificates
6175                // if the package appears to be unchanged.
6176                pkg.mSignatures = ps.signatures.mSignatures;
6177                pkg.mSigningKeys = signingKs;
6178                return;
6179            }
6180
6181            Slog.w(TAG, "PackageSetting for " + ps.name
6182                    + " is missing signatures.  Collecting certs again to recover them.");
6183        } else {
6184            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6185        }
6186
6187        try {
6188            pp.collectCertificates(pkg, parseFlags);
6189        } catch (PackageParserException e) {
6190            throw PackageManagerException.from(e);
6191        }
6192    }
6193
6194    /**
6195     *  Traces a package scan.
6196     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6197     */
6198    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6199            long currentTime, UserHandle user) throws PackageManagerException {
6200        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6201        try {
6202            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6203        } finally {
6204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6205        }
6206    }
6207
6208    /**
6209     *  Scans a package and returns the newly parsed package.
6210     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6211     */
6212    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6213            long currentTime, UserHandle user) throws PackageManagerException {
6214        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6215        parseFlags |= mDefParseFlags;
6216        PackageParser pp = new PackageParser();
6217        pp.setSeparateProcesses(mSeparateProcesses);
6218        pp.setOnlyCoreApps(mOnlyCore);
6219        pp.setDisplayMetrics(mMetrics);
6220
6221        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6222            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6223        }
6224
6225        final PackageParser.Package pkg;
6226        try {
6227            pkg = pp.parsePackage(scanFile, parseFlags);
6228        } catch (PackageParserException e) {
6229            throw PackageManagerException.from(e);
6230        }
6231
6232        PackageSetting ps = null;
6233        PackageSetting updatedPkg;
6234        // reader
6235        synchronized (mPackages) {
6236            // Look to see if we already know about this package.
6237            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6238            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6239                // This package has been renamed to its original name.  Let's
6240                // use that.
6241                ps = mSettings.peekPackageLPr(oldName);
6242            }
6243            // If there was no original package, see one for the real package name.
6244            if (ps == null) {
6245                ps = mSettings.peekPackageLPr(pkg.packageName);
6246            }
6247            // Check to see if this package could be hiding/updating a system
6248            // package.  Must look for it either under the original or real
6249            // package name depending on our state.
6250            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6251            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6252        }
6253        boolean updatedPkgBetter = false;
6254        // First check if this is a system package that may involve an update
6255        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6256            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6257            // it needs to drop FLAG_PRIVILEGED.
6258            if (locationIsPrivileged(scanFile)) {
6259                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6260            } else {
6261                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6262            }
6263
6264            if (ps != null && !ps.codePath.equals(scanFile)) {
6265                // The path has changed from what was last scanned...  check the
6266                // version of the new path against what we have stored to determine
6267                // what to do.
6268                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6269                if (pkg.mVersionCode <= ps.versionCode) {
6270                    // The system package has been updated and the code path does not match
6271                    // Ignore entry. Skip it.
6272                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6273                            + " ignored: updated version " + ps.versionCode
6274                            + " better than this " + pkg.mVersionCode);
6275                    if (!updatedPkg.codePath.equals(scanFile)) {
6276                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6277                                + ps.name + " changing from " + updatedPkg.codePathString
6278                                + " to " + scanFile);
6279                        updatedPkg.codePath = scanFile;
6280                        updatedPkg.codePathString = scanFile.toString();
6281                        updatedPkg.resourcePath = scanFile;
6282                        updatedPkg.resourcePathString = scanFile.toString();
6283                    }
6284                    updatedPkg.pkg = pkg;
6285                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6286                            "Package " + ps.name + " at " + scanFile
6287                                    + " ignored: updated version " + ps.versionCode
6288                                    + " better than this " + pkg.mVersionCode);
6289                } else {
6290                    // The current app on the system partition is better than
6291                    // what we have updated to on the data partition; switch
6292                    // back to the system partition version.
6293                    // At this point, its safely assumed that package installation for
6294                    // apps in system partition will go through. If not there won't be a working
6295                    // version of the app
6296                    // writer
6297                    synchronized (mPackages) {
6298                        // Just remove the loaded entries from package lists.
6299                        mPackages.remove(ps.name);
6300                    }
6301
6302                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6303                            + " reverting from " + ps.codePathString
6304                            + ": new version " + pkg.mVersionCode
6305                            + " better than installed " + ps.versionCode);
6306
6307                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6308                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6309                    synchronized (mInstallLock) {
6310                        args.cleanUpResourcesLI();
6311                    }
6312                    synchronized (mPackages) {
6313                        mSettings.enableSystemPackageLPw(ps.name);
6314                    }
6315                    updatedPkgBetter = true;
6316                }
6317            }
6318        }
6319
6320        if (updatedPkg != null) {
6321            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6322            // initially
6323            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6324
6325            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6326            // flag set initially
6327            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6328                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6329            }
6330        }
6331
6332        // Verify certificates against what was last scanned
6333        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6334
6335        /*
6336         * A new system app appeared, but we already had a non-system one of the
6337         * same name installed earlier.
6338         */
6339        boolean shouldHideSystemApp = false;
6340        if (updatedPkg == null && ps != null
6341                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6342            /*
6343             * Check to make sure the signatures match first. If they don't,
6344             * wipe the installed application and its data.
6345             */
6346            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6347                    != PackageManager.SIGNATURE_MATCH) {
6348                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6349                        + " signatures don't match existing userdata copy; removing");
6350                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6351                ps = null;
6352            } else {
6353                /*
6354                 * If the newly-added system app is an older version than the
6355                 * already installed version, hide it. It will be scanned later
6356                 * and re-added like an update.
6357                 */
6358                if (pkg.mVersionCode <= ps.versionCode) {
6359                    shouldHideSystemApp = true;
6360                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6361                            + " but new version " + pkg.mVersionCode + " better than installed "
6362                            + ps.versionCode + "; hiding system");
6363                } else {
6364                    /*
6365                     * The newly found system app is a newer version that the
6366                     * one previously installed. Simply remove the
6367                     * already-installed application and replace it with our own
6368                     * while keeping the application data.
6369                     */
6370                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6371                            + " reverting from " + ps.codePathString + ": new version "
6372                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6373                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6374                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6375                    synchronized (mInstallLock) {
6376                        args.cleanUpResourcesLI();
6377                    }
6378                }
6379            }
6380        }
6381
6382        // The apk is forward locked (not public) if its code and resources
6383        // are kept in different files. (except for app in either system or
6384        // vendor path).
6385        // TODO grab this value from PackageSettings
6386        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6387            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6388                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6389            }
6390        }
6391
6392        // TODO: extend to support forward-locked splits
6393        String resourcePath = null;
6394        String baseResourcePath = null;
6395        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6396            if (ps != null && ps.resourcePathString != null) {
6397                resourcePath = ps.resourcePathString;
6398                baseResourcePath = ps.resourcePathString;
6399            } else {
6400                // Should not happen at all. Just log an error.
6401                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6402            }
6403        } else {
6404            resourcePath = pkg.codePath;
6405            baseResourcePath = pkg.baseCodePath;
6406        }
6407
6408        // Set application objects path explicitly.
6409        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6410        pkg.applicationInfo.setCodePath(pkg.codePath);
6411        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6412        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6413        pkg.applicationInfo.setResourcePath(resourcePath);
6414        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6415        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6416
6417        // Note that we invoke the following method only if we are about to unpack an application
6418        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6419                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6420
6421        /*
6422         * If the system app should be overridden by a previously installed
6423         * data, hide the system app now and let the /data/app scan pick it up
6424         * again.
6425         */
6426        if (shouldHideSystemApp) {
6427            synchronized (mPackages) {
6428                mSettings.disableSystemPackageLPw(pkg.packageName);
6429            }
6430        }
6431
6432        return scannedPkg;
6433    }
6434
6435    private static String fixProcessName(String defProcessName,
6436            String processName, int uid) {
6437        if (processName == null) {
6438            return defProcessName;
6439        }
6440        return processName;
6441    }
6442
6443    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6444            throws PackageManagerException {
6445        if (pkgSetting.signatures.mSignatures != null) {
6446            // Already existing package. Make sure signatures match
6447            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6448                    == PackageManager.SIGNATURE_MATCH;
6449            if (!match) {
6450                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6451                        == PackageManager.SIGNATURE_MATCH;
6452            }
6453            if (!match) {
6454                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6455                        == PackageManager.SIGNATURE_MATCH;
6456            }
6457            if (!match) {
6458                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6459                        + pkg.packageName + " signatures do not match the "
6460                        + "previously installed version; ignoring!");
6461            }
6462        }
6463
6464        // Check for shared user signatures
6465        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6466            // Already existing package. Make sure signatures match
6467            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6468                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6469            if (!match) {
6470                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6471                        == PackageManager.SIGNATURE_MATCH;
6472            }
6473            if (!match) {
6474                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6475                        == PackageManager.SIGNATURE_MATCH;
6476            }
6477            if (!match) {
6478                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6479                        "Package " + pkg.packageName
6480                        + " has no signatures that match those in shared user "
6481                        + pkgSetting.sharedUser.name + "; ignoring!");
6482            }
6483        }
6484    }
6485
6486    /**
6487     * Enforces that only the system UID or root's UID can call a method exposed
6488     * via Binder.
6489     *
6490     * @param message used as message if SecurityException is thrown
6491     * @throws SecurityException if the caller is not system or root
6492     */
6493    private static final void enforceSystemOrRoot(String message) {
6494        final int uid = Binder.getCallingUid();
6495        if (uid != Process.SYSTEM_UID && uid != 0) {
6496            throw new SecurityException(message);
6497        }
6498    }
6499
6500    @Override
6501    public void performFstrimIfNeeded() {
6502        enforceSystemOrRoot("Only the system can request fstrim");
6503
6504        // Before everything else, see whether we need to fstrim.
6505        try {
6506            IMountService ms = PackageHelper.getMountService();
6507            if (ms != null) {
6508                final boolean isUpgrade = isUpgrade();
6509                boolean doTrim = isUpgrade;
6510                if (doTrim) {
6511                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6512                } else {
6513                    final long interval = android.provider.Settings.Global.getLong(
6514                            mContext.getContentResolver(),
6515                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6516                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6517                    if (interval > 0) {
6518                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6519                        if (timeSinceLast > interval) {
6520                            doTrim = true;
6521                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6522                                    + "; running immediately");
6523                        }
6524                    }
6525                }
6526                if (doTrim) {
6527                    if (!isFirstBoot()) {
6528                        try {
6529                            ActivityManagerNative.getDefault().showBootMessage(
6530                                    mContext.getResources().getString(
6531                                            R.string.android_upgrading_fstrim), true);
6532                        } catch (RemoteException e) {
6533                        }
6534                    }
6535                    ms.runMaintenance();
6536                }
6537            } else {
6538                Slog.e(TAG, "Mount service unavailable!");
6539            }
6540        } catch (RemoteException e) {
6541            // Can't happen; MountService is local
6542        }
6543    }
6544
6545    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6546        List<ResolveInfo> ris = null;
6547        try {
6548            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6549                    intent, null, 0, userId);
6550        } catch (RemoteException e) {
6551        }
6552        ArraySet<String> pkgNames = new ArraySet<String>();
6553        if (ris != null) {
6554            for (ResolveInfo ri : ris) {
6555                pkgNames.add(ri.activityInfo.packageName);
6556            }
6557        }
6558        return pkgNames;
6559    }
6560
6561    @Override
6562    public void notifyPackageUse(String packageName) {
6563        synchronized (mPackages) {
6564            PackageParser.Package p = mPackages.get(packageName);
6565            if (p == null) {
6566                return;
6567            }
6568            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6569        }
6570    }
6571
6572    @Override
6573    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6574        return performDexOptTraced(packageName, instructionSet);
6575    }
6576
6577    public boolean performDexOpt(String packageName, String instructionSet) {
6578        return performDexOptTraced(packageName, instructionSet);
6579    }
6580
6581    private boolean performDexOptTraced(String packageName, String instructionSet) {
6582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6583        try {
6584            return performDexOptInternal(packageName, instructionSet);
6585        } finally {
6586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6587        }
6588    }
6589
6590    private boolean performDexOptInternal(String packageName, String instructionSet) {
6591        PackageParser.Package p;
6592        final String targetInstructionSet;
6593        synchronized (mPackages) {
6594            p = mPackages.get(packageName);
6595            if (p == null) {
6596                return false;
6597            }
6598            mPackageUsage.write(false);
6599
6600            targetInstructionSet = instructionSet != null ? instructionSet :
6601                    getPrimaryInstructionSet(p.applicationInfo);
6602            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6603                return false;
6604            }
6605        }
6606        long callingId = Binder.clearCallingIdentity();
6607        try {
6608            synchronized (mInstallLock) {
6609                final String[] instructionSets = new String[] { targetInstructionSet };
6610                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6611                        true /* inclDependencies */);
6612                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6613            }
6614        } finally {
6615            Binder.restoreCallingIdentity(callingId);
6616        }
6617    }
6618
6619    public ArraySet<String> getPackagesThatNeedDexOpt() {
6620        ArraySet<String> pkgs = null;
6621        synchronized (mPackages) {
6622            for (PackageParser.Package p : mPackages.values()) {
6623                if (DEBUG_DEXOPT) {
6624                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6625                }
6626                if (!p.mDexOptPerformed.isEmpty()) {
6627                    continue;
6628                }
6629                if (pkgs == null) {
6630                    pkgs = new ArraySet<String>();
6631                }
6632                pkgs.add(p.packageName);
6633            }
6634        }
6635        return pkgs;
6636    }
6637
6638    public void shutdown() {
6639        mPackageUsage.write(true);
6640    }
6641
6642    @Override
6643    public void forceDexOpt(String packageName) {
6644        enforceSystemOrRoot("forceDexOpt");
6645
6646        PackageParser.Package pkg;
6647        synchronized (mPackages) {
6648            pkg = mPackages.get(packageName);
6649            if (pkg == null) {
6650                throw new IllegalArgumentException("Unknown package: " + packageName);
6651            }
6652        }
6653
6654        synchronized (mInstallLock) {
6655            final String[] instructionSets = new String[] {
6656                    getPrimaryInstructionSet(pkg.applicationInfo) };
6657
6658            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6659
6660            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6661                    true /* inclDependencies */);
6662
6663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6664            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6665                throw new IllegalStateException("Failed to dexopt: " + res);
6666            }
6667        }
6668    }
6669
6670    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6671        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6672            Slog.w(TAG, "Unable to update from " + oldPkg.name
6673                    + " to " + newPkg.packageName
6674                    + ": old package not in system partition");
6675            return false;
6676        } else if (mPackages.get(oldPkg.name) != null) {
6677            Slog.w(TAG, "Unable to update from " + oldPkg.name
6678                    + " to " + newPkg.packageName
6679                    + ": old package still exists");
6680            return false;
6681        }
6682        return true;
6683    }
6684
6685    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6686            throws PackageManagerException {
6687        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6688        if (res != 0) {
6689            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6690                    "Failed to install " + packageName + ": " + res);
6691        }
6692
6693        final int[] users = sUserManager.getUserIds();
6694        for (int user : users) {
6695            if (user != 0) {
6696                res = mInstaller.createUserData(volumeUuid, packageName,
6697                        UserHandle.getUid(user, uid), user, seinfo);
6698                if (res != 0) {
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Failed to createUserData " + packageName + ": " + res);
6701                }
6702            }
6703        }
6704    }
6705
6706    private int removeDataDirsLI(String volumeUuid, String packageName) {
6707        int[] users = sUserManager.getUserIds();
6708        int res = 0;
6709        for (int user : users) {
6710            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6711            if (resInner < 0) {
6712                res = resInner;
6713            }
6714        }
6715
6716        return res;
6717    }
6718
6719    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6720        int[] users = sUserManager.getUserIds();
6721        int res = 0;
6722        for (int user : users) {
6723            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6724            if (resInner < 0) {
6725                res = resInner;
6726            }
6727        }
6728        return res;
6729    }
6730
6731    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6732            PackageParser.Package changingLib) {
6733        if (file.path != null) {
6734            usesLibraryFiles.add(file.path);
6735            return;
6736        }
6737        PackageParser.Package p = mPackages.get(file.apk);
6738        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6739            // If we are doing this while in the middle of updating a library apk,
6740            // then we need to make sure to use that new apk for determining the
6741            // dependencies here.  (We haven't yet finished committing the new apk
6742            // to the package manager state.)
6743            if (p == null || p.packageName.equals(changingLib.packageName)) {
6744                p = changingLib;
6745            }
6746        }
6747        if (p != null) {
6748            usesLibraryFiles.addAll(p.getAllCodePaths());
6749        }
6750    }
6751
6752    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6753            PackageParser.Package changingLib) throws PackageManagerException {
6754        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6755            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6756            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6757            for (int i=0; i<N; i++) {
6758                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6759                if (file == null) {
6760                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6761                            "Package " + pkg.packageName + " requires unavailable shared library "
6762                            + pkg.usesLibraries.get(i) + "; failing!");
6763                }
6764                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6765            }
6766            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6767            for (int i=0; i<N; i++) {
6768                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6769                if (file == null) {
6770                    Slog.w(TAG, "Package " + pkg.packageName
6771                            + " desires unavailable shared library "
6772                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6773                } else {
6774                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6775                }
6776            }
6777            N = usesLibraryFiles.size();
6778            if (N > 0) {
6779                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6780            } else {
6781                pkg.usesLibraryFiles = null;
6782            }
6783        }
6784    }
6785
6786    private static boolean hasString(List<String> list, List<String> which) {
6787        if (list == null) {
6788            return false;
6789        }
6790        for (int i=list.size()-1; i>=0; i--) {
6791            for (int j=which.size()-1; j>=0; j--) {
6792                if (which.get(j).equals(list.get(i))) {
6793                    return true;
6794                }
6795            }
6796        }
6797        return false;
6798    }
6799
6800    private void updateAllSharedLibrariesLPw() {
6801        for (PackageParser.Package pkg : mPackages.values()) {
6802            try {
6803                updateSharedLibrariesLPw(pkg, null);
6804            } catch (PackageManagerException e) {
6805                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6806            }
6807        }
6808    }
6809
6810    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6811            PackageParser.Package changingPkg) {
6812        ArrayList<PackageParser.Package> res = null;
6813        for (PackageParser.Package pkg : mPackages.values()) {
6814            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6815                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6816                if (res == null) {
6817                    res = new ArrayList<PackageParser.Package>();
6818                }
6819                res.add(pkg);
6820                try {
6821                    updateSharedLibrariesLPw(pkg, changingPkg);
6822                } catch (PackageManagerException e) {
6823                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6824                }
6825            }
6826        }
6827        return res;
6828    }
6829
6830    /**
6831     * Derive the value of the {@code cpuAbiOverride} based on the provided
6832     * value and an optional stored value from the package settings.
6833     */
6834    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6835        String cpuAbiOverride = null;
6836
6837        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6838            cpuAbiOverride = null;
6839        } else if (abiOverride != null) {
6840            cpuAbiOverride = abiOverride;
6841        } else if (settings != null) {
6842            cpuAbiOverride = settings.cpuAbiOverrideString;
6843        }
6844
6845        return cpuAbiOverride;
6846    }
6847
6848    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6849            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6851        try {
6852            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6853        } finally {
6854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6855        }
6856    }
6857
6858    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6860        boolean success = false;
6861        try {
6862            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6863                    currentTime, user);
6864            success = true;
6865            return res;
6866        } finally {
6867            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6868                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6869            }
6870        }
6871    }
6872
6873    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6874            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6875        final File scanFile = new File(pkg.codePath);
6876        if (pkg.applicationInfo.getCodePath() == null ||
6877                pkg.applicationInfo.getResourcePath() == null) {
6878            // Bail out. The resource and code paths haven't been set.
6879            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6880                    "Code and resource paths haven't been set correctly");
6881        }
6882
6883        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6884            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6885        } else {
6886            // Only allow system apps to be flagged as core apps.
6887            pkg.coreApp = false;
6888        }
6889
6890        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6891            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6892        }
6893
6894        if (mCustomResolverComponentName != null &&
6895                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6896            setUpCustomResolverActivity(pkg);
6897        }
6898
6899        if (pkg.packageName.equals("android")) {
6900            synchronized (mPackages) {
6901                if (mAndroidApplication != null) {
6902                    Slog.w(TAG, "*************************************************");
6903                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6904                    Slog.w(TAG, " file=" + scanFile);
6905                    Slog.w(TAG, "*************************************************");
6906                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6907                            "Core android package being redefined.  Skipping.");
6908                }
6909
6910                // Set up information for our fall-back user intent resolution activity.
6911                mPlatformPackage = pkg;
6912                pkg.mVersionCode = mSdkVersion;
6913                mAndroidApplication = pkg.applicationInfo;
6914
6915                if (!mResolverReplaced) {
6916                    mResolveActivity.applicationInfo = mAndroidApplication;
6917                    mResolveActivity.name = ResolverActivity.class.getName();
6918                    mResolveActivity.packageName = mAndroidApplication.packageName;
6919                    mResolveActivity.processName = "system:ui";
6920                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6921                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6922                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6923                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6924                    mResolveActivity.exported = true;
6925                    mResolveActivity.enabled = true;
6926                    mResolveInfo.activityInfo = mResolveActivity;
6927                    mResolveInfo.priority = 0;
6928                    mResolveInfo.preferredOrder = 0;
6929                    mResolveInfo.match = 0;
6930                    mResolveComponentName = new ComponentName(
6931                            mAndroidApplication.packageName, mResolveActivity.name);
6932                }
6933            }
6934        }
6935
6936        if (DEBUG_PACKAGE_SCANNING) {
6937            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6938                Log.d(TAG, "Scanning package " + pkg.packageName);
6939        }
6940
6941        if (mPackages.containsKey(pkg.packageName)
6942                || mSharedLibraries.containsKey(pkg.packageName)) {
6943            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6944                    "Application package " + pkg.packageName
6945                    + " already installed.  Skipping duplicate.");
6946        }
6947
6948        // If we're only installing presumed-existing packages, require that the
6949        // scanned APK is both already known and at the path previously established
6950        // for it.  Previously unknown packages we pick up normally, but if we have an
6951        // a priori expectation about this package's install presence, enforce it.
6952        // With a singular exception for new system packages. When an OTA contains
6953        // a new system package, we allow the codepath to change from a system location
6954        // to the user-installed location. If we don't allow this change, any newer,
6955        // user-installed version of the application will be ignored.
6956        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6957            if (mExpectingBetter.containsKey(pkg.packageName)) {
6958                logCriticalInfo(Log.WARN,
6959                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6960            } else {
6961                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6962                if (known != null) {
6963                    if (DEBUG_PACKAGE_SCANNING) {
6964                        Log.d(TAG, "Examining " + pkg.codePath
6965                                + " and requiring known paths " + known.codePathString
6966                                + " & " + known.resourcePathString);
6967                    }
6968                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6969                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6970                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6971                                "Application package " + pkg.packageName
6972                                + " found at " + pkg.applicationInfo.getCodePath()
6973                                + " but expected at " + known.codePathString + "; ignoring.");
6974                    }
6975                }
6976            }
6977        }
6978
6979        // Initialize package source and resource directories
6980        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6981        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6982
6983        SharedUserSetting suid = null;
6984        PackageSetting pkgSetting = null;
6985
6986        if (!isSystemApp(pkg)) {
6987            // Only system apps can use these features.
6988            pkg.mOriginalPackages = null;
6989            pkg.mRealPackage = null;
6990            pkg.mAdoptPermissions = null;
6991        }
6992
6993        // writer
6994        synchronized (mPackages) {
6995            if (pkg.mSharedUserId != null) {
6996                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6997                if (suid == null) {
6998                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6999                            "Creating application package " + pkg.packageName
7000                            + " for shared user failed");
7001                }
7002                if (DEBUG_PACKAGE_SCANNING) {
7003                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7004                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7005                                + "): packages=" + suid.packages);
7006                }
7007            }
7008
7009            // Check if we are renaming from an original package name.
7010            PackageSetting origPackage = null;
7011            String realName = null;
7012            if (pkg.mOriginalPackages != null) {
7013                // This package may need to be renamed to a previously
7014                // installed name.  Let's check on that...
7015                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7016                if (pkg.mOriginalPackages.contains(renamed)) {
7017                    // This package had originally been installed as the
7018                    // original name, and we have already taken care of
7019                    // transitioning to the new one.  Just update the new
7020                    // one to continue using the old name.
7021                    realName = pkg.mRealPackage;
7022                    if (!pkg.packageName.equals(renamed)) {
7023                        // Callers into this function may have already taken
7024                        // care of renaming the package; only do it here if
7025                        // it is not already done.
7026                        pkg.setPackageName(renamed);
7027                    }
7028
7029                } else {
7030                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7031                        if ((origPackage = mSettings.peekPackageLPr(
7032                                pkg.mOriginalPackages.get(i))) != null) {
7033                            // We do have the package already installed under its
7034                            // original name...  should we use it?
7035                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7036                                // New package is not compatible with original.
7037                                origPackage = null;
7038                                continue;
7039                            } else if (origPackage.sharedUser != null) {
7040                                // Make sure uid is compatible between packages.
7041                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7042                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7043                                            + " to " + pkg.packageName + ": old uid "
7044                                            + origPackage.sharedUser.name
7045                                            + " differs from " + pkg.mSharedUserId);
7046                                    origPackage = null;
7047                                    continue;
7048                                }
7049                            } else {
7050                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7051                                        + pkg.packageName + " to old name " + origPackage.name);
7052                            }
7053                            break;
7054                        }
7055                    }
7056                }
7057            }
7058
7059            if (mTransferedPackages.contains(pkg.packageName)) {
7060                Slog.w(TAG, "Package " + pkg.packageName
7061                        + " was transferred to another, but its .apk remains");
7062            }
7063
7064            // Just create the setting, don't add it yet. For already existing packages
7065            // the PkgSetting exists already and doesn't have to be created.
7066            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7067                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7068                    pkg.applicationInfo.primaryCpuAbi,
7069                    pkg.applicationInfo.secondaryCpuAbi,
7070                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7071                    user, false);
7072            if (pkgSetting == null) {
7073                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7074                        "Creating application package " + pkg.packageName + " failed");
7075            }
7076
7077            if (pkgSetting.origPackage != null) {
7078                // If we are first transitioning from an original package,
7079                // fix up the new package's name now.  We need to do this after
7080                // looking up the package under its new name, so getPackageLP
7081                // can take care of fiddling things correctly.
7082                pkg.setPackageName(origPackage.name);
7083
7084                // File a report about this.
7085                String msg = "New package " + pkgSetting.realName
7086                        + " renamed to replace old package " + pkgSetting.name;
7087                reportSettingsProblem(Log.WARN, msg);
7088
7089                // Make a note of it.
7090                mTransferedPackages.add(origPackage.name);
7091
7092                // No longer need to retain this.
7093                pkgSetting.origPackage = null;
7094            }
7095
7096            if (realName != null) {
7097                // Make a note of it.
7098                mTransferedPackages.add(pkg.packageName);
7099            }
7100
7101            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7102                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7103            }
7104
7105            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7106                // Check all shared libraries and map to their actual file path.
7107                // We only do this here for apps not on a system dir, because those
7108                // are the only ones that can fail an install due to this.  We
7109                // will take care of the system apps by updating all of their
7110                // library paths after the scan is done.
7111                updateSharedLibrariesLPw(pkg, null);
7112            }
7113
7114            if (mFoundPolicyFile) {
7115                SELinuxMMAC.assignSeinfoValue(pkg);
7116            }
7117
7118            pkg.applicationInfo.uid = pkgSetting.appId;
7119            pkg.mExtras = pkgSetting;
7120            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7121                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7122                    // We just determined the app is signed correctly, so bring
7123                    // over the latest parsed certs.
7124                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7125                } else {
7126                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7127                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7128                                "Package " + pkg.packageName + " upgrade keys do not match the "
7129                                + "previously installed version");
7130                    } else {
7131                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7132                        String msg = "System package " + pkg.packageName
7133                            + " signature changed; retaining data.";
7134                        reportSettingsProblem(Log.WARN, msg);
7135                    }
7136                }
7137            } else {
7138                try {
7139                    verifySignaturesLP(pkgSetting, pkg);
7140                    // We just determined the app is signed correctly, so bring
7141                    // over the latest parsed certs.
7142                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7143                } catch (PackageManagerException e) {
7144                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7145                        throw e;
7146                    }
7147                    // The signature has changed, but this package is in the system
7148                    // image...  let's recover!
7149                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7150                    // However...  if this package is part of a shared user, but it
7151                    // doesn't match the signature of the shared user, let's fail.
7152                    // What this means is that you can't change the signatures
7153                    // associated with an overall shared user, which doesn't seem all
7154                    // that unreasonable.
7155                    if (pkgSetting.sharedUser != null) {
7156                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7157                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7158                            throw new PackageManagerException(
7159                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7160                                            "Signature mismatch for shared user: "
7161                                            + pkgSetting.sharedUser);
7162                        }
7163                    }
7164                    // File a report about this.
7165                    String msg = "System package " + pkg.packageName
7166                        + " signature changed; retaining data.";
7167                    reportSettingsProblem(Log.WARN, msg);
7168                }
7169            }
7170            // Verify that this new package doesn't have any content providers
7171            // that conflict with existing packages.  Only do this if the
7172            // package isn't already installed, since we don't want to break
7173            // things that are installed.
7174            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7175                final int N = pkg.providers.size();
7176                int i;
7177                for (i=0; i<N; i++) {
7178                    PackageParser.Provider p = pkg.providers.get(i);
7179                    if (p.info.authority != null) {
7180                        String names[] = p.info.authority.split(";");
7181                        for (int j = 0; j < names.length; j++) {
7182                            if (mProvidersByAuthority.containsKey(names[j])) {
7183                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7184                                final String otherPackageName =
7185                                        ((other != null && other.getComponentName() != null) ?
7186                                                other.getComponentName().getPackageName() : "?");
7187                                throw new PackageManagerException(
7188                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7189                                                "Can't install because provider name " + names[j]
7190                                                + " (in package " + pkg.applicationInfo.packageName
7191                                                + ") is already used by " + otherPackageName);
7192                            }
7193                        }
7194                    }
7195                }
7196            }
7197
7198            if (pkg.mAdoptPermissions != null) {
7199                // This package wants to adopt ownership of permissions from
7200                // another package.
7201                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7202                    final String origName = pkg.mAdoptPermissions.get(i);
7203                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7204                    if (orig != null) {
7205                        if (verifyPackageUpdateLPr(orig, pkg)) {
7206                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7207                                    + pkg.packageName);
7208                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7209                        }
7210                    }
7211                }
7212            }
7213        }
7214
7215        final String pkgName = pkg.packageName;
7216
7217        final long scanFileTime = scanFile.lastModified();
7218        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7219        pkg.applicationInfo.processName = fixProcessName(
7220                pkg.applicationInfo.packageName,
7221                pkg.applicationInfo.processName,
7222                pkg.applicationInfo.uid);
7223
7224        if (pkg != mPlatformPackage) {
7225            // This is a normal package, need to make its data directory.
7226            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7227                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7228
7229            boolean uidError = false;
7230            if (dataPath.exists()) {
7231                int currentUid = 0;
7232                try {
7233                    StructStat stat = Os.stat(dataPath.getPath());
7234                    currentUid = stat.st_uid;
7235                } catch (ErrnoException e) {
7236                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7237                }
7238
7239                // If we have mismatched owners for the data path, we have a problem.
7240                if (currentUid != pkg.applicationInfo.uid) {
7241                    boolean recovered = false;
7242                    if (currentUid == 0) {
7243                        // The directory somehow became owned by root.  Wow.
7244                        // This is probably because the system was stopped while
7245                        // installd was in the middle of messing with its libs
7246                        // directory.  Ask installd to fix that.
7247                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7248                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7249                        if (ret >= 0) {
7250                            recovered = true;
7251                            String msg = "Package " + pkg.packageName
7252                                    + " unexpectedly changed to uid 0; recovered to " +
7253                                    + pkg.applicationInfo.uid;
7254                            reportSettingsProblem(Log.WARN, msg);
7255                        }
7256                    }
7257                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7258                            || (scanFlags&SCAN_BOOTING) != 0)) {
7259                        // If this is a system app, we can at least delete its
7260                        // current data so the application will still work.
7261                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7262                        if (ret >= 0) {
7263                            // TODO: Kill the processes first
7264                            // Old data gone!
7265                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7266                                    ? "System package " : "Third party package ";
7267                            String msg = prefix + pkg.packageName
7268                                    + " has changed from uid: "
7269                                    + currentUid + " to "
7270                                    + pkg.applicationInfo.uid + "; old data erased";
7271                            reportSettingsProblem(Log.WARN, msg);
7272                            recovered = true;
7273                        }
7274                        if (!recovered) {
7275                            mHasSystemUidErrors = true;
7276                        }
7277                    } else if (!recovered) {
7278                        // If we allow this install to proceed, we will be broken.
7279                        // Abort, abort!
7280                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7281                                "scanPackageLI");
7282                    }
7283                    if (!recovered) {
7284                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7285                            + pkg.applicationInfo.uid + "/fs_"
7286                            + currentUid;
7287                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7288                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7289                        String msg = "Package " + pkg.packageName
7290                                + " has mismatched uid: "
7291                                + currentUid + " on disk, "
7292                                + pkg.applicationInfo.uid + " in settings";
7293                        // writer
7294                        synchronized (mPackages) {
7295                            mSettings.mReadMessages.append(msg);
7296                            mSettings.mReadMessages.append('\n');
7297                            uidError = true;
7298                            if (!pkgSetting.uidError) {
7299                                reportSettingsProblem(Log.ERROR, msg);
7300                            }
7301                        }
7302                    }
7303                }
7304
7305                // Ensure that directories are prepared
7306                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7307                        pkg.applicationInfo.seinfo);
7308
7309                if (mShouldRestoreconData) {
7310                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7311                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7312                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7313                }
7314            } else {
7315                if (DEBUG_PACKAGE_SCANNING) {
7316                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7317                        Log.v(TAG, "Want this data dir: " + dataPath);
7318                }
7319                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7320                        pkg.applicationInfo.seinfo);
7321            }
7322
7323            // Get all of our default paths setup
7324            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7325
7326            pkgSetting.uidError = uidError;
7327        }
7328
7329        final String path = scanFile.getPath();
7330        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7331
7332        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7333            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7334
7335            // Some system apps still use directory structure for native libraries
7336            // in which case we might end up not detecting abi solely based on apk
7337            // structure. Try to detect abi based on directory structure.
7338            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7339                    pkg.applicationInfo.primaryCpuAbi == null) {
7340                setBundledAppAbisAndRoots(pkg, pkgSetting);
7341                setNativeLibraryPaths(pkg);
7342            }
7343
7344        } else {
7345            if ((scanFlags & SCAN_MOVE) != 0) {
7346                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7347                // but we already have this packages package info in the PackageSetting. We just
7348                // use that and derive the native library path based on the new codepath.
7349                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7350                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7351            }
7352
7353            // Set native library paths again. For moves, the path will be updated based on the
7354            // ABIs we've determined above. For non-moves, the path will be updated based on the
7355            // ABIs we determined during compilation, but the path will depend on the final
7356            // package path (after the rename away from the stage path).
7357            setNativeLibraryPaths(pkg);
7358        }
7359
7360        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7361        final int[] userIds = sUserManager.getUserIds();
7362        synchronized (mInstallLock) {
7363            // Make sure all user data directories are ready to roll; we're okay
7364            // if they already exist
7365            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7366                for (int userId : userIds) {
7367                    if (userId != UserHandle.USER_SYSTEM) {
7368                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7369                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7370                                pkg.applicationInfo.seinfo);
7371                    }
7372                }
7373            }
7374
7375            // Create a native library symlink only if we have native libraries
7376            // and if the native libraries are 32 bit libraries. We do not provide
7377            // this symlink for 64 bit libraries.
7378            if (pkg.applicationInfo.primaryCpuAbi != null &&
7379                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7380                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7381                try {
7382                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7383                    for (int userId : userIds) {
7384                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7385                                nativeLibPath, userId) < 0) {
7386                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7387                                    "Failed linking native library dir (user=" + userId + ")");
7388                        }
7389                    }
7390                } finally {
7391                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7392                }
7393            }
7394        }
7395
7396        // This is a special case for the "system" package, where the ABI is
7397        // dictated by the zygote configuration (and init.rc). We should keep track
7398        // of this ABI so that we can deal with "normal" applications that run under
7399        // the same UID correctly.
7400        if (mPlatformPackage == pkg) {
7401            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7402                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7403        }
7404
7405        // If there's a mismatch between the abi-override in the package setting
7406        // and the abiOverride specified for the install. Warn about this because we
7407        // would've already compiled the app without taking the package setting into
7408        // account.
7409        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7410            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7411                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7412                        " for package " + pkg.packageName);
7413            }
7414        }
7415
7416        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7417        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7418        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7419
7420        // Copy the derived override back to the parsed package, so that we can
7421        // update the package settings accordingly.
7422        pkg.cpuAbiOverride = cpuAbiOverride;
7423
7424        if (DEBUG_ABI_SELECTION) {
7425            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7426                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7427                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7428        }
7429
7430        // Push the derived path down into PackageSettings so we know what to
7431        // clean up at uninstall time.
7432        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7433
7434        if (DEBUG_ABI_SELECTION) {
7435            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7436                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7437                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7438        }
7439
7440        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7441            // We don't do this here during boot because we can do it all
7442            // at once after scanning all existing packages.
7443            //
7444            // We also do this *before* we perform dexopt on this package, so that
7445            // we can avoid redundant dexopts, and also to make sure we've got the
7446            // code and package path correct.
7447            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7448                    pkg, true /* boot complete */);
7449        }
7450
7451        if (mFactoryTest && pkg.requestedPermissions.contains(
7452                android.Manifest.permission.FACTORY_TEST)) {
7453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7454        }
7455
7456        ArrayList<PackageParser.Package> clientLibPkgs = null;
7457
7458        // writer
7459        synchronized (mPackages) {
7460            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7461                // Only system apps can add new shared libraries.
7462                if (pkg.libraryNames != null) {
7463                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7464                        String name = pkg.libraryNames.get(i);
7465                        boolean allowed = false;
7466                        if (pkg.isUpdatedSystemApp()) {
7467                            // New library entries can only be added through the
7468                            // system image.  This is important to get rid of a lot
7469                            // of nasty edge cases: for example if we allowed a non-
7470                            // system update of the app to add a library, then uninstalling
7471                            // the update would make the library go away, and assumptions
7472                            // we made such as through app install filtering would now
7473                            // have allowed apps on the device which aren't compatible
7474                            // with it.  Better to just have the restriction here, be
7475                            // conservative, and create many fewer cases that can negatively
7476                            // impact the user experience.
7477                            final PackageSetting sysPs = mSettings
7478                                    .getDisabledSystemPkgLPr(pkg.packageName);
7479                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7480                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7481                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7482                                        allowed = true;
7483                                        break;
7484                                    }
7485                                }
7486                            }
7487                        } else {
7488                            allowed = true;
7489                        }
7490                        if (allowed) {
7491                            if (!mSharedLibraries.containsKey(name)) {
7492                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7493                            } else if (!name.equals(pkg.packageName)) {
7494                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7495                                        + name + " already exists; skipping");
7496                            }
7497                        } else {
7498                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7499                                    + name + " that is not declared on system image; skipping");
7500                        }
7501                    }
7502                    if ((scanFlags & SCAN_BOOTING) == 0) {
7503                        // If we are not booting, we need to update any applications
7504                        // that are clients of our shared library.  If we are booting,
7505                        // this will all be done once the scan is complete.
7506                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7507                    }
7508                }
7509            }
7510        }
7511
7512        // Request the ActivityManager to kill the process(only for existing packages)
7513        // so that we do not end up in a confused state while the user is still using the older
7514        // version of the application while the new one gets installed.
7515        if ((scanFlags & SCAN_REPLACING) != 0) {
7516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7517
7518            killApplication(pkg.applicationInfo.packageName,
7519                        pkg.applicationInfo.uid, "replace pkg");
7520
7521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7522        }
7523
7524        // Also need to kill any apps that are dependent on the library.
7525        if (clientLibPkgs != null) {
7526            for (int i=0; i<clientLibPkgs.size(); i++) {
7527                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7528                killApplication(clientPkg.applicationInfo.packageName,
7529                        clientPkg.applicationInfo.uid, "update lib");
7530            }
7531        }
7532
7533        // Make sure we're not adding any bogus keyset info
7534        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7535        ksms.assertScannedPackageValid(pkg);
7536
7537        // writer
7538        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7539
7540        boolean createIdmapFailed = false;
7541        synchronized (mPackages) {
7542            // We don't expect installation to fail beyond this point
7543
7544            // Add the new setting to mSettings
7545            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7546            // Add the new setting to mPackages
7547            mPackages.put(pkg.applicationInfo.packageName, pkg);
7548            // Make sure we don't accidentally delete its data.
7549            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7550            while (iter.hasNext()) {
7551                PackageCleanItem item = iter.next();
7552                if (pkgName.equals(item.packageName)) {
7553                    iter.remove();
7554                }
7555            }
7556
7557            // Take care of first install / last update times.
7558            if (currentTime != 0) {
7559                if (pkgSetting.firstInstallTime == 0) {
7560                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7561                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7562                    pkgSetting.lastUpdateTime = currentTime;
7563                }
7564            } else if (pkgSetting.firstInstallTime == 0) {
7565                // We need *something*.  Take time time stamp of the file.
7566                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7567            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7568                if (scanFileTime != pkgSetting.timeStamp) {
7569                    // A package on the system image has changed; consider this
7570                    // to be an update.
7571                    pkgSetting.lastUpdateTime = scanFileTime;
7572                }
7573            }
7574
7575            // Add the package's KeySets to the global KeySetManagerService
7576            ksms.addScannedPackageLPw(pkg);
7577
7578            int N = pkg.providers.size();
7579            StringBuilder r = null;
7580            int i;
7581            for (i=0; i<N; i++) {
7582                PackageParser.Provider p = pkg.providers.get(i);
7583                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7584                        p.info.processName, pkg.applicationInfo.uid);
7585                mProviders.addProvider(p);
7586                p.syncable = p.info.isSyncable;
7587                if (p.info.authority != null) {
7588                    String names[] = p.info.authority.split(";");
7589                    p.info.authority = null;
7590                    for (int j = 0; j < names.length; j++) {
7591                        if (j == 1 && p.syncable) {
7592                            // We only want the first authority for a provider to possibly be
7593                            // syncable, so if we already added this provider using a different
7594                            // authority clear the syncable flag. We copy the provider before
7595                            // changing it because the mProviders object contains a reference
7596                            // to a provider that we don't want to change.
7597                            // Only do this for the second authority since the resulting provider
7598                            // object can be the same for all future authorities for this provider.
7599                            p = new PackageParser.Provider(p);
7600                            p.syncable = false;
7601                        }
7602                        if (!mProvidersByAuthority.containsKey(names[j])) {
7603                            mProvidersByAuthority.put(names[j], p);
7604                            if (p.info.authority == null) {
7605                                p.info.authority = names[j];
7606                            } else {
7607                                p.info.authority = p.info.authority + ";" + names[j];
7608                            }
7609                            if (DEBUG_PACKAGE_SCANNING) {
7610                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7611                                    Log.d(TAG, "Registered content provider: " + names[j]
7612                                            + ", className = " + p.info.name + ", isSyncable = "
7613                                            + p.info.isSyncable);
7614                            }
7615                        } else {
7616                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7617                            Slog.w(TAG, "Skipping provider name " + names[j] +
7618                                    " (in package " + pkg.applicationInfo.packageName +
7619                                    "): name already used by "
7620                                    + ((other != null && other.getComponentName() != null)
7621                                            ? other.getComponentName().getPackageName() : "?"));
7622                        }
7623                    }
7624                }
7625                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7626                    if (r == null) {
7627                        r = new StringBuilder(256);
7628                    } else {
7629                        r.append(' ');
7630                    }
7631                    r.append(p.info.name);
7632                }
7633            }
7634            if (r != null) {
7635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7636            }
7637
7638            N = pkg.services.size();
7639            r = null;
7640            for (i=0; i<N; i++) {
7641                PackageParser.Service s = pkg.services.get(i);
7642                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7643                        s.info.processName, pkg.applicationInfo.uid);
7644                mServices.addService(s);
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(s.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7656            }
7657
7658            N = pkg.receivers.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.Activity a = pkg.receivers.get(i);
7662                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7663                        a.info.processName, pkg.applicationInfo.uid);
7664                mReceivers.addActivity(a, "receiver");
7665                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                    if (r == null) {
7667                        r = new StringBuilder(256);
7668                    } else {
7669                        r.append(' ');
7670                    }
7671                    r.append(a.info.name);
7672                }
7673            }
7674            if (r != null) {
7675                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7676            }
7677
7678            N = pkg.activities.size();
7679            r = null;
7680            for (i=0; i<N; i++) {
7681                PackageParser.Activity a = pkg.activities.get(i);
7682                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7683                        a.info.processName, pkg.applicationInfo.uid);
7684                mActivities.addActivity(a, "activity");
7685                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7686                    if (r == null) {
7687                        r = new StringBuilder(256);
7688                    } else {
7689                        r.append(' ');
7690                    }
7691                    r.append(a.info.name);
7692                }
7693            }
7694            if (r != null) {
7695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7696            }
7697
7698            N = pkg.permissionGroups.size();
7699            r = null;
7700            for (i=0; i<N; i++) {
7701                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7702                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7703                if (cur == null) {
7704                    mPermissionGroups.put(pg.info.name, pg);
7705                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7706                        if (r == null) {
7707                            r = new StringBuilder(256);
7708                        } else {
7709                            r.append(' ');
7710                        }
7711                        r.append(pg.info.name);
7712                    }
7713                } else {
7714                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7715                            + pg.info.packageName + " ignored: original from "
7716                            + cur.info.packageName);
7717                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7718                        if (r == null) {
7719                            r = new StringBuilder(256);
7720                        } else {
7721                            r.append(' ');
7722                        }
7723                        r.append("DUP:");
7724                        r.append(pg.info.name);
7725                    }
7726                }
7727            }
7728            if (r != null) {
7729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7730            }
7731
7732            N = pkg.permissions.size();
7733            r = null;
7734            for (i=0; i<N; i++) {
7735                PackageParser.Permission p = pkg.permissions.get(i);
7736
7737                // Assume by default that we did not install this permission into the system.
7738                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7739
7740                // Now that permission groups have a special meaning, we ignore permission
7741                // groups for legacy apps to prevent unexpected behavior. In particular,
7742                // permissions for one app being granted to someone just becuase they happen
7743                // to be in a group defined by another app (before this had no implications).
7744                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7745                    p.group = mPermissionGroups.get(p.info.group);
7746                    // Warn for a permission in an unknown group.
7747                    if (p.info.group != null && p.group == null) {
7748                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7749                                + p.info.packageName + " in an unknown group " + p.info.group);
7750                    }
7751                }
7752
7753                ArrayMap<String, BasePermission> permissionMap =
7754                        p.tree ? mSettings.mPermissionTrees
7755                                : mSettings.mPermissions;
7756                BasePermission bp = permissionMap.get(p.info.name);
7757
7758                // Allow system apps to redefine non-system permissions
7759                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7760                    final boolean currentOwnerIsSystem = (bp.perm != null
7761                            && isSystemApp(bp.perm.owner));
7762                    if (isSystemApp(p.owner)) {
7763                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7764                            // It's a built-in permission and no owner, take ownership now
7765                            bp.packageSetting = pkgSetting;
7766                            bp.perm = p;
7767                            bp.uid = pkg.applicationInfo.uid;
7768                            bp.sourcePackage = p.info.packageName;
7769                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7770                        } else if (!currentOwnerIsSystem) {
7771                            String msg = "New decl " + p.owner + " of permission  "
7772                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7773                            reportSettingsProblem(Log.WARN, msg);
7774                            bp = null;
7775                        }
7776                    }
7777                }
7778
7779                if (bp == null) {
7780                    bp = new BasePermission(p.info.name, p.info.packageName,
7781                            BasePermission.TYPE_NORMAL);
7782                    permissionMap.put(p.info.name, bp);
7783                }
7784
7785                if (bp.perm == null) {
7786                    if (bp.sourcePackage == null
7787                            || bp.sourcePackage.equals(p.info.packageName)) {
7788                        BasePermission tree = findPermissionTreeLP(p.info.name);
7789                        if (tree == null
7790                                || tree.sourcePackage.equals(p.info.packageName)) {
7791                            bp.packageSetting = pkgSetting;
7792                            bp.perm = p;
7793                            bp.uid = pkg.applicationInfo.uid;
7794                            bp.sourcePackage = p.info.packageName;
7795                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7796                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7797                                if (r == null) {
7798                                    r = new StringBuilder(256);
7799                                } else {
7800                                    r.append(' ');
7801                                }
7802                                r.append(p.info.name);
7803                            }
7804                        } else {
7805                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7806                                    + p.info.packageName + " ignored: base tree "
7807                                    + tree.name + " is from package "
7808                                    + tree.sourcePackage);
7809                        }
7810                    } else {
7811                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7812                                + p.info.packageName + " ignored: original from "
7813                                + bp.sourcePackage);
7814                    }
7815                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7816                    if (r == null) {
7817                        r = new StringBuilder(256);
7818                    } else {
7819                        r.append(' ');
7820                    }
7821                    r.append("DUP:");
7822                    r.append(p.info.name);
7823                }
7824                if (bp.perm == p) {
7825                    bp.protectionLevel = p.info.protectionLevel;
7826                }
7827            }
7828
7829            if (r != null) {
7830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7831            }
7832
7833            N = pkg.instrumentation.size();
7834            r = null;
7835            for (i=0; i<N; i++) {
7836                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7837                a.info.packageName = pkg.applicationInfo.packageName;
7838                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7839                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7840                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7841                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7842                a.info.dataDir = pkg.applicationInfo.dataDir;
7843                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7844                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7845
7846                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7847                // need other information about the application, like the ABI and what not ?
7848                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7849                mInstrumentation.put(a.getComponentName(), a);
7850                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7851                    if (r == null) {
7852                        r = new StringBuilder(256);
7853                    } else {
7854                        r.append(' ');
7855                    }
7856                    r.append(a.info.name);
7857                }
7858            }
7859            if (r != null) {
7860                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7861            }
7862
7863            if (pkg.protectedBroadcasts != null) {
7864                N = pkg.protectedBroadcasts.size();
7865                for (i=0; i<N; i++) {
7866                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7867                }
7868            }
7869
7870            pkgSetting.setTimeStamp(scanFileTime);
7871
7872            // Create idmap files for pairs of (packages, overlay packages).
7873            // Note: "android", ie framework-res.apk, is handled by native layers.
7874            if (pkg.mOverlayTarget != null) {
7875                // This is an overlay package.
7876                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7877                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7878                        mOverlays.put(pkg.mOverlayTarget,
7879                                new ArrayMap<String, PackageParser.Package>());
7880                    }
7881                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7882                    map.put(pkg.packageName, pkg);
7883                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7884                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7885                        createIdmapFailed = true;
7886                    }
7887                }
7888            } else if (mOverlays.containsKey(pkg.packageName) &&
7889                    !pkg.packageName.equals("android")) {
7890                // This is a regular package, with one or more known overlay packages.
7891                createIdmapsForPackageLI(pkg);
7892            }
7893        }
7894
7895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7896
7897        if (createIdmapFailed) {
7898            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7899                    "scanPackageLI failed to createIdmap");
7900        }
7901        return pkg;
7902    }
7903
7904    /**
7905     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7906     * is derived purely on the basis of the contents of {@code scanFile} and
7907     * {@code cpuAbiOverride}.
7908     *
7909     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7910     */
7911    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7912                                 String cpuAbiOverride, boolean extractLibs)
7913            throws PackageManagerException {
7914        // TODO: We can probably be smarter about this stuff. For installed apps,
7915        // we can calculate this information at install time once and for all. For
7916        // system apps, we can probably assume that this information doesn't change
7917        // after the first boot scan. As things stand, we do lots of unnecessary work.
7918
7919        // Give ourselves some initial paths; we'll come back for another
7920        // pass once we've determined ABI below.
7921        setNativeLibraryPaths(pkg);
7922
7923        // We would never need to extract libs for forward-locked and external packages,
7924        // since the container service will do it for us. We shouldn't attempt to
7925        // extract libs from system app when it was not updated.
7926        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7927                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7928            extractLibs = false;
7929        }
7930
7931        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7932        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7933
7934        NativeLibraryHelper.Handle handle = null;
7935        try {
7936            handle = NativeLibraryHelper.Handle.create(pkg);
7937            // TODO(multiArch): This can be null for apps that didn't go through the
7938            // usual installation process. We can calculate it again, like we
7939            // do during install time.
7940            //
7941            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7942            // unnecessary.
7943            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7944
7945            // Null out the abis so that they can be recalculated.
7946            pkg.applicationInfo.primaryCpuAbi = null;
7947            pkg.applicationInfo.secondaryCpuAbi = null;
7948            if (isMultiArch(pkg.applicationInfo)) {
7949                // Warn if we've set an abiOverride for multi-lib packages..
7950                // By definition, we need to copy both 32 and 64 bit libraries for
7951                // such packages.
7952                if (pkg.cpuAbiOverride != null
7953                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7954                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7955                }
7956
7957                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7958                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7959                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7960                    if (extractLibs) {
7961                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7962                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7963                                useIsaSpecificSubdirs);
7964                    } else {
7965                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7966                    }
7967                }
7968
7969                maybeThrowExceptionForMultiArchCopy(
7970                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7971
7972                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7973                    if (extractLibs) {
7974                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7975                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7976                                useIsaSpecificSubdirs);
7977                    } else {
7978                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7979                    }
7980                }
7981
7982                maybeThrowExceptionForMultiArchCopy(
7983                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7984
7985                if (abi64 >= 0) {
7986                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7987                }
7988
7989                if (abi32 >= 0) {
7990                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7991                    if (abi64 >= 0) {
7992                        pkg.applicationInfo.secondaryCpuAbi = abi;
7993                    } else {
7994                        pkg.applicationInfo.primaryCpuAbi = abi;
7995                    }
7996                }
7997            } else {
7998                String[] abiList = (cpuAbiOverride != null) ?
7999                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8000
8001                // Enable gross and lame hacks for apps that are built with old
8002                // SDK tools. We must scan their APKs for renderscript bitcode and
8003                // not launch them if it's present. Don't bother checking on devices
8004                // that don't have 64 bit support.
8005                boolean needsRenderScriptOverride = false;
8006                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8007                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8008                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8009                    needsRenderScriptOverride = true;
8010                }
8011
8012                final int copyRet;
8013                if (extractLibs) {
8014                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8015                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8016                } else {
8017                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8018                }
8019
8020                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8021                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8022                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8023                }
8024
8025                if (copyRet >= 0) {
8026                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8027                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8028                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8029                } else if (needsRenderScriptOverride) {
8030                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8031                }
8032            }
8033        } catch (IOException ioe) {
8034            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8035        } finally {
8036            IoUtils.closeQuietly(handle);
8037        }
8038
8039        // Now that we've calculated the ABIs and determined if it's an internal app,
8040        // we will go ahead and populate the nativeLibraryPath.
8041        setNativeLibraryPaths(pkg);
8042    }
8043
8044    /**
8045     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8046     * i.e, so that all packages can be run inside a single process if required.
8047     *
8048     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8049     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8050     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8051     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8052     * updating a package that belongs to a shared user.
8053     *
8054     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8055     * adds unnecessary complexity.
8056     */
8057    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8058            PackageParser.Package scannedPackage, boolean bootComplete) {
8059        String requiredInstructionSet = null;
8060        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8061            requiredInstructionSet = VMRuntime.getInstructionSet(
8062                     scannedPackage.applicationInfo.primaryCpuAbi);
8063        }
8064
8065        PackageSetting requirer = null;
8066        for (PackageSetting ps : packagesForUser) {
8067            // If packagesForUser contains scannedPackage, we skip it. This will happen
8068            // when scannedPackage is an update of an existing package. Without this check,
8069            // we will never be able to change the ABI of any package belonging to a shared
8070            // user, even if it's compatible with other packages.
8071            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8072                if (ps.primaryCpuAbiString == null) {
8073                    continue;
8074                }
8075
8076                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8077                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8078                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8079                    // this but there's not much we can do.
8080                    String errorMessage = "Instruction set mismatch, "
8081                            + ((requirer == null) ? "[caller]" : requirer)
8082                            + " requires " + requiredInstructionSet + " whereas " + ps
8083                            + " requires " + instructionSet;
8084                    Slog.w(TAG, errorMessage);
8085                }
8086
8087                if (requiredInstructionSet == null) {
8088                    requiredInstructionSet = instructionSet;
8089                    requirer = ps;
8090                }
8091            }
8092        }
8093
8094        if (requiredInstructionSet != null) {
8095            String adjustedAbi;
8096            if (requirer != null) {
8097                // requirer != null implies that either scannedPackage was null or that scannedPackage
8098                // did not require an ABI, in which case we have to adjust scannedPackage to match
8099                // the ABI of the set (which is the same as requirer's ABI)
8100                adjustedAbi = requirer.primaryCpuAbiString;
8101                if (scannedPackage != null) {
8102                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8103                }
8104            } else {
8105                // requirer == null implies that we're updating all ABIs in the set to
8106                // match scannedPackage.
8107                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8108            }
8109
8110            for (PackageSetting ps : packagesForUser) {
8111                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8112                    if (ps.primaryCpuAbiString != null) {
8113                        continue;
8114                    }
8115
8116                    ps.primaryCpuAbiString = adjustedAbi;
8117                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8118                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8119                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8120                        mInstaller.rmdex(ps.codePathString,
8121                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8122                    }
8123                }
8124            }
8125        }
8126    }
8127
8128    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8129        synchronized (mPackages) {
8130            mResolverReplaced = true;
8131            // Set up information for custom user intent resolution activity.
8132            mResolveActivity.applicationInfo = pkg.applicationInfo;
8133            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8134            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8135            mResolveActivity.processName = pkg.applicationInfo.packageName;
8136            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8137            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8138                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8139            mResolveActivity.theme = 0;
8140            mResolveActivity.exported = true;
8141            mResolveActivity.enabled = true;
8142            mResolveInfo.activityInfo = mResolveActivity;
8143            mResolveInfo.priority = 0;
8144            mResolveInfo.preferredOrder = 0;
8145            mResolveInfo.match = 0;
8146            mResolveComponentName = mCustomResolverComponentName;
8147            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8148                    mResolveComponentName);
8149        }
8150    }
8151
8152    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8153        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8154
8155        // Set up information for ephemeral installer activity
8156        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8157        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8158        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8159        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8160        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8161        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8162                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8163        mEphemeralInstallerActivity.theme = 0;
8164        mEphemeralInstallerActivity.exported = true;
8165        mEphemeralInstallerActivity.enabled = true;
8166        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8167        mEphemeralInstallerInfo.priority = 0;
8168        mEphemeralInstallerInfo.preferredOrder = 0;
8169        mEphemeralInstallerInfo.match = 0;
8170
8171        if (DEBUG_EPHEMERAL) {
8172            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8173        }
8174    }
8175
8176    private static String calculateBundledApkRoot(final String codePathString) {
8177        final File codePath = new File(codePathString);
8178        final File codeRoot;
8179        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8180            codeRoot = Environment.getRootDirectory();
8181        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8182            codeRoot = Environment.getOemDirectory();
8183        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8184            codeRoot = Environment.getVendorDirectory();
8185        } else {
8186            // Unrecognized code path; take its top real segment as the apk root:
8187            // e.g. /something/app/blah.apk => /something
8188            try {
8189                File f = codePath.getCanonicalFile();
8190                File parent = f.getParentFile();    // non-null because codePath is a file
8191                File tmp;
8192                while ((tmp = parent.getParentFile()) != null) {
8193                    f = parent;
8194                    parent = tmp;
8195                }
8196                codeRoot = f;
8197                Slog.w(TAG, "Unrecognized code path "
8198                        + codePath + " - using " + codeRoot);
8199            } catch (IOException e) {
8200                // Can't canonicalize the code path -- shenanigans?
8201                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8202                return Environment.getRootDirectory().getPath();
8203            }
8204        }
8205        return codeRoot.getPath();
8206    }
8207
8208    /**
8209     * Derive and set the location of native libraries for the given package,
8210     * which varies depending on where and how the package was installed.
8211     */
8212    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8213        final ApplicationInfo info = pkg.applicationInfo;
8214        final String codePath = pkg.codePath;
8215        final File codeFile = new File(codePath);
8216        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8217        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8218
8219        info.nativeLibraryRootDir = null;
8220        info.nativeLibraryRootRequiresIsa = false;
8221        info.nativeLibraryDir = null;
8222        info.secondaryNativeLibraryDir = null;
8223
8224        if (isApkFile(codeFile)) {
8225            // Monolithic install
8226            if (bundledApp) {
8227                // If "/system/lib64/apkname" exists, assume that is the per-package
8228                // native library directory to use; otherwise use "/system/lib/apkname".
8229                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8230                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8231                        getPrimaryInstructionSet(info));
8232
8233                // This is a bundled system app so choose the path based on the ABI.
8234                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8235                // is just the default path.
8236                final String apkName = deriveCodePathName(codePath);
8237                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8238                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8239                        apkName).getAbsolutePath();
8240
8241                if (info.secondaryCpuAbi != null) {
8242                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8243                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8244                            secondaryLibDir, apkName).getAbsolutePath();
8245                }
8246            } else if (asecApp) {
8247                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8248                        .getAbsolutePath();
8249            } else {
8250                final String apkName = deriveCodePathName(codePath);
8251                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8252                        .getAbsolutePath();
8253            }
8254
8255            info.nativeLibraryRootRequiresIsa = false;
8256            info.nativeLibraryDir = info.nativeLibraryRootDir;
8257        } else {
8258            // Cluster install
8259            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8260            info.nativeLibraryRootRequiresIsa = true;
8261
8262            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8263                    getPrimaryInstructionSet(info)).getAbsolutePath();
8264
8265            if (info.secondaryCpuAbi != null) {
8266                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8267                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8268            }
8269        }
8270    }
8271
8272    /**
8273     * Calculate the abis and roots for a bundled app. These can uniquely
8274     * be determined from the contents of the system partition, i.e whether
8275     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8276     * of this information, and instead assume that the system was built
8277     * sensibly.
8278     */
8279    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8280                                           PackageSetting pkgSetting) {
8281        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8282
8283        // If "/system/lib64/apkname" exists, assume that is the per-package
8284        // native library directory to use; otherwise use "/system/lib/apkname".
8285        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8286        setBundledAppAbi(pkg, apkRoot, apkName);
8287        // pkgSetting might be null during rescan following uninstall of updates
8288        // to a bundled app, so accommodate that possibility.  The settings in
8289        // that case will be established later from the parsed package.
8290        //
8291        // If the settings aren't null, sync them up with what we've just derived.
8292        // note that apkRoot isn't stored in the package settings.
8293        if (pkgSetting != null) {
8294            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8295            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8296        }
8297    }
8298
8299    /**
8300     * Deduces the ABI of a bundled app and sets the relevant fields on the
8301     * parsed pkg object.
8302     *
8303     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8304     *        under which system libraries are installed.
8305     * @param apkName the name of the installed package.
8306     */
8307    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8308        final File codeFile = new File(pkg.codePath);
8309
8310        final boolean has64BitLibs;
8311        final boolean has32BitLibs;
8312        if (isApkFile(codeFile)) {
8313            // Monolithic install
8314            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8315            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8316        } else {
8317            // Cluster install
8318            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8319            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8320                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8321                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8322                has64BitLibs = (new File(rootDir, isa)).exists();
8323            } else {
8324                has64BitLibs = false;
8325            }
8326            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8327                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8328                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8329                has32BitLibs = (new File(rootDir, isa)).exists();
8330            } else {
8331                has32BitLibs = false;
8332            }
8333        }
8334
8335        if (has64BitLibs && !has32BitLibs) {
8336            // The package has 64 bit libs, but not 32 bit libs. Its primary
8337            // ABI should be 64 bit. We can safely assume here that the bundled
8338            // native libraries correspond to the most preferred ABI in the list.
8339
8340            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8341            pkg.applicationInfo.secondaryCpuAbi = null;
8342        } else if (has32BitLibs && !has64BitLibs) {
8343            // The package has 32 bit libs but not 64 bit libs. Its primary
8344            // ABI should be 32 bit.
8345
8346            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8347            pkg.applicationInfo.secondaryCpuAbi = null;
8348        } else if (has32BitLibs && has64BitLibs) {
8349            // The application has both 64 and 32 bit bundled libraries. We check
8350            // here that the app declares multiArch support, and warn if it doesn't.
8351            //
8352            // We will be lenient here and record both ABIs. The primary will be the
8353            // ABI that's higher on the list, i.e, a device that's configured to prefer
8354            // 64 bit apps will see a 64 bit primary ABI,
8355
8356            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8357                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8358            }
8359
8360            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8361                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8362                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8363            } else {
8364                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8365                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8366            }
8367        } else {
8368            pkg.applicationInfo.primaryCpuAbi = null;
8369            pkg.applicationInfo.secondaryCpuAbi = null;
8370        }
8371    }
8372
8373    private void killApplication(String pkgName, int appId, String reason) {
8374        // Request the ActivityManager to kill the process(only for existing packages)
8375        // so that we do not end up in a confused state while the user is still using the older
8376        // version of the application while the new one gets installed.
8377        IActivityManager am = ActivityManagerNative.getDefault();
8378        if (am != null) {
8379            try {
8380                am.killApplicationWithAppId(pkgName, appId, reason);
8381            } catch (RemoteException e) {
8382            }
8383        }
8384    }
8385
8386    void removePackageLI(PackageSetting ps, boolean chatty) {
8387        if (DEBUG_INSTALL) {
8388            if (chatty)
8389                Log.d(TAG, "Removing package " + ps.name);
8390        }
8391
8392        // writer
8393        synchronized (mPackages) {
8394            mPackages.remove(ps.name);
8395            final PackageParser.Package pkg = ps.pkg;
8396            if (pkg != null) {
8397                cleanPackageDataStructuresLILPw(pkg, chatty);
8398            }
8399        }
8400    }
8401
8402    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8403        if (DEBUG_INSTALL) {
8404            if (chatty)
8405                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8406        }
8407
8408        // writer
8409        synchronized (mPackages) {
8410            mPackages.remove(pkg.applicationInfo.packageName);
8411            cleanPackageDataStructuresLILPw(pkg, chatty);
8412        }
8413    }
8414
8415    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8416        int N = pkg.providers.size();
8417        StringBuilder r = null;
8418        int i;
8419        for (i=0; i<N; i++) {
8420            PackageParser.Provider p = pkg.providers.get(i);
8421            mProviders.removeProvider(p);
8422            if (p.info.authority == null) {
8423
8424                /* There was another ContentProvider with this authority when
8425                 * this app was installed so this authority is null,
8426                 * Ignore it as we don't have to unregister the provider.
8427                 */
8428                continue;
8429            }
8430            String names[] = p.info.authority.split(";");
8431            for (int j = 0; j < names.length; j++) {
8432                if (mProvidersByAuthority.get(names[j]) == p) {
8433                    mProvidersByAuthority.remove(names[j]);
8434                    if (DEBUG_REMOVE) {
8435                        if (chatty)
8436                            Log.d(TAG, "Unregistered content provider: " + names[j]
8437                                    + ", className = " + p.info.name + ", isSyncable = "
8438                                    + p.info.isSyncable);
8439                    }
8440                }
8441            }
8442            if (DEBUG_REMOVE && chatty) {
8443                if (r == null) {
8444                    r = new StringBuilder(256);
8445                } else {
8446                    r.append(' ');
8447                }
8448                r.append(p.info.name);
8449            }
8450        }
8451        if (r != null) {
8452            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8453        }
8454
8455        N = pkg.services.size();
8456        r = null;
8457        for (i=0; i<N; i++) {
8458            PackageParser.Service s = pkg.services.get(i);
8459            mServices.removeService(s);
8460            if (chatty) {
8461                if (r == null) {
8462                    r = new StringBuilder(256);
8463                } else {
8464                    r.append(' ');
8465                }
8466                r.append(s.info.name);
8467            }
8468        }
8469        if (r != null) {
8470            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8471        }
8472
8473        N = pkg.receivers.size();
8474        r = null;
8475        for (i=0; i<N; i++) {
8476            PackageParser.Activity a = pkg.receivers.get(i);
8477            mReceivers.removeActivity(a, "receiver");
8478            if (DEBUG_REMOVE && chatty) {
8479                if (r == null) {
8480                    r = new StringBuilder(256);
8481                } else {
8482                    r.append(' ');
8483                }
8484                r.append(a.info.name);
8485            }
8486        }
8487        if (r != null) {
8488            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8489        }
8490
8491        N = pkg.activities.size();
8492        r = null;
8493        for (i=0; i<N; i++) {
8494            PackageParser.Activity a = pkg.activities.get(i);
8495            mActivities.removeActivity(a, "activity");
8496            if (DEBUG_REMOVE && chatty) {
8497                if (r == null) {
8498                    r = new StringBuilder(256);
8499                } else {
8500                    r.append(' ');
8501                }
8502                r.append(a.info.name);
8503            }
8504        }
8505        if (r != null) {
8506            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8507        }
8508
8509        N = pkg.permissions.size();
8510        r = null;
8511        for (i=0; i<N; i++) {
8512            PackageParser.Permission p = pkg.permissions.get(i);
8513            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8514            if (bp == null) {
8515                bp = mSettings.mPermissionTrees.get(p.info.name);
8516            }
8517            if (bp != null && bp.perm == p) {
8518                bp.perm = null;
8519                if (DEBUG_REMOVE && chatty) {
8520                    if (r == null) {
8521                        r = new StringBuilder(256);
8522                    } else {
8523                        r.append(' ');
8524                    }
8525                    r.append(p.info.name);
8526                }
8527            }
8528            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8529                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8530                if (appOpPkgs != null) {
8531                    appOpPkgs.remove(pkg.packageName);
8532                }
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8537        }
8538
8539        N = pkg.requestedPermissions.size();
8540        r = null;
8541        for (i=0; i<N; i++) {
8542            String perm = pkg.requestedPermissions.get(i);
8543            BasePermission bp = mSettings.mPermissions.get(perm);
8544            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8545                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8546                if (appOpPkgs != null) {
8547                    appOpPkgs.remove(pkg.packageName);
8548                    if (appOpPkgs.isEmpty()) {
8549                        mAppOpPermissionPackages.remove(perm);
8550                    }
8551                }
8552            }
8553        }
8554        if (r != null) {
8555            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8556        }
8557
8558        N = pkg.instrumentation.size();
8559        r = null;
8560        for (i=0; i<N; i++) {
8561            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8562            mInstrumentation.remove(a.getComponentName());
8563            if (DEBUG_REMOVE && chatty) {
8564                if (r == null) {
8565                    r = new StringBuilder(256);
8566                } else {
8567                    r.append(' ');
8568                }
8569                r.append(a.info.name);
8570            }
8571        }
8572        if (r != null) {
8573            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8574        }
8575
8576        r = null;
8577        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8578            // Only system apps can hold shared libraries.
8579            if (pkg.libraryNames != null) {
8580                for (i=0; i<pkg.libraryNames.size(); i++) {
8581                    String name = pkg.libraryNames.get(i);
8582                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8583                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8584                        mSharedLibraries.remove(name);
8585                        if (DEBUG_REMOVE && chatty) {
8586                            if (r == null) {
8587                                r = new StringBuilder(256);
8588                            } else {
8589                                r.append(' ');
8590                            }
8591                            r.append(name);
8592                        }
8593                    }
8594                }
8595            }
8596        }
8597        if (r != null) {
8598            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8599        }
8600    }
8601
8602    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8603        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8604            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8605                return true;
8606            }
8607        }
8608        return false;
8609    }
8610
8611    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8612    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8613    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8614
8615    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8616            int flags) {
8617        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8618        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8619    }
8620
8621    private void updatePermissionsLPw(String changingPkg,
8622            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8623        // Make sure there are no dangling permission trees.
8624        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8625        while (it.hasNext()) {
8626            final BasePermission bp = it.next();
8627            if (bp.packageSetting == null) {
8628                // We may not yet have parsed the package, so just see if
8629                // we still know about its settings.
8630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8631            }
8632            if (bp.packageSetting == null) {
8633                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8634                        + " from package " + bp.sourcePackage);
8635                it.remove();
8636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8638                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8639                            + " from package " + bp.sourcePackage);
8640                    flags |= UPDATE_PERMISSIONS_ALL;
8641                    it.remove();
8642                }
8643            }
8644        }
8645
8646        // Make sure all dynamic permissions have been assigned to a package,
8647        // and make sure there are no dangling permissions.
8648        it = mSettings.mPermissions.values().iterator();
8649        while (it.hasNext()) {
8650            final BasePermission bp = it.next();
8651            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8652                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8653                        + bp.name + " pkg=" + bp.sourcePackage
8654                        + " info=" + bp.pendingInfo);
8655                if (bp.packageSetting == null && bp.pendingInfo != null) {
8656                    final BasePermission tree = findPermissionTreeLP(bp.name);
8657                    if (tree != null && tree.perm != null) {
8658                        bp.packageSetting = tree.packageSetting;
8659                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8660                                new PermissionInfo(bp.pendingInfo));
8661                        bp.perm.info.packageName = tree.perm.info.packageName;
8662                        bp.perm.info.name = bp.name;
8663                        bp.uid = tree.uid;
8664                    }
8665                }
8666            }
8667            if (bp.packageSetting == null) {
8668                // We may not yet have parsed the package, so just see if
8669                // we still know about its settings.
8670                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8671            }
8672            if (bp.packageSetting == null) {
8673                Slog.w(TAG, "Removing dangling permission: " + bp.name
8674                        + " from package " + bp.sourcePackage);
8675                it.remove();
8676            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8677                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8678                    Slog.i(TAG, "Removing old permission: " + bp.name
8679                            + " from package " + bp.sourcePackage);
8680                    flags |= UPDATE_PERMISSIONS_ALL;
8681                    it.remove();
8682                }
8683            }
8684        }
8685
8686        // Now update the permissions for all packages, in particular
8687        // replace the granted permissions of the system packages.
8688        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8689            for (PackageParser.Package pkg : mPackages.values()) {
8690                if (pkg != pkgInfo) {
8691                    // Only replace for packages on requested volume
8692                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8693                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8694                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8695                    grantPermissionsLPw(pkg, replace, changingPkg);
8696                }
8697            }
8698        }
8699
8700        if (pkgInfo != null) {
8701            // Only replace for packages on requested volume
8702            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8703            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8704                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8705            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8706        }
8707    }
8708
8709    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8710            String packageOfInterest) {
8711        // IMPORTANT: There are two types of permissions: install and runtime.
8712        // Install time permissions are granted when the app is installed to
8713        // all device users and users added in the future. Runtime permissions
8714        // are granted at runtime explicitly to specific users. Normal and signature
8715        // protected permissions are install time permissions. Dangerous permissions
8716        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8717        // otherwise they are runtime permissions. This function does not manage
8718        // runtime permissions except for the case an app targeting Lollipop MR1
8719        // being upgraded to target a newer SDK, in which case dangerous permissions
8720        // are transformed from install time to runtime ones.
8721
8722        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8723        if (ps == null) {
8724            return;
8725        }
8726
8727        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8728
8729        PermissionsState permissionsState = ps.getPermissionsState();
8730        PermissionsState origPermissions = permissionsState;
8731
8732        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8733
8734        boolean runtimePermissionsRevoked = false;
8735        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8736
8737        boolean changedInstallPermission = false;
8738
8739        if (replace) {
8740            ps.installPermissionsFixed = false;
8741            if (!ps.isSharedUser()) {
8742                origPermissions = new PermissionsState(permissionsState);
8743                permissionsState.reset();
8744            } else {
8745                // We need to know only about runtime permission changes since the
8746                // calling code always writes the install permissions state but
8747                // the runtime ones are written only if changed. The only cases of
8748                // changed runtime permissions here are promotion of an install to
8749                // runtime and revocation of a runtime from a shared user.
8750                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8751                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8752                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8753                    runtimePermissionsRevoked = true;
8754                }
8755            }
8756        }
8757
8758        permissionsState.setGlobalGids(mGlobalGids);
8759
8760        final int N = pkg.requestedPermissions.size();
8761        for (int i=0; i<N; i++) {
8762            final String name = pkg.requestedPermissions.get(i);
8763            final BasePermission bp = mSettings.mPermissions.get(name);
8764
8765            if (DEBUG_INSTALL) {
8766                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8767            }
8768
8769            if (bp == null || bp.packageSetting == null) {
8770                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8771                    Slog.w(TAG, "Unknown permission " + name
8772                            + " in package " + pkg.packageName);
8773                }
8774                continue;
8775            }
8776
8777            final String perm = bp.name;
8778            boolean allowedSig = false;
8779            int grant = GRANT_DENIED;
8780
8781            // Keep track of app op permissions.
8782            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8783                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8784                if (pkgs == null) {
8785                    pkgs = new ArraySet<>();
8786                    mAppOpPermissionPackages.put(bp.name, pkgs);
8787                }
8788                pkgs.add(pkg.packageName);
8789            }
8790
8791            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8792            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8793                    >= Build.VERSION_CODES.M;
8794            switch (level) {
8795                case PermissionInfo.PROTECTION_NORMAL: {
8796                    // For all apps normal permissions are install time ones.
8797                    grant = GRANT_INSTALL;
8798                } break;
8799
8800                case PermissionInfo.PROTECTION_DANGEROUS: {
8801                    // If a permission review is required for legacy apps we represent
8802                    // their permissions as always granted runtime ones since we need
8803                    // to keep the review required permission flag per user while an
8804                    // install permission's state is shared across all users.
8805                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8806                        // For legacy apps dangerous permissions are install time ones.
8807                        grant = GRANT_INSTALL;
8808                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8809                        // For legacy apps that became modern, install becomes runtime.
8810                        grant = GRANT_UPGRADE;
8811                    } else if (mPromoteSystemApps
8812                            && isSystemApp(ps)
8813                            && mExistingSystemPackages.contains(ps.name)) {
8814                        // For legacy system apps, install becomes runtime.
8815                        // We cannot check hasInstallPermission() for system apps since those
8816                        // permissions were granted implicitly and not persisted pre-M.
8817                        grant = GRANT_UPGRADE;
8818                    } else {
8819                        // For modern apps keep runtime permissions unchanged.
8820                        grant = GRANT_RUNTIME;
8821                    }
8822                } break;
8823
8824                case PermissionInfo.PROTECTION_SIGNATURE: {
8825                    // For all apps signature permissions are install time ones.
8826                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8827                    if (allowedSig) {
8828                        grant = GRANT_INSTALL;
8829                    }
8830                } break;
8831            }
8832
8833            if (DEBUG_INSTALL) {
8834                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8835            }
8836
8837            if (grant != GRANT_DENIED) {
8838                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8839                    // If this is an existing, non-system package, then
8840                    // we can't add any new permissions to it.
8841                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8842                        // Except...  if this is a permission that was added
8843                        // to the platform (note: need to only do this when
8844                        // updating the platform).
8845                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8846                            grant = GRANT_DENIED;
8847                        }
8848                    }
8849                }
8850
8851                switch (grant) {
8852                    case GRANT_INSTALL: {
8853                        // Revoke this as runtime permission to handle the case of
8854                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8855                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8856                            if (origPermissions.getRuntimePermissionState(
8857                                    bp.name, userId) != null) {
8858                                // Revoke the runtime permission and clear the flags.
8859                                origPermissions.revokeRuntimePermission(bp, userId);
8860                                origPermissions.updatePermissionFlags(bp, userId,
8861                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8862                                // If we revoked a permission permission, we have to write.
8863                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8864                                        changedRuntimePermissionUserIds, userId);
8865                            }
8866                        }
8867                        // Grant an install permission.
8868                        if (permissionsState.grantInstallPermission(bp) !=
8869                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8870                            changedInstallPermission = true;
8871                        }
8872                    } break;
8873
8874                    case GRANT_RUNTIME: {
8875                        // Grant previously granted runtime permissions.
8876                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8877                            PermissionState permissionState = origPermissions
8878                                    .getRuntimePermissionState(bp.name, userId);
8879                            int flags = permissionState != null
8880                                    ? permissionState.getFlags() : 0;
8881                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8882                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8883                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8884                                    // If we cannot put the permission as it was, we have to write.
8885                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8886                                            changedRuntimePermissionUserIds, userId);
8887                                }
8888                                // If the app supports runtime permissions no need for a review.
8889                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8890                                        && appSupportsRuntimePermissions
8891                                        && (flags & PackageManager
8892                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8893                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8894                                    // Since we changed the flags, we have to write.
8895                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8896                                            changedRuntimePermissionUserIds, userId);
8897                                }
8898                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8899                                    && !appSupportsRuntimePermissions) {
8900                                // For legacy apps that need a permission review, every new
8901                                // runtime permission is granted but it is pending a review.
8902                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8903                                    permissionsState.grantRuntimePermission(bp, userId);
8904                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8905                                    // We changed the permission and flags, hence have to write.
8906                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8907                                            changedRuntimePermissionUserIds, userId);
8908                                }
8909                            }
8910                            // Propagate the permission flags.
8911                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8912                        }
8913                    } break;
8914
8915                    case GRANT_UPGRADE: {
8916                        // Grant runtime permissions for a previously held install permission.
8917                        PermissionState permissionState = origPermissions
8918                                .getInstallPermissionState(bp.name);
8919                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8920
8921                        if (origPermissions.revokeInstallPermission(bp)
8922                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8923                            // We will be transferring the permission flags, so clear them.
8924                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8925                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8926                            changedInstallPermission = true;
8927                        }
8928
8929                        // If the permission is not to be promoted to runtime we ignore it and
8930                        // also its other flags as they are not applicable to install permissions.
8931                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8932                            for (int userId : currentUserIds) {
8933                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8934                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8935                                    // Transfer the permission flags.
8936                                    permissionsState.updatePermissionFlags(bp, userId,
8937                                            flags, flags);
8938                                    // If we granted the permission, we have to write.
8939                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8940                                            changedRuntimePermissionUserIds, userId);
8941                                }
8942                            }
8943                        }
8944                    } break;
8945
8946                    default: {
8947                        if (packageOfInterest == null
8948                                || packageOfInterest.equals(pkg.packageName)) {
8949                            Slog.w(TAG, "Not granting permission " + perm
8950                                    + " to package " + pkg.packageName
8951                                    + " because it was previously installed without");
8952                        }
8953                    } break;
8954                }
8955            } else {
8956                if (permissionsState.revokeInstallPermission(bp) !=
8957                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8958                    // Also drop the permission flags.
8959                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8960                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8961                    changedInstallPermission = true;
8962                    Slog.i(TAG, "Un-granting permission " + perm
8963                            + " from package " + pkg.packageName
8964                            + " (protectionLevel=" + bp.protectionLevel
8965                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8966                            + ")");
8967                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8968                    // Don't print warning for app op permissions, since it is fine for them
8969                    // not to be granted, there is a UI for the user to decide.
8970                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8971                        Slog.w(TAG, "Not granting permission " + perm
8972                                + " to package " + pkg.packageName
8973                                + " (protectionLevel=" + bp.protectionLevel
8974                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8975                                + ")");
8976                    }
8977                }
8978            }
8979        }
8980
8981        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8982                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8983            // This is the first that we have heard about this package, so the
8984            // permissions we have now selected are fixed until explicitly
8985            // changed.
8986            ps.installPermissionsFixed = true;
8987        }
8988
8989        // Persist the runtime permissions state for users with changes. If permissions
8990        // were revoked because no app in the shared user declares them we have to
8991        // write synchronously to avoid losing runtime permissions state.
8992        for (int userId : changedRuntimePermissionUserIds) {
8993            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8994        }
8995
8996        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8997    }
8998
8999    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9000        boolean allowed = false;
9001        final int NP = PackageParser.NEW_PERMISSIONS.length;
9002        for (int ip=0; ip<NP; ip++) {
9003            final PackageParser.NewPermissionInfo npi
9004                    = PackageParser.NEW_PERMISSIONS[ip];
9005            if (npi.name.equals(perm)
9006                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9007                allowed = true;
9008                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9009                        + pkg.packageName);
9010                break;
9011            }
9012        }
9013        return allowed;
9014    }
9015
9016    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9017            BasePermission bp, PermissionsState origPermissions) {
9018        boolean allowed;
9019        allowed = (compareSignatures(
9020                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9021                        == PackageManager.SIGNATURE_MATCH)
9022                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9023                        == PackageManager.SIGNATURE_MATCH);
9024        if (!allowed && (bp.protectionLevel
9025                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9026            if (isSystemApp(pkg)) {
9027                // For updated system applications, a system permission
9028                // is granted only if it had been defined by the original application.
9029                if (pkg.isUpdatedSystemApp()) {
9030                    final PackageSetting sysPs = mSettings
9031                            .getDisabledSystemPkgLPr(pkg.packageName);
9032                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9033                        // If the original was granted this permission, we take
9034                        // that grant decision as read and propagate it to the
9035                        // update.
9036                        if (sysPs.isPrivileged()) {
9037                            allowed = true;
9038                        }
9039                    } else {
9040                        // The system apk may have been updated with an older
9041                        // version of the one on the data partition, but which
9042                        // granted a new system permission that it didn't have
9043                        // before.  In this case we do want to allow the app to
9044                        // now get the new permission if the ancestral apk is
9045                        // privileged to get it.
9046                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9047                            for (int j=0;
9048                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9049                                if (perm.equals(
9050                                        sysPs.pkg.requestedPermissions.get(j))) {
9051                                    allowed = true;
9052                                    break;
9053                                }
9054                            }
9055                        }
9056                    }
9057                } else {
9058                    allowed = isPrivilegedApp(pkg);
9059                }
9060            }
9061        }
9062        if (!allowed) {
9063            if (!allowed && (bp.protectionLevel
9064                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9065                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9066                // If this was a previously normal/dangerous permission that got moved
9067                // to a system permission as part of the runtime permission redesign, then
9068                // we still want to blindly grant it to old apps.
9069                allowed = true;
9070            }
9071            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9072                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9073                // If this permission is to be granted to the system installer and
9074                // this app is an installer, then it gets the permission.
9075                allowed = true;
9076            }
9077            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9078                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9079                // If this permission is to be granted to the system verifier and
9080                // this app is a verifier, then it gets the permission.
9081                allowed = true;
9082            }
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9085                    && isSystemApp(pkg)) {
9086                // Any pre-installed system app is allowed to get this permission.
9087                allowed = true;
9088            }
9089            if (!allowed && (bp.protectionLevel
9090                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9091                // For development permissions, a development permission
9092                // is granted only if it was already granted.
9093                allowed = origPermissions.hasInstallPermission(perm);
9094            }
9095        }
9096        return allowed;
9097    }
9098
9099    final class ActivityIntentResolver
9100            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9102                boolean defaultOnly, int userId) {
9103            if (!sUserManager.exists(userId)) return null;
9104            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9105            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9106        }
9107
9108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9109                int userId) {
9110            if (!sUserManager.exists(userId)) return null;
9111            mFlags = flags;
9112            return super.queryIntent(intent, resolvedType,
9113                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9114        }
9115
9116        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9117                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9118            if (!sUserManager.exists(userId)) return null;
9119            if (packageActivities == null) {
9120                return null;
9121            }
9122            mFlags = flags;
9123            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9124            final int N = packageActivities.size();
9125            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9126                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9127
9128            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9129            for (int i = 0; i < N; ++i) {
9130                intentFilters = packageActivities.get(i).intents;
9131                if (intentFilters != null && intentFilters.size() > 0) {
9132                    PackageParser.ActivityIntentInfo[] array =
9133                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9134                    intentFilters.toArray(array);
9135                    listCut.add(array);
9136                }
9137            }
9138            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9139        }
9140
9141        public final void addActivity(PackageParser.Activity a, String type) {
9142            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9143            mActivities.put(a.getComponentName(), a);
9144            if (DEBUG_SHOW_INFO)
9145                Log.v(
9146                TAG, "  " + type + " " +
9147                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9148            if (DEBUG_SHOW_INFO)
9149                Log.v(TAG, "    Class=" + a.info.name);
9150            final int NI = a.intents.size();
9151            for (int j=0; j<NI; j++) {
9152                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9153                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9154                    intent.setPriority(0);
9155                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9156                            + a.className + " with priority > 0, forcing to 0");
9157                }
9158                if (DEBUG_SHOW_INFO) {
9159                    Log.v(TAG, "    IntentFilter:");
9160                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9161                }
9162                if (!intent.debugCheck()) {
9163                    Log.w(TAG, "==> For Activity " + a.info.name);
9164                }
9165                addFilter(intent);
9166            }
9167        }
9168
9169        public final void removeActivity(PackageParser.Activity a, String type) {
9170            mActivities.remove(a.getComponentName());
9171            if (DEBUG_SHOW_INFO) {
9172                Log.v(TAG, "  " + type + " "
9173                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9174                                : a.info.name) + ":");
9175                Log.v(TAG, "    Class=" + a.info.name);
9176            }
9177            final int NI = a.intents.size();
9178            for (int j=0; j<NI; j++) {
9179                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9180                if (DEBUG_SHOW_INFO) {
9181                    Log.v(TAG, "    IntentFilter:");
9182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9183                }
9184                removeFilter(intent);
9185            }
9186        }
9187
9188        @Override
9189        protected boolean allowFilterResult(
9190                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9191            ActivityInfo filterAi = filter.activity.info;
9192            for (int i=dest.size()-1; i>=0; i--) {
9193                ActivityInfo destAi = dest.get(i).activityInfo;
9194                if (destAi.name == filterAi.name
9195                        && destAi.packageName == filterAi.packageName) {
9196                    return false;
9197                }
9198            }
9199            return true;
9200        }
9201
9202        @Override
9203        protected ActivityIntentInfo[] newArray(int size) {
9204            return new ActivityIntentInfo[size];
9205        }
9206
9207        @Override
9208        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9209            if (!sUserManager.exists(userId)) return true;
9210            PackageParser.Package p = filter.activity.owner;
9211            if (p != null) {
9212                PackageSetting ps = (PackageSetting)p.mExtras;
9213                if (ps != null) {
9214                    // System apps are never considered stopped for purposes of
9215                    // filtering, because there may be no way for the user to
9216                    // actually re-launch them.
9217                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9218                            && ps.getStopped(userId);
9219                }
9220            }
9221            return false;
9222        }
9223
9224        @Override
9225        protected boolean isPackageForFilter(String packageName,
9226                PackageParser.ActivityIntentInfo info) {
9227            return packageName.equals(info.activity.owner.packageName);
9228        }
9229
9230        @Override
9231        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9232                int match, int userId) {
9233            if (!sUserManager.exists(userId)) return null;
9234            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9235                return null;
9236            }
9237            final PackageParser.Activity activity = info.activity;
9238            if (mSafeMode && (activity.info.applicationInfo.flags
9239                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9240                return null;
9241            }
9242            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9243            if (ps == null) {
9244                return null;
9245            }
9246            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9247                    ps.readUserState(userId), userId);
9248            if (ai == null) {
9249                return null;
9250            }
9251            final ResolveInfo res = new ResolveInfo();
9252            res.activityInfo = ai;
9253            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9254                res.filter = info;
9255            }
9256            if (info != null) {
9257                res.handleAllWebDataURI = info.handleAllWebDataURI();
9258            }
9259            res.priority = info.getPriority();
9260            res.preferredOrder = activity.owner.mPreferredOrder;
9261            //System.out.println("Result: " + res.activityInfo.className +
9262            //                   " = " + res.priority);
9263            res.match = match;
9264            res.isDefault = info.hasDefault;
9265            res.labelRes = info.labelRes;
9266            res.nonLocalizedLabel = info.nonLocalizedLabel;
9267            if (userNeedsBadging(userId)) {
9268                res.noResourceId = true;
9269            } else {
9270                res.icon = info.icon;
9271            }
9272            res.iconResourceId = info.icon;
9273            res.system = res.activityInfo.applicationInfo.isSystemApp();
9274            return res;
9275        }
9276
9277        @Override
9278        protected void sortResults(List<ResolveInfo> results) {
9279            Collections.sort(results, mResolvePrioritySorter);
9280        }
9281
9282        @Override
9283        protected void dumpFilter(PrintWriter out, String prefix,
9284                PackageParser.ActivityIntentInfo filter) {
9285            out.print(prefix); out.print(
9286                    Integer.toHexString(System.identityHashCode(filter.activity)));
9287                    out.print(' ');
9288                    filter.activity.printComponentShortName(out);
9289                    out.print(" filter ");
9290                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9291        }
9292
9293        @Override
9294        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9295            return filter.activity;
9296        }
9297
9298        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9299            PackageParser.Activity activity = (PackageParser.Activity)label;
9300            out.print(prefix); out.print(
9301                    Integer.toHexString(System.identityHashCode(activity)));
9302                    out.print(' ');
9303                    activity.printComponentShortName(out);
9304            if (count > 1) {
9305                out.print(" ("); out.print(count); out.print(" filters)");
9306            }
9307            out.println();
9308        }
9309
9310//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9311//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9312//            final List<ResolveInfo> retList = Lists.newArrayList();
9313//            while (i.hasNext()) {
9314//                final ResolveInfo resolveInfo = i.next();
9315//                if (isEnabledLP(resolveInfo.activityInfo)) {
9316//                    retList.add(resolveInfo);
9317//                }
9318//            }
9319//            return retList;
9320//        }
9321
9322        // Keys are String (activity class name), values are Activity.
9323        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9324                = new ArrayMap<ComponentName, PackageParser.Activity>();
9325        private int mFlags;
9326    }
9327
9328    private final class ServiceIntentResolver
9329            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9331                boolean defaultOnly, int userId) {
9332            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9333            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9334        }
9335
9336        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9337                int userId) {
9338            if (!sUserManager.exists(userId)) return null;
9339            mFlags = flags;
9340            return super.queryIntent(intent, resolvedType,
9341                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9342        }
9343
9344        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9345                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9346            if (!sUserManager.exists(userId)) return null;
9347            if (packageServices == null) {
9348                return null;
9349            }
9350            mFlags = flags;
9351            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9352            final int N = packageServices.size();
9353            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9354                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9355
9356            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9357            for (int i = 0; i < N; ++i) {
9358                intentFilters = packageServices.get(i).intents;
9359                if (intentFilters != null && intentFilters.size() > 0) {
9360                    PackageParser.ServiceIntentInfo[] array =
9361                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9362                    intentFilters.toArray(array);
9363                    listCut.add(array);
9364                }
9365            }
9366            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9367        }
9368
9369        public final void addService(PackageParser.Service s) {
9370            mServices.put(s.getComponentName(), s);
9371            if (DEBUG_SHOW_INFO) {
9372                Log.v(TAG, "  "
9373                        + (s.info.nonLocalizedLabel != null
9374                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9375                Log.v(TAG, "    Class=" + s.info.name);
9376            }
9377            final int NI = s.intents.size();
9378            int j;
9379            for (j=0; j<NI; j++) {
9380                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9381                if (DEBUG_SHOW_INFO) {
9382                    Log.v(TAG, "    IntentFilter:");
9383                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9384                }
9385                if (!intent.debugCheck()) {
9386                    Log.w(TAG, "==> For Service " + s.info.name);
9387                }
9388                addFilter(intent);
9389            }
9390        }
9391
9392        public final void removeService(PackageParser.Service s) {
9393            mServices.remove(s.getComponentName());
9394            if (DEBUG_SHOW_INFO) {
9395                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9396                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9397                Log.v(TAG, "    Class=" + s.info.name);
9398            }
9399            final int NI = s.intents.size();
9400            int j;
9401            for (j=0; j<NI; j++) {
9402                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9403                if (DEBUG_SHOW_INFO) {
9404                    Log.v(TAG, "    IntentFilter:");
9405                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9406                }
9407                removeFilter(intent);
9408            }
9409        }
9410
9411        @Override
9412        protected boolean allowFilterResult(
9413                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9414            ServiceInfo filterSi = filter.service.info;
9415            for (int i=dest.size()-1; i>=0; i--) {
9416                ServiceInfo destAi = dest.get(i).serviceInfo;
9417                if (destAi.name == filterSi.name
9418                        && destAi.packageName == filterSi.packageName) {
9419                    return false;
9420                }
9421            }
9422            return true;
9423        }
9424
9425        @Override
9426        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9427            return new PackageParser.ServiceIntentInfo[size];
9428        }
9429
9430        @Override
9431        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9432            if (!sUserManager.exists(userId)) return true;
9433            PackageParser.Package p = filter.service.owner;
9434            if (p != null) {
9435                PackageSetting ps = (PackageSetting)p.mExtras;
9436                if (ps != null) {
9437                    // System apps are never considered stopped for purposes of
9438                    // filtering, because there may be no way for the user to
9439                    // actually re-launch them.
9440                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9441                            && ps.getStopped(userId);
9442                }
9443            }
9444            return false;
9445        }
9446
9447        @Override
9448        protected boolean isPackageForFilter(String packageName,
9449                PackageParser.ServiceIntentInfo info) {
9450            return packageName.equals(info.service.owner.packageName);
9451        }
9452
9453        @Override
9454        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9455                int match, int userId) {
9456            if (!sUserManager.exists(userId)) return null;
9457            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9458            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9459                return null;
9460            }
9461            final PackageParser.Service service = info.service;
9462            if (mSafeMode && (service.info.applicationInfo.flags
9463                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9464                return null;
9465            }
9466            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9467            if (ps == null) {
9468                return null;
9469            }
9470            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9471                    ps.readUserState(userId), userId);
9472            if (si == null) {
9473                return null;
9474            }
9475            final ResolveInfo res = new ResolveInfo();
9476            res.serviceInfo = si;
9477            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9478                res.filter = filter;
9479            }
9480            res.priority = info.getPriority();
9481            res.preferredOrder = service.owner.mPreferredOrder;
9482            res.match = match;
9483            res.isDefault = info.hasDefault;
9484            res.labelRes = info.labelRes;
9485            res.nonLocalizedLabel = info.nonLocalizedLabel;
9486            res.icon = info.icon;
9487            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9488            return res;
9489        }
9490
9491        @Override
9492        protected void sortResults(List<ResolveInfo> results) {
9493            Collections.sort(results, mResolvePrioritySorter);
9494        }
9495
9496        @Override
9497        protected void dumpFilter(PrintWriter out, String prefix,
9498                PackageParser.ServiceIntentInfo filter) {
9499            out.print(prefix); out.print(
9500                    Integer.toHexString(System.identityHashCode(filter.service)));
9501                    out.print(' ');
9502                    filter.service.printComponentShortName(out);
9503                    out.print(" filter ");
9504                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9505        }
9506
9507        @Override
9508        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9509            return filter.service;
9510        }
9511
9512        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9513            PackageParser.Service service = (PackageParser.Service)label;
9514            out.print(prefix); out.print(
9515                    Integer.toHexString(System.identityHashCode(service)));
9516                    out.print(' ');
9517                    service.printComponentShortName(out);
9518            if (count > 1) {
9519                out.print(" ("); out.print(count); out.print(" filters)");
9520            }
9521            out.println();
9522        }
9523
9524//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9525//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9526//            final List<ResolveInfo> retList = Lists.newArrayList();
9527//            while (i.hasNext()) {
9528//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9529//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9530//                    retList.add(resolveInfo);
9531//                }
9532//            }
9533//            return retList;
9534//        }
9535
9536        // Keys are String (activity class name), values are Activity.
9537        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9538                = new ArrayMap<ComponentName, PackageParser.Service>();
9539        private int mFlags;
9540    };
9541
9542    private final class ProviderIntentResolver
9543            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9545                boolean defaultOnly, int userId) {
9546            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9547            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9548        }
9549
9550        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9551                int userId) {
9552            if (!sUserManager.exists(userId))
9553                return null;
9554            mFlags = flags;
9555            return super.queryIntent(intent, resolvedType,
9556                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9557        }
9558
9559        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9560                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9561            if (!sUserManager.exists(userId))
9562                return null;
9563            if (packageProviders == null) {
9564                return null;
9565            }
9566            mFlags = flags;
9567            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9568            final int N = packageProviders.size();
9569            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9570                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9571
9572            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9573            for (int i = 0; i < N; ++i) {
9574                intentFilters = packageProviders.get(i).intents;
9575                if (intentFilters != null && intentFilters.size() > 0) {
9576                    PackageParser.ProviderIntentInfo[] array =
9577                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9578                    intentFilters.toArray(array);
9579                    listCut.add(array);
9580                }
9581            }
9582            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9583        }
9584
9585        public final void addProvider(PackageParser.Provider p) {
9586            if (mProviders.containsKey(p.getComponentName())) {
9587                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9588                return;
9589            }
9590
9591            mProviders.put(p.getComponentName(), p);
9592            if (DEBUG_SHOW_INFO) {
9593                Log.v(TAG, "  "
9594                        + (p.info.nonLocalizedLabel != null
9595                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9596                Log.v(TAG, "    Class=" + p.info.name);
9597            }
9598            final int NI = p.intents.size();
9599            int j;
9600            for (j = 0; j < NI; j++) {
9601                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9602                if (DEBUG_SHOW_INFO) {
9603                    Log.v(TAG, "    IntentFilter:");
9604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9605                }
9606                if (!intent.debugCheck()) {
9607                    Log.w(TAG, "==> For Provider " + p.info.name);
9608                }
9609                addFilter(intent);
9610            }
9611        }
9612
9613        public final void removeProvider(PackageParser.Provider p) {
9614            mProviders.remove(p.getComponentName());
9615            if (DEBUG_SHOW_INFO) {
9616                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9617                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9618                Log.v(TAG, "    Class=" + p.info.name);
9619            }
9620            final int NI = p.intents.size();
9621            int j;
9622            for (j = 0; j < NI; j++) {
9623                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9624                if (DEBUG_SHOW_INFO) {
9625                    Log.v(TAG, "    IntentFilter:");
9626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9627                }
9628                removeFilter(intent);
9629            }
9630        }
9631
9632        @Override
9633        protected boolean allowFilterResult(
9634                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9635            ProviderInfo filterPi = filter.provider.info;
9636            for (int i = dest.size() - 1; i >= 0; i--) {
9637                ProviderInfo destPi = dest.get(i).providerInfo;
9638                if (destPi.name == filterPi.name
9639                        && destPi.packageName == filterPi.packageName) {
9640                    return false;
9641                }
9642            }
9643            return true;
9644        }
9645
9646        @Override
9647        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9648            return new PackageParser.ProviderIntentInfo[size];
9649        }
9650
9651        @Override
9652        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9653            if (!sUserManager.exists(userId))
9654                return true;
9655            PackageParser.Package p = filter.provider.owner;
9656            if (p != null) {
9657                PackageSetting ps = (PackageSetting) p.mExtras;
9658                if (ps != null) {
9659                    // System apps are never considered stopped for purposes of
9660                    // filtering, because there may be no way for the user to
9661                    // actually re-launch them.
9662                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9663                            && ps.getStopped(userId);
9664                }
9665            }
9666            return false;
9667        }
9668
9669        @Override
9670        protected boolean isPackageForFilter(String packageName,
9671                PackageParser.ProviderIntentInfo info) {
9672            return packageName.equals(info.provider.owner.packageName);
9673        }
9674
9675        @Override
9676        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9677                int match, int userId) {
9678            if (!sUserManager.exists(userId))
9679                return null;
9680            final PackageParser.ProviderIntentInfo info = filter;
9681            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9682                return null;
9683            }
9684            final PackageParser.Provider provider = info.provider;
9685            if (mSafeMode && (provider.info.applicationInfo.flags
9686                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9687                return null;
9688            }
9689            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9690            if (ps == null) {
9691                return null;
9692            }
9693            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9694                    ps.readUserState(userId), userId);
9695            if (pi == null) {
9696                return null;
9697            }
9698            final ResolveInfo res = new ResolveInfo();
9699            res.providerInfo = pi;
9700            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9701                res.filter = filter;
9702            }
9703            res.priority = info.getPriority();
9704            res.preferredOrder = provider.owner.mPreferredOrder;
9705            res.match = match;
9706            res.isDefault = info.hasDefault;
9707            res.labelRes = info.labelRes;
9708            res.nonLocalizedLabel = info.nonLocalizedLabel;
9709            res.icon = info.icon;
9710            res.system = res.providerInfo.applicationInfo.isSystemApp();
9711            return res;
9712        }
9713
9714        @Override
9715        protected void sortResults(List<ResolveInfo> results) {
9716            Collections.sort(results, mResolvePrioritySorter);
9717        }
9718
9719        @Override
9720        protected void dumpFilter(PrintWriter out, String prefix,
9721                PackageParser.ProviderIntentInfo filter) {
9722            out.print(prefix);
9723            out.print(
9724                    Integer.toHexString(System.identityHashCode(filter.provider)));
9725            out.print(' ');
9726            filter.provider.printComponentShortName(out);
9727            out.print(" filter ");
9728            out.println(Integer.toHexString(System.identityHashCode(filter)));
9729        }
9730
9731        @Override
9732        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9733            return filter.provider;
9734        }
9735
9736        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9737            PackageParser.Provider provider = (PackageParser.Provider)label;
9738            out.print(prefix); out.print(
9739                    Integer.toHexString(System.identityHashCode(provider)));
9740                    out.print(' ');
9741                    provider.printComponentShortName(out);
9742            if (count > 1) {
9743                out.print(" ("); out.print(count); out.print(" filters)");
9744            }
9745            out.println();
9746        }
9747
9748        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9749                = new ArrayMap<ComponentName, PackageParser.Provider>();
9750        private int mFlags;
9751    }
9752
9753    private static final class EphemeralIntentResolver
9754            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9755        @Override
9756        protected EphemeralResolveIntentInfo[] newArray(int size) {
9757            return new EphemeralResolveIntentInfo[size];
9758        }
9759
9760        @Override
9761        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9762            return true;
9763        }
9764
9765        @Override
9766        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9767                int userId) {
9768            if (!sUserManager.exists(userId)) {
9769                return null;
9770            }
9771            return info.getEphemeralResolveInfo();
9772        }
9773    }
9774
9775    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9776            new Comparator<ResolveInfo>() {
9777        public int compare(ResolveInfo r1, ResolveInfo r2) {
9778            int v1 = r1.priority;
9779            int v2 = r2.priority;
9780            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9781            if (v1 != v2) {
9782                return (v1 > v2) ? -1 : 1;
9783            }
9784            v1 = r1.preferredOrder;
9785            v2 = r2.preferredOrder;
9786            if (v1 != v2) {
9787                return (v1 > v2) ? -1 : 1;
9788            }
9789            if (r1.isDefault != r2.isDefault) {
9790                return r1.isDefault ? -1 : 1;
9791            }
9792            v1 = r1.match;
9793            v2 = r2.match;
9794            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9795            if (v1 != v2) {
9796                return (v1 > v2) ? -1 : 1;
9797            }
9798            if (r1.system != r2.system) {
9799                return r1.system ? -1 : 1;
9800            }
9801            if (r1.activityInfo != null) {
9802                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9803            }
9804            if (r1.serviceInfo != null) {
9805                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9806            }
9807            if (r1.providerInfo != null) {
9808                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9809            }
9810            return 0;
9811        }
9812    };
9813
9814    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9815            new Comparator<ProviderInfo>() {
9816        public int compare(ProviderInfo p1, ProviderInfo p2) {
9817            final int v1 = p1.initOrder;
9818            final int v2 = p2.initOrder;
9819            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9820        }
9821    };
9822
9823    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9824            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9825            final int[] userIds) {
9826        mHandler.post(new Runnable() {
9827            @Override
9828            public void run() {
9829                try {
9830                    final IActivityManager am = ActivityManagerNative.getDefault();
9831                    if (am == null) return;
9832                    final int[] resolvedUserIds;
9833                    if (userIds == null) {
9834                        resolvedUserIds = am.getRunningUserIds();
9835                    } else {
9836                        resolvedUserIds = userIds;
9837                    }
9838                    for (int id : resolvedUserIds) {
9839                        final Intent intent = new Intent(action,
9840                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9841                        if (extras != null) {
9842                            intent.putExtras(extras);
9843                        }
9844                        if (targetPkg != null) {
9845                            intent.setPackage(targetPkg);
9846                        }
9847                        // Modify the UID when posting to other users
9848                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9849                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9850                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9851                            intent.putExtra(Intent.EXTRA_UID, uid);
9852                        }
9853                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9854                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9855                        if (DEBUG_BROADCASTS) {
9856                            RuntimeException here = new RuntimeException("here");
9857                            here.fillInStackTrace();
9858                            Slog.d(TAG, "Sending to user " + id + ": "
9859                                    + intent.toShortString(false, true, false, false)
9860                                    + " " + intent.getExtras(), here);
9861                        }
9862                        am.broadcastIntent(null, intent, null, finishedReceiver,
9863                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9864                                null, finishedReceiver != null, false, id);
9865                    }
9866                } catch (RemoteException ex) {
9867                }
9868            }
9869        });
9870    }
9871
9872    /**
9873     * Check if the external storage media is available. This is true if there
9874     * is a mounted external storage medium or if the external storage is
9875     * emulated.
9876     */
9877    private boolean isExternalMediaAvailable() {
9878        return mMediaMounted || Environment.isExternalStorageEmulated();
9879    }
9880
9881    @Override
9882    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9883        // writer
9884        synchronized (mPackages) {
9885            if (!isExternalMediaAvailable()) {
9886                // If the external storage is no longer mounted at this point,
9887                // the caller may not have been able to delete all of this
9888                // packages files and can not delete any more.  Bail.
9889                return null;
9890            }
9891            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9892            if (lastPackage != null) {
9893                pkgs.remove(lastPackage);
9894            }
9895            if (pkgs.size() > 0) {
9896                return pkgs.get(0);
9897            }
9898        }
9899        return null;
9900    }
9901
9902    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9903        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9904                userId, andCode ? 1 : 0, packageName);
9905        if (mSystemReady) {
9906            msg.sendToTarget();
9907        } else {
9908            if (mPostSystemReadyMessages == null) {
9909                mPostSystemReadyMessages = new ArrayList<>();
9910            }
9911            mPostSystemReadyMessages.add(msg);
9912        }
9913    }
9914
9915    void startCleaningPackages() {
9916        // reader
9917        synchronized (mPackages) {
9918            if (!isExternalMediaAvailable()) {
9919                return;
9920            }
9921            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9922                return;
9923            }
9924        }
9925        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9926        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9927        IActivityManager am = ActivityManagerNative.getDefault();
9928        if (am != null) {
9929            try {
9930                am.startService(null, intent, null, mContext.getOpPackageName(),
9931                        UserHandle.USER_SYSTEM);
9932            } catch (RemoteException e) {
9933            }
9934        }
9935    }
9936
9937    @Override
9938    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9939            int installFlags, String installerPackageName, VerificationParams verificationParams,
9940            String packageAbiOverride) {
9941        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9942                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9943    }
9944
9945    @Override
9946    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9947            int installFlags, String installerPackageName, VerificationParams verificationParams,
9948            String packageAbiOverride, int userId) {
9949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9950
9951        final int callingUid = Binder.getCallingUid();
9952        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9953
9954        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9955            try {
9956                if (observer != null) {
9957                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9958                }
9959            } catch (RemoteException re) {
9960            }
9961            return;
9962        }
9963
9964        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9965            installFlags |= PackageManager.INSTALL_FROM_ADB;
9966
9967        } else {
9968            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9969            // about installerPackageName.
9970
9971            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9972            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9973        }
9974
9975        UserHandle user;
9976        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9977            user = UserHandle.ALL;
9978        } else {
9979            user = new UserHandle(userId);
9980        }
9981
9982        // Only system components can circumvent runtime permissions when installing.
9983        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9984                && mContext.checkCallingOrSelfPermission(Manifest.permission
9985                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9986            throw new SecurityException("You need the "
9987                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9988                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9989        }
9990
9991        verificationParams.setInstallerUid(callingUid);
9992
9993        final File originFile = new File(originPath);
9994        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9995
9996        final Message msg = mHandler.obtainMessage(INIT_COPY);
9997        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9998                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9999        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10000        msg.obj = params;
10001
10002        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10003                System.identityHashCode(msg.obj));
10004        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10005                System.identityHashCode(msg.obj));
10006
10007        mHandler.sendMessage(msg);
10008    }
10009
10010    void installStage(String packageName, File stagedDir, String stagedCid,
10011            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10012            String installerPackageName, int installerUid, UserHandle user) {
10013        if (DEBUG_EPHEMERAL) {
10014            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10015                Slog.d(TAG, "Ephemeral install of " + packageName);
10016            }
10017        }
10018        final VerificationParams verifParams = new VerificationParams(
10019                null, sessionParams.originatingUri, sessionParams.referrerUri,
10020                sessionParams.originatingUid);
10021        verifParams.setInstallerUid(installerUid);
10022
10023        final OriginInfo origin;
10024        if (stagedDir != null) {
10025            origin = OriginInfo.fromStagedFile(stagedDir);
10026        } else {
10027            origin = OriginInfo.fromStagedContainer(stagedCid);
10028        }
10029
10030        final Message msg = mHandler.obtainMessage(INIT_COPY);
10031        final InstallParams params = new InstallParams(origin, null, observer,
10032                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10033                verifParams, user, sessionParams.abiOverride,
10034                sessionParams.grantedRuntimePermissions);
10035        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10036        msg.obj = params;
10037
10038        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10039                System.identityHashCode(msg.obj));
10040        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10041                System.identityHashCode(msg.obj));
10042
10043        mHandler.sendMessage(msg);
10044    }
10045
10046    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10047        Bundle extras = new Bundle(1);
10048        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10049
10050        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10051                packageName, extras, 0, null, null, new int[] {userId});
10052        try {
10053            IActivityManager am = ActivityManagerNative.getDefault();
10054            final boolean isSystem =
10055                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10056            if (isSystem && am.isUserRunning(userId, 0)) {
10057                // The just-installed/enabled app is bundled on the system, so presumed
10058                // to be able to run automatically without needing an explicit launch.
10059                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10060                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10061                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10062                        .setPackage(packageName);
10063                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10064                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10065            }
10066        } catch (RemoteException e) {
10067            // shouldn't happen
10068            Slog.w(TAG, "Unable to bootstrap installed package", e);
10069        }
10070    }
10071
10072    @Override
10073    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10074            int userId) {
10075        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10076        PackageSetting pkgSetting;
10077        final int uid = Binder.getCallingUid();
10078        enforceCrossUserPermission(uid, userId, true, true,
10079                "setApplicationHiddenSetting for user " + userId);
10080
10081        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10082            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10083            return false;
10084        }
10085
10086        long callingId = Binder.clearCallingIdentity();
10087        try {
10088            boolean sendAdded = false;
10089            boolean sendRemoved = false;
10090            // writer
10091            synchronized (mPackages) {
10092                pkgSetting = mSettings.mPackages.get(packageName);
10093                if (pkgSetting == null) {
10094                    return false;
10095                }
10096                if (pkgSetting.getHidden(userId) != hidden) {
10097                    pkgSetting.setHidden(hidden, userId);
10098                    mSettings.writePackageRestrictionsLPr(userId);
10099                    if (hidden) {
10100                        sendRemoved = true;
10101                    } else {
10102                        sendAdded = true;
10103                    }
10104                }
10105            }
10106            if (sendAdded) {
10107                sendPackageAddedForUser(packageName, pkgSetting, userId);
10108                return true;
10109            }
10110            if (sendRemoved) {
10111                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10112                        "hiding pkg");
10113                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10114                return true;
10115            }
10116        } finally {
10117            Binder.restoreCallingIdentity(callingId);
10118        }
10119        return false;
10120    }
10121
10122    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10123            int userId) {
10124        final PackageRemovedInfo info = new PackageRemovedInfo();
10125        info.removedPackage = packageName;
10126        info.removedUsers = new int[] {userId};
10127        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10128        info.sendBroadcast(false, false, false);
10129    }
10130
10131    /**
10132     * Returns true if application is not found or there was an error. Otherwise it returns
10133     * the hidden state of the package for the given user.
10134     */
10135    @Override
10136    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10137        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10138        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10139                false, "getApplicationHidden for user " + userId);
10140        PackageSetting pkgSetting;
10141        long callingId = Binder.clearCallingIdentity();
10142        try {
10143            // writer
10144            synchronized (mPackages) {
10145                pkgSetting = mSettings.mPackages.get(packageName);
10146                if (pkgSetting == null) {
10147                    return true;
10148                }
10149                return pkgSetting.getHidden(userId);
10150            }
10151        } finally {
10152            Binder.restoreCallingIdentity(callingId);
10153        }
10154    }
10155
10156    /**
10157     * @hide
10158     */
10159    @Override
10160    public int installExistingPackageAsUser(String packageName, int userId) {
10161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10162                null);
10163        PackageSetting pkgSetting;
10164        final int uid = Binder.getCallingUid();
10165        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10166                + userId);
10167        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10168            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10169        }
10170
10171        long callingId = Binder.clearCallingIdentity();
10172        try {
10173            boolean sendAdded = false;
10174
10175            // writer
10176            synchronized (mPackages) {
10177                pkgSetting = mSettings.mPackages.get(packageName);
10178                if (pkgSetting == null) {
10179                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10180                }
10181                if (!pkgSetting.getInstalled(userId)) {
10182                    pkgSetting.setInstalled(true, userId);
10183                    pkgSetting.setHidden(false, userId);
10184                    mSettings.writePackageRestrictionsLPr(userId);
10185                    sendAdded = true;
10186                }
10187            }
10188
10189            if (sendAdded) {
10190                sendPackageAddedForUser(packageName, pkgSetting, userId);
10191            }
10192        } finally {
10193            Binder.restoreCallingIdentity(callingId);
10194        }
10195
10196        return PackageManager.INSTALL_SUCCEEDED;
10197    }
10198
10199    boolean isUserRestricted(int userId, String restrictionKey) {
10200        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10201        if (restrictions.getBoolean(restrictionKey, false)) {
10202            Log.w(TAG, "User is restricted: " + restrictionKey);
10203            return true;
10204        }
10205        return false;
10206    }
10207
10208    @Override
10209    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10210        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10211        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10212                "setPackageSuspended for user " + userId);
10213
10214        long callingId = Binder.clearCallingIdentity();
10215        try {
10216            synchronized (mPackages) {
10217                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10218                if (pkgSetting != null) {
10219                    if (pkgSetting.getSuspended(userId) != suspended) {
10220                        pkgSetting.setSuspended(suspended, userId);
10221                        mSettings.writePackageRestrictionsLPr(userId);
10222                    }
10223
10224                    // TODO:
10225                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10226                    // * remove app from recents (kill app it if it is running)
10227                    // * erase existing notifications for this app
10228                    return true;
10229                }
10230
10231                return false;
10232            }
10233        } finally {
10234            Binder.restoreCallingIdentity(callingId);
10235        }
10236    }
10237
10238    @Override
10239    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10240        mContext.enforceCallingOrSelfPermission(
10241                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10242                "Only package verification agents can verify applications");
10243
10244        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10245        final PackageVerificationResponse response = new PackageVerificationResponse(
10246                verificationCode, Binder.getCallingUid());
10247        msg.arg1 = id;
10248        msg.obj = response;
10249        mHandler.sendMessage(msg);
10250    }
10251
10252    @Override
10253    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10254            long millisecondsToDelay) {
10255        mContext.enforceCallingOrSelfPermission(
10256                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10257                "Only package verification agents can extend verification timeouts");
10258
10259        final PackageVerificationState state = mPendingVerification.get(id);
10260        final PackageVerificationResponse response = new PackageVerificationResponse(
10261                verificationCodeAtTimeout, Binder.getCallingUid());
10262
10263        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10264            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10265        }
10266        if (millisecondsToDelay < 0) {
10267            millisecondsToDelay = 0;
10268        }
10269        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10270                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10271            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10272        }
10273
10274        if ((state != null) && !state.timeoutExtended()) {
10275            state.extendTimeout();
10276
10277            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10278            msg.arg1 = id;
10279            msg.obj = response;
10280            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10281        }
10282    }
10283
10284    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10285            int verificationCode, UserHandle user) {
10286        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10287        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10288        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10289        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10290        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10291
10292        mContext.sendBroadcastAsUser(intent, user,
10293                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10294    }
10295
10296    private ComponentName matchComponentForVerifier(String packageName,
10297            List<ResolveInfo> receivers) {
10298        ActivityInfo targetReceiver = null;
10299
10300        final int NR = receivers.size();
10301        for (int i = 0; i < NR; i++) {
10302            final ResolveInfo info = receivers.get(i);
10303            if (info.activityInfo == null) {
10304                continue;
10305            }
10306
10307            if (packageName.equals(info.activityInfo.packageName)) {
10308                targetReceiver = info.activityInfo;
10309                break;
10310            }
10311        }
10312
10313        if (targetReceiver == null) {
10314            return null;
10315        }
10316
10317        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10318    }
10319
10320    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10321            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10322        if (pkgInfo.verifiers.length == 0) {
10323            return null;
10324        }
10325
10326        final int N = pkgInfo.verifiers.length;
10327        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10328        for (int i = 0; i < N; i++) {
10329            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10330
10331            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10332                    receivers);
10333            if (comp == null) {
10334                continue;
10335            }
10336
10337            final int verifierUid = getUidForVerifier(verifierInfo);
10338            if (verifierUid == -1) {
10339                continue;
10340            }
10341
10342            if (DEBUG_VERIFY) {
10343                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10344                        + " with the correct signature");
10345            }
10346            sufficientVerifiers.add(comp);
10347            verificationState.addSufficientVerifier(verifierUid);
10348        }
10349
10350        return sufficientVerifiers;
10351    }
10352
10353    private int getUidForVerifier(VerifierInfo verifierInfo) {
10354        synchronized (mPackages) {
10355            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10356            if (pkg == null) {
10357                return -1;
10358            } else if (pkg.mSignatures.length != 1) {
10359                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10360                        + " has more than one signature; ignoring");
10361                return -1;
10362            }
10363
10364            /*
10365             * If the public key of the package's signature does not match
10366             * our expected public key, then this is a different package and
10367             * we should skip.
10368             */
10369
10370            final byte[] expectedPublicKey;
10371            try {
10372                final Signature verifierSig = pkg.mSignatures[0];
10373                final PublicKey publicKey = verifierSig.getPublicKey();
10374                expectedPublicKey = publicKey.getEncoded();
10375            } catch (CertificateException e) {
10376                return -1;
10377            }
10378
10379            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10380
10381            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10382                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10383                        + " does not have the expected public key; ignoring");
10384                return -1;
10385            }
10386
10387            return pkg.applicationInfo.uid;
10388        }
10389    }
10390
10391    @Override
10392    public void finishPackageInstall(int token) {
10393        enforceSystemOrRoot("Only the system is allowed to finish installs");
10394
10395        if (DEBUG_INSTALL) {
10396            Slog.v(TAG, "BM finishing package install for " + token);
10397        }
10398        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10399
10400        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10401        mHandler.sendMessage(msg);
10402    }
10403
10404    /**
10405     * Get the verification agent timeout.
10406     *
10407     * @return verification timeout in milliseconds
10408     */
10409    private long getVerificationTimeout() {
10410        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10411                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10412                DEFAULT_VERIFICATION_TIMEOUT);
10413    }
10414
10415    /**
10416     * Get the default verification agent response code.
10417     *
10418     * @return default verification response code
10419     */
10420    private int getDefaultVerificationResponse() {
10421        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10422                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10423                DEFAULT_VERIFICATION_RESPONSE);
10424    }
10425
10426    /**
10427     * Check whether or not package verification has been enabled.
10428     *
10429     * @return true if verification should be performed
10430     */
10431    private boolean isVerificationEnabled(int userId, int installFlags) {
10432        if (!DEFAULT_VERIFY_ENABLE) {
10433            return false;
10434        }
10435        // Ephemeral apps don't get the full verification treatment
10436        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10437            if (DEBUG_EPHEMERAL) {
10438                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10439            }
10440            return false;
10441        }
10442
10443        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10444
10445        // Check if installing from ADB
10446        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10447            // Do not run verification in a test harness environment
10448            if (ActivityManager.isRunningInTestHarness()) {
10449                return false;
10450            }
10451            if (ensureVerifyAppsEnabled) {
10452                return true;
10453            }
10454            // Check if the developer does not want package verification for ADB installs
10455            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10456                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10457                return false;
10458            }
10459        }
10460
10461        if (ensureVerifyAppsEnabled) {
10462            return true;
10463        }
10464
10465        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10466                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10467    }
10468
10469    @Override
10470    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10471            throws RemoteException {
10472        mContext.enforceCallingOrSelfPermission(
10473                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10474                "Only intentfilter verification agents can verify applications");
10475
10476        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10477        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10478                Binder.getCallingUid(), verificationCode, failedDomains);
10479        msg.arg1 = id;
10480        msg.obj = response;
10481        mHandler.sendMessage(msg);
10482    }
10483
10484    @Override
10485    public int getIntentVerificationStatus(String packageName, int userId) {
10486        synchronized (mPackages) {
10487            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10488        }
10489    }
10490
10491    @Override
10492    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10493        mContext.enforceCallingOrSelfPermission(
10494                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10495
10496        boolean result = false;
10497        synchronized (mPackages) {
10498            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10499        }
10500        if (result) {
10501            scheduleWritePackageRestrictionsLocked(userId);
10502        }
10503        return result;
10504    }
10505
10506    @Override
10507    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10508        synchronized (mPackages) {
10509            return mSettings.getIntentFilterVerificationsLPr(packageName);
10510        }
10511    }
10512
10513    @Override
10514    public List<IntentFilter> getAllIntentFilters(String packageName) {
10515        if (TextUtils.isEmpty(packageName)) {
10516            return Collections.<IntentFilter>emptyList();
10517        }
10518        synchronized (mPackages) {
10519            PackageParser.Package pkg = mPackages.get(packageName);
10520            if (pkg == null || pkg.activities == null) {
10521                return Collections.<IntentFilter>emptyList();
10522            }
10523            final int count = pkg.activities.size();
10524            ArrayList<IntentFilter> result = new ArrayList<>();
10525            for (int n=0; n<count; n++) {
10526                PackageParser.Activity activity = pkg.activities.get(n);
10527                if (activity.intents != null && activity.intents.size() > 0) {
10528                    result.addAll(activity.intents);
10529                }
10530            }
10531            return result;
10532        }
10533    }
10534
10535    @Override
10536    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10537        mContext.enforceCallingOrSelfPermission(
10538                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10539
10540        synchronized (mPackages) {
10541            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10542            if (packageName != null) {
10543                result |= updateIntentVerificationStatus(packageName,
10544                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10545                        userId);
10546                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10547                        packageName, userId);
10548            }
10549            return result;
10550        }
10551    }
10552
10553    @Override
10554    public String getDefaultBrowserPackageName(int userId) {
10555        synchronized (mPackages) {
10556            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10557        }
10558    }
10559
10560    /**
10561     * Get the "allow unknown sources" setting.
10562     *
10563     * @return the current "allow unknown sources" setting
10564     */
10565    private int getUnknownSourcesSettings() {
10566        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10567                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10568                -1);
10569    }
10570
10571    @Override
10572    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10573        final int uid = Binder.getCallingUid();
10574        // writer
10575        synchronized (mPackages) {
10576            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10577            if (targetPackageSetting == null) {
10578                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10579            }
10580
10581            PackageSetting installerPackageSetting;
10582            if (installerPackageName != null) {
10583                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10584                if (installerPackageSetting == null) {
10585                    throw new IllegalArgumentException("Unknown installer package: "
10586                            + installerPackageName);
10587                }
10588            } else {
10589                installerPackageSetting = null;
10590            }
10591
10592            Signature[] callerSignature;
10593            Object obj = mSettings.getUserIdLPr(uid);
10594            if (obj != null) {
10595                if (obj instanceof SharedUserSetting) {
10596                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10597                } else if (obj instanceof PackageSetting) {
10598                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10599                } else {
10600                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10601                }
10602            } else {
10603                throw new SecurityException("Unknown calling UID: " + uid);
10604            }
10605
10606            // Verify: can't set installerPackageName to a package that is
10607            // not signed with the same cert as the caller.
10608            if (installerPackageSetting != null) {
10609                if (compareSignatures(callerSignature,
10610                        installerPackageSetting.signatures.mSignatures)
10611                        != PackageManager.SIGNATURE_MATCH) {
10612                    throw new SecurityException(
10613                            "Caller does not have same cert as new installer package "
10614                            + installerPackageName);
10615                }
10616            }
10617
10618            // Verify: if target already has an installer package, it must
10619            // be signed with the same cert as the caller.
10620            if (targetPackageSetting.installerPackageName != null) {
10621                PackageSetting setting = mSettings.mPackages.get(
10622                        targetPackageSetting.installerPackageName);
10623                // If the currently set package isn't valid, then it's always
10624                // okay to change it.
10625                if (setting != null) {
10626                    if (compareSignatures(callerSignature,
10627                            setting.signatures.mSignatures)
10628                            != PackageManager.SIGNATURE_MATCH) {
10629                        throw new SecurityException(
10630                                "Caller does not have same cert as old installer package "
10631                                + targetPackageSetting.installerPackageName);
10632                    }
10633                }
10634            }
10635
10636            // Okay!
10637            targetPackageSetting.installerPackageName = installerPackageName;
10638            scheduleWriteSettingsLocked();
10639        }
10640    }
10641
10642    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10643        // Queue up an async operation since the package installation may take a little while.
10644        mHandler.post(new Runnable() {
10645            public void run() {
10646                mHandler.removeCallbacks(this);
10647                 // Result object to be returned
10648                PackageInstalledInfo res = new PackageInstalledInfo();
10649                res.returnCode = currentStatus;
10650                res.uid = -1;
10651                res.pkg = null;
10652                res.removedInfo = new PackageRemovedInfo();
10653                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10654                    args.doPreInstall(res.returnCode);
10655                    synchronized (mInstallLock) {
10656                        installPackageTracedLI(args, res);
10657                    }
10658                    args.doPostInstall(res.returnCode, res.uid);
10659                }
10660
10661                // A restore should be performed at this point if (a) the install
10662                // succeeded, (b) the operation is not an update, and (c) the new
10663                // package has not opted out of backup participation.
10664                final boolean update = res.removedInfo.removedPackage != null;
10665                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10666                boolean doRestore = !update
10667                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10668
10669                // Set up the post-install work request bookkeeping.  This will be used
10670                // and cleaned up by the post-install event handling regardless of whether
10671                // there's a restore pass performed.  Token values are >= 1.
10672                int token;
10673                if (mNextInstallToken < 0) mNextInstallToken = 1;
10674                token = mNextInstallToken++;
10675
10676                PostInstallData data = new PostInstallData(args, res);
10677                mRunningInstalls.put(token, data);
10678                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10679
10680                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10681                    // Pass responsibility to the Backup Manager.  It will perform a
10682                    // restore if appropriate, then pass responsibility back to the
10683                    // Package Manager to run the post-install observer callbacks
10684                    // and broadcasts.
10685                    IBackupManager bm = IBackupManager.Stub.asInterface(
10686                            ServiceManager.getService(Context.BACKUP_SERVICE));
10687                    if (bm != null) {
10688                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10689                                + " to BM for possible restore");
10690                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10691                        try {
10692                            // TODO: http://b/22388012
10693                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10694                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10695                            } else {
10696                                doRestore = false;
10697                            }
10698                        } catch (RemoteException e) {
10699                            // can't happen; the backup manager is local
10700                        } catch (Exception e) {
10701                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10702                            doRestore = false;
10703                        }
10704                    } else {
10705                        Slog.e(TAG, "Backup Manager not found!");
10706                        doRestore = false;
10707                    }
10708                }
10709
10710                if (!doRestore) {
10711                    // No restore possible, or the Backup Manager was mysteriously not
10712                    // available -- just fire the post-install work request directly.
10713                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10714
10715                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10716
10717                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10718                    mHandler.sendMessage(msg);
10719                }
10720            }
10721        });
10722    }
10723
10724    private abstract class HandlerParams {
10725        private static final int MAX_RETRIES = 4;
10726
10727        /**
10728         * Number of times startCopy() has been attempted and had a non-fatal
10729         * error.
10730         */
10731        private int mRetries = 0;
10732
10733        /** User handle for the user requesting the information or installation. */
10734        private final UserHandle mUser;
10735        String traceMethod;
10736        int traceCookie;
10737
10738        HandlerParams(UserHandle user) {
10739            mUser = user;
10740        }
10741
10742        UserHandle getUser() {
10743            return mUser;
10744        }
10745
10746        HandlerParams setTraceMethod(String traceMethod) {
10747            this.traceMethod = traceMethod;
10748            return this;
10749        }
10750
10751        HandlerParams setTraceCookie(int traceCookie) {
10752            this.traceCookie = traceCookie;
10753            return this;
10754        }
10755
10756        final boolean startCopy() {
10757            boolean res;
10758            try {
10759                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10760
10761                if (++mRetries > MAX_RETRIES) {
10762                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10763                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10764                    handleServiceError();
10765                    return false;
10766                } else {
10767                    handleStartCopy();
10768                    res = true;
10769                }
10770            } catch (RemoteException e) {
10771                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10772                mHandler.sendEmptyMessage(MCS_RECONNECT);
10773                res = false;
10774            }
10775            handleReturnCode();
10776            return res;
10777        }
10778
10779        final void serviceError() {
10780            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10781            handleServiceError();
10782            handleReturnCode();
10783        }
10784
10785        abstract void handleStartCopy() throws RemoteException;
10786        abstract void handleServiceError();
10787        abstract void handleReturnCode();
10788    }
10789
10790    class MeasureParams extends HandlerParams {
10791        private final PackageStats mStats;
10792        private boolean mSuccess;
10793
10794        private final IPackageStatsObserver mObserver;
10795
10796        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10797            super(new UserHandle(stats.userHandle));
10798            mObserver = observer;
10799            mStats = stats;
10800        }
10801
10802        @Override
10803        public String toString() {
10804            return "MeasureParams{"
10805                + Integer.toHexString(System.identityHashCode(this))
10806                + " " + mStats.packageName + "}";
10807        }
10808
10809        @Override
10810        void handleStartCopy() throws RemoteException {
10811            synchronized (mInstallLock) {
10812                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10813            }
10814
10815            if (mSuccess) {
10816                final boolean mounted;
10817                if (Environment.isExternalStorageEmulated()) {
10818                    mounted = true;
10819                } else {
10820                    final String status = Environment.getExternalStorageState();
10821                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10822                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10823                }
10824
10825                if (mounted) {
10826                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10827
10828                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10829                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10830
10831                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10832                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10833
10834                    // Always subtract cache size, since it's a subdirectory
10835                    mStats.externalDataSize -= mStats.externalCacheSize;
10836
10837                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10838                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10839
10840                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10841                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10842                }
10843            }
10844        }
10845
10846        @Override
10847        void handleReturnCode() {
10848            if (mObserver != null) {
10849                try {
10850                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10851                } catch (RemoteException e) {
10852                    Slog.i(TAG, "Observer no longer exists.");
10853                }
10854            }
10855        }
10856
10857        @Override
10858        void handleServiceError() {
10859            Slog.e(TAG, "Could not measure application " + mStats.packageName
10860                            + " external storage");
10861        }
10862    }
10863
10864    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10865            throws RemoteException {
10866        long result = 0;
10867        for (File path : paths) {
10868            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10869        }
10870        return result;
10871    }
10872
10873    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10874        for (File path : paths) {
10875            try {
10876                mcs.clearDirectory(path.getAbsolutePath());
10877            } catch (RemoteException e) {
10878            }
10879        }
10880    }
10881
10882    static class OriginInfo {
10883        /**
10884         * Location where install is coming from, before it has been
10885         * copied/renamed into place. This could be a single monolithic APK
10886         * file, or a cluster directory. This location may be untrusted.
10887         */
10888        final File file;
10889        final String cid;
10890
10891        /**
10892         * Flag indicating that {@link #file} or {@link #cid} has already been
10893         * staged, meaning downstream users don't need to defensively copy the
10894         * contents.
10895         */
10896        final boolean staged;
10897
10898        /**
10899         * Flag indicating that {@link #file} or {@link #cid} is an already
10900         * installed app that is being moved.
10901         */
10902        final boolean existing;
10903
10904        final String resolvedPath;
10905        final File resolvedFile;
10906
10907        static OriginInfo fromNothing() {
10908            return new OriginInfo(null, null, false, false);
10909        }
10910
10911        static OriginInfo fromUntrustedFile(File file) {
10912            return new OriginInfo(file, null, false, false);
10913        }
10914
10915        static OriginInfo fromExistingFile(File file) {
10916            return new OriginInfo(file, null, false, true);
10917        }
10918
10919        static OriginInfo fromStagedFile(File file) {
10920            return new OriginInfo(file, null, true, false);
10921        }
10922
10923        static OriginInfo fromStagedContainer(String cid) {
10924            return new OriginInfo(null, cid, true, false);
10925        }
10926
10927        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10928            this.file = file;
10929            this.cid = cid;
10930            this.staged = staged;
10931            this.existing = existing;
10932
10933            if (cid != null) {
10934                resolvedPath = PackageHelper.getSdDir(cid);
10935                resolvedFile = new File(resolvedPath);
10936            } else if (file != null) {
10937                resolvedPath = file.getAbsolutePath();
10938                resolvedFile = file;
10939            } else {
10940                resolvedPath = null;
10941                resolvedFile = null;
10942            }
10943        }
10944    }
10945
10946    static class MoveInfo {
10947        final int moveId;
10948        final String fromUuid;
10949        final String toUuid;
10950        final String packageName;
10951        final String dataAppName;
10952        final int appId;
10953        final String seinfo;
10954
10955        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10956                String dataAppName, int appId, String seinfo) {
10957            this.moveId = moveId;
10958            this.fromUuid = fromUuid;
10959            this.toUuid = toUuid;
10960            this.packageName = packageName;
10961            this.dataAppName = dataAppName;
10962            this.appId = appId;
10963            this.seinfo = seinfo;
10964        }
10965    }
10966
10967    class InstallParams extends HandlerParams {
10968        final OriginInfo origin;
10969        final MoveInfo move;
10970        final IPackageInstallObserver2 observer;
10971        int installFlags;
10972        final String installerPackageName;
10973        final String volumeUuid;
10974        final VerificationParams verificationParams;
10975        private InstallArgs mArgs;
10976        private int mRet;
10977        final String packageAbiOverride;
10978        final String[] grantedRuntimePermissions;
10979
10980        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10981                int installFlags, String installerPackageName, String volumeUuid,
10982                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10983                String[] grantedPermissions) {
10984            super(user);
10985            this.origin = origin;
10986            this.move = move;
10987            this.observer = observer;
10988            this.installFlags = installFlags;
10989            this.installerPackageName = installerPackageName;
10990            this.volumeUuid = volumeUuid;
10991            this.verificationParams = verificationParams;
10992            this.packageAbiOverride = packageAbiOverride;
10993            this.grantedRuntimePermissions = grantedPermissions;
10994        }
10995
10996        @Override
10997        public String toString() {
10998            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10999                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11000        }
11001
11002        private int installLocationPolicy(PackageInfoLite pkgLite) {
11003            String packageName = pkgLite.packageName;
11004            int installLocation = pkgLite.installLocation;
11005            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11006            // reader
11007            synchronized (mPackages) {
11008                PackageParser.Package pkg = mPackages.get(packageName);
11009                if (pkg != null) {
11010                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11011                        // Check for downgrading.
11012                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11013                            try {
11014                                checkDowngrade(pkg, pkgLite);
11015                            } catch (PackageManagerException e) {
11016                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11017                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11018                            }
11019                        }
11020                        // Check for updated system application.
11021                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11022                            if (onSd) {
11023                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11024                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11025                            }
11026                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11027                        } else {
11028                            if (onSd) {
11029                                // Install flag overrides everything.
11030                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11031                            }
11032                            // If current upgrade specifies particular preference
11033                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11034                                // Application explicitly specified internal.
11035                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11036                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11037                                // App explictly prefers external. Let policy decide
11038                            } else {
11039                                // Prefer previous location
11040                                if (isExternal(pkg)) {
11041                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11042                                }
11043                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11044                            }
11045                        }
11046                    } else {
11047                        // Invalid install. Return error code
11048                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11049                    }
11050                }
11051            }
11052            // All the special cases have been taken care of.
11053            // Return result based on recommended install location.
11054            if (onSd) {
11055                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11056            }
11057            return pkgLite.recommendedInstallLocation;
11058        }
11059
11060        /*
11061         * Invoke remote method to get package information and install
11062         * location values. Override install location based on default
11063         * policy if needed and then create install arguments based
11064         * on the install location.
11065         */
11066        public void handleStartCopy() throws RemoteException {
11067            int ret = PackageManager.INSTALL_SUCCEEDED;
11068
11069            // If we're already staged, we've firmly committed to an install location
11070            if (origin.staged) {
11071                if (origin.file != null) {
11072                    installFlags |= PackageManager.INSTALL_INTERNAL;
11073                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11074                } else if (origin.cid != null) {
11075                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11076                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11077                } else {
11078                    throw new IllegalStateException("Invalid stage location");
11079                }
11080            }
11081
11082            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11083            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11084            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11085            PackageInfoLite pkgLite = null;
11086
11087            if (onInt && onSd) {
11088                // Check if both bits are set.
11089                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11090                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11091            } else if (onSd && ephemeral) {
11092                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11093                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11094            } else {
11095                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11096                        packageAbiOverride);
11097
11098                if (DEBUG_EPHEMERAL && ephemeral) {
11099                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11100                }
11101
11102                /*
11103                 * If we have too little free space, try to free cache
11104                 * before giving up.
11105                 */
11106                if (!origin.staged && pkgLite.recommendedInstallLocation
11107                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11108                    // TODO: focus freeing disk space on the target device
11109                    final StorageManager storage = StorageManager.from(mContext);
11110                    final long lowThreshold = storage.getStorageLowBytes(
11111                            Environment.getDataDirectory());
11112
11113                    final long sizeBytes = mContainerService.calculateInstalledSize(
11114                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11115
11116                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11117                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11118                                installFlags, packageAbiOverride);
11119                    }
11120
11121                    /*
11122                     * The cache free must have deleted the file we
11123                     * downloaded to install.
11124                     *
11125                     * TODO: fix the "freeCache" call to not delete
11126                     *       the file we care about.
11127                     */
11128                    if (pkgLite.recommendedInstallLocation
11129                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11130                        pkgLite.recommendedInstallLocation
11131                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11132                    }
11133                }
11134            }
11135
11136            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11137                int loc = pkgLite.recommendedInstallLocation;
11138                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11139                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11140                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11141                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11142                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11143                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11144                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11145                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11146                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11147                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11148                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11149                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11150                } else {
11151                    // Override with defaults if needed.
11152                    loc = installLocationPolicy(pkgLite);
11153                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11154                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11155                    } else if (!onSd && !onInt) {
11156                        // Override install location with flags
11157                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11158                            // Set the flag to install on external media.
11159                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11160                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11161                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11162                            if (DEBUG_EPHEMERAL) {
11163                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11164                            }
11165                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11166                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11167                                    |PackageManager.INSTALL_INTERNAL);
11168                        } else {
11169                            // Make sure the flag for installing on external
11170                            // media is unset
11171                            installFlags |= PackageManager.INSTALL_INTERNAL;
11172                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11173                        }
11174                    }
11175                }
11176            }
11177
11178            final InstallArgs args = createInstallArgs(this);
11179            mArgs = args;
11180
11181            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11182                // TODO: http://b/22976637
11183                // Apps installed for "all" users use the device owner to verify the app
11184                UserHandle verifierUser = getUser();
11185                if (verifierUser == UserHandle.ALL) {
11186                    verifierUser = UserHandle.SYSTEM;
11187                }
11188
11189                /*
11190                 * Determine if we have any installed package verifiers. If we
11191                 * do, then we'll defer to them to verify the packages.
11192                 */
11193                final int requiredUid = mRequiredVerifierPackage == null ? -1
11194                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11195                if (!origin.existing && requiredUid != -1
11196                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11197                    final Intent verification = new Intent(
11198                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11199                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11200                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11201                            PACKAGE_MIME_TYPE);
11202                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11203
11204                    // Query all live verifiers based on current user state
11205                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11206                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11207
11208                    if (DEBUG_VERIFY) {
11209                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11210                                + verification.toString() + " with " + pkgLite.verifiers.length
11211                                + " optional verifiers");
11212                    }
11213
11214                    final int verificationId = mPendingVerificationToken++;
11215
11216                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11217
11218                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11219                            installerPackageName);
11220
11221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11222                            installFlags);
11223
11224                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11225                            pkgLite.packageName);
11226
11227                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11228                            pkgLite.versionCode);
11229
11230                    if (verificationParams != null) {
11231                        if (verificationParams.getVerificationURI() != null) {
11232                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11233                                 verificationParams.getVerificationURI());
11234                        }
11235                        if (verificationParams.getOriginatingURI() != null) {
11236                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11237                                  verificationParams.getOriginatingURI());
11238                        }
11239                        if (verificationParams.getReferrer() != null) {
11240                            verification.putExtra(Intent.EXTRA_REFERRER,
11241                                  verificationParams.getReferrer());
11242                        }
11243                        if (verificationParams.getOriginatingUid() >= 0) {
11244                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11245                                  verificationParams.getOriginatingUid());
11246                        }
11247                        if (verificationParams.getInstallerUid() >= 0) {
11248                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11249                                  verificationParams.getInstallerUid());
11250                        }
11251                    }
11252
11253                    final PackageVerificationState verificationState = new PackageVerificationState(
11254                            requiredUid, args);
11255
11256                    mPendingVerification.append(verificationId, verificationState);
11257
11258                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11259                            receivers, verificationState);
11260
11261                    /*
11262                     * If any sufficient verifiers were listed in the package
11263                     * manifest, attempt to ask them.
11264                     */
11265                    if (sufficientVerifiers != null) {
11266                        final int N = sufficientVerifiers.size();
11267                        if (N == 0) {
11268                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11269                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11270                        } else {
11271                            for (int i = 0; i < N; i++) {
11272                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11273
11274                                final Intent sufficientIntent = new Intent(verification);
11275                                sufficientIntent.setComponent(verifierComponent);
11276                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11277                            }
11278                        }
11279                    }
11280
11281                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11282                            mRequiredVerifierPackage, receivers);
11283                    if (ret == PackageManager.INSTALL_SUCCEEDED
11284                            && mRequiredVerifierPackage != null) {
11285                        Trace.asyncTraceBegin(
11286                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11287                        /*
11288                         * Send the intent to the required verification agent,
11289                         * but only start the verification timeout after the
11290                         * target BroadcastReceivers have run.
11291                         */
11292                        verification.setComponent(requiredVerifierComponent);
11293                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11294                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11295                                new BroadcastReceiver() {
11296                                    @Override
11297                                    public void onReceive(Context context, Intent intent) {
11298                                        final Message msg = mHandler
11299                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11300                                        msg.arg1 = verificationId;
11301                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11302                                    }
11303                                }, null, 0, null, null);
11304
11305                        /*
11306                         * We don't want the copy to proceed until verification
11307                         * succeeds, so null out this field.
11308                         */
11309                        mArgs = null;
11310                    }
11311                } else {
11312                    /*
11313                     * No package verification is enabled, so immediately start
11314                     * the remote call to initiate copy using temporary file.
11315                     */
11316                    ret = args.copyApk(mContainerService, true);
11317                }
11318            }
11319
11320            mRet = ret;
11321        }
11322
11323        @Override
11324        void handleReturnCode() {
11325            // If mArgs is null, then MCS couldn't be reached. When it
11326            // reconnects, it will try again to install. At that point, this
11327            // will succeed.
11328            if (mArgs != null) {
11329                processPendingInstall(mArgs, mRet);
11330            }
11331        }
11332
11333        @Override
11334        void handleServiceError() {
11335            mArgs = createInstallArgs(this);
11336            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11337        }
11338
11339        public boolean isForwardLocked() {
11340            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11341        }
11342    }
11343
11344    /**
11345     * Used during creation of InstallArgs
11346     *
11347     * @param installFlags package installation flags
11348     * @return true if should be installed on external storage
11349     */
11350    private static boolean installOnExternalAsec(int installFlags) {
11351        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11352            return false;
11353        }
11354        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11355            return true;
11356        }
11357        return false;
11358    }
11359
11360    /**
11361     * Used during creation of InstallArgs
11362     *
11363     * @param installFlags package installation flags
11364     * @return true if should be installed as forward locked
11365     */
11366    private static boolean installForwardLocked(int installFlags) {
11367        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11368    }
11369
11370    private InstallArgs createInstallArgs(InstallParams params) {
11371        if (params.move != null) {
11372            return new MoveInstallArgs(params);
11373        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11374            return new AsecInstallArgs(params);
11375        } else {
11376            return new FileInstallArgs(params);
11377        }
11378    }
11379
11380    /**
11381     * Create args that describe an existing installed package. Typically used
11382     * when cleaning up old installs, or used as a move source.
11383     */
11384    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11385            String resourcePath, String[] instructionSets) {
11386        final boolean isInAsec;
11387        if (installOnExternalAsec(installFlags)) {
11388            /* Apps on SD card are always in ASEC containers. */
11389            isInAsec = true;
11390        } else if (installForwardLocked(installFlags)
11391                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11392            /*
11393             * Forward-locked apps are only in ASEC containers if they're the
11394             * new style
11395             */
11396            isInAsec = true;
11397        } else {
11398            isInAsec = false;
11399        }
11400
11401        if (isInAsec) {
11402            return new AsecInstallArgs(codePath, instructionSets,
11403                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11404        } else {
11405            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11406        }
11407    }
11408
11409    static abstract class InstallArgs {
11410        /** @see InstallParams#origin */
11411        final OriginInfo origin;
11412        /** @see InstallParams#move */
11413        final MoveInfo move;
11414
11415        final IPackageInstallObserver2 observer;
11416        // Always refers to PackageManager flags only
11417        final int installFlags;
11418        final String installerPackageName;
11419        final String volumeUuid;
11420        final UserHandle user;
11421        final String abiOverride;
11422        final String[] installGrantPermissions;
11423        /** If non-null, drop an async trace when the install completes */
11424        final String traceMethod;
11425        final int traceCookie;
11426
11427        // The list of instruction sets supported by this app. This is currently
11428        // only used during the rmdex() phase to clean up resources. We can get rid of this
11429        // if we move dex files under the common app path.
11430        /* nullable */ String[] instructionSets;
11431
11432        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11433                int installFlags, String installerPackageName, String volumeUuid,
11434                UserHandle user, String[] instructionSets,
11435                String abiOverride, String[] installGrantPermissions,
11436                String traceMethod, int traceCookie) {
11437            this.origin = origin;
11438            this.move = move;
11439            this.installFlags = installFlags;
11440            this.observer = observer;
11441            this.installerPackageName = installerPackageName;
11442            this.volumeUuid = volumeUuid;
11443            this.user = user;
11444            this.instructionSets = instructionSets;
11445            this.abiOverride = abiOverride;
11446            this.installGrantPermissions = installGrantPermissions;
11447            this.traceMethod = traceMethod;
11448            this.traceCookie = traceCookie;
11449        }
11450
11451        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11452        abstract int doPreInstall(int status);
11453
11454        /**
11455         * Rename package into final resting place. All paths on the given
11456         * scanned package should be updated to reflect the rename.
11457         */
11458        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11459        abstract int doPostInstall(int status, int uid);
11460
11461        /** @see PackageSettingBase#codePathString */
11462        abstract String getCodePath();
11463        /** @see PackageSettingBase#resourcePathString */
11464        abstract String getResourcePath();
11465
11466        // Need installer lock especially for dex file removal.
11467        abstract void cleanUpResourcesLI();
11468        abstract boolean doPostDeleteLI(boolean delete);
11469
11470        /**
11471         * Called before the source arguments are copied. This is used mostly
11472         * for MoveParams when it needs to read the source file to put it in the
11473         * destination.
11474         */
11475        int doPreCopy() {
11476            return PackageManager.INSTALL_SUCCEEDED;
11477        }
11478
11479        /**
11480         * Called after the source arguments are copied. This is used mostly for
11481         * MoveParams when it needs to read the source file to put it in the
11482         * destination.
11483         *
11484         * @return
11485         */
11486        int doPostCopy(int uid) {
11487            return PackageManager.INSTALL_SUCCEEDED;
11488        }
11489
11490        protected boolean isFwdLocked() {
11491            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11492        }
11493
11494        protected boolean isExternalAsec() {
11495            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11496        }
11497
11498        protected boolean isEphemeral() {
11499            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11500        }
11501
11502        UserHandle getUser() {
11503            return user;
11504        }
11505    }
11506
11507    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11508        if (!allCodePaths.isEmpty()) {
11509            if (instructionSets == null) {
11510                throw new IllegalStateException("instructionSet == null");
11511            }
11512            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11513            for (String codePath : allCodePaths) {
11514                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11515                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11516                    if (retCode < 0) {
11517                        Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath
11518                                + ", retcode=" + retCode);
11519                        // we don't consider this to be a failure of the core package deletion
11520                    }
11521                }
11522            }
11523        }
11524    }
11525
11526    /**
11527     * Logic to handle installation of non-ASEC applications, including copying
11528     * and renaming logic.
11529     */
11530    class FileInstallArgs extends InstallArgs {
11531        private File codeFile;
11532        private File resourceFile;
11533
11534        // Example topology:
11535        // /data/app/com.example/base.apk
11536        // /data/app/com.example/split_foo.apk
11537        // /data/app/com.example/lib/arm/libfoo.so
11538        // /data/app/com.example/lib/arm64/libfoo.so
11539        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11540
11541        /** New install */
11542        FileInstallArgs(InstallParams params) {
11543            super(params.origin, params.move, params.observer, params.installFlags,
11544                    params.installerPackageName, params.volumeUuid,
11545                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11546                    params.grantedRuntimePermissions,
11547                    params.traceMethod, params.traceCookie);
11548            if (isFwdLocked()) {
11549                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11550            }
11551        }
11552
11553        /** Existing install */
11554        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11555            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11556                    null, null, null, 0);
11557            this.codeFile = (codePath != null) ? new File(codePath) : null;
11558            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11559        }
11560
11561        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11562            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11563            try {
11564                return doCopyApk(imcs, temp);
11565            } finally {
11566                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11567            }
11568        }
11569
11570        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11571            if (origin.staged) {
11572                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11573                codeFile = origin.file;
11574                resourceFile = origin.file;
11575                return PackageManager.INSTALL_SUCCEEDED;
11576            }
11577
11578            try {
11579                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11580                final File tempDir =
11581                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11582                codeFile = tempDir;
11583                resourceFile = tempDir;
11584            } catch (IOException e) {
11585                Slog.w(TAG, "Failed to create copy file: " + e);
11586                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11587            }
11588
11589            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11590                @Override
11591                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11592                    if (!FileUtils.isValidExtFilename(name)) {
11593                        throw new IllegalArgumentException("Invalid filename: " + name);
11594                    }
11595                    try {
11596                        final File file = new File(codeFile, name);
11597                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11598                                O_RDWR | O_CREAT, 0644);
11599                        Os.chmod(file.getAbsolutePath(), 0644);
11600                        return new ParcelFileDescriptor(fd);
11601                    } catch (ErrnoException e) {
11602                        throw new RemoteException("Failed to open: " + e.getMessage());
11603                    }
11604                }
11605            };
11606
11607            int ret = PackageManager.INSTALL_SUCCEEDED;
11608            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11609            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11610                Slog.e(TAG, "Failed to copy package");
11611                return ret;
11612            }
11613
11614            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11615            NativeLibraryHelper.Handle handle = null;
11616            try {
11617                handle = NativeLibraryHelper.Handle.create(codeFile);
11618                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11619                        abiOverride);
11620            } catch (IOException e) {
11621                Slog.e(TAG, "Copying native libraries failed", e);
11622                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11623            } finally {
11624                IoUtils.closeQuietly(handle);
11625            }
11626
11627            return ret;
11628        }
11629
11630        int doPreInstall(int status) {
11631            if (status != PackageManager.INSTALL_SUCCEEDED) {
11632                cleanUp();
11633            }
11634            return status;
11635        }
11636
11637        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11638            if (status != PackageManager.INSTALL_SUCCEEDED) {
11639                cleanUp();
11640                return false;
11641            }
11642
11643            final File targetDir = codeFile.getParentFile();
11644            final File beforeCodeFile = codeFile;
11645            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11646
11647            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11648            try {
11649                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11650            } catch (ErrnoException e) {
11651                Slog.w(TAG, "Failed to rename", e);
11652                return false;
11653            }
11654
11655            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11656                Slog.w(TAG, "Failed to restorecon");
11657                return false;
11658            }
11659
11660            // Reflect the rename internally
11661            codeFile = afterCodeFile;
11662            resourceFile = afterCodeFile;
11663
11664            // Reflect the rename in scanned details
11665            pkg.codePath = afterCodeFile.getAbsolutePath();
11666            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11667                    pkg.baseCodePath);
11668            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11669                    pkg.splitCodePaths);
11670
11671            // Reflect the rename in app info
11672            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11673            pkg.applicationInfo.setCodePath(pkg.codePath);
11674            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11675            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11676            pkg.applicationInfo.setResourcePath(pkg.codePath);
11677            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11678            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11679
11680            return true;
11681        }
11682
11683        int doPostInstall(int status, int uid) {
11684            if (status != PackageManager.INSTALL_SUCCEEDED) {
11685                cleanUp();
11686            }
11687            return status;
11688        }
11689
11690        @Override
11691        String getCodePath() {
11692            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11693        }
11694
11695        @Override
11696        String getResourcePath() {
11697            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11698        }
11699
11700        private boolean cleanUp() {
11701            if (codeFile == null || !codeFile.exists()) {
11702                return false;
11703            }
11704
11705            if (codeFile.isDirectory()) {
11706                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11707            } else {
11708                codeFile.delete();
11709            }
11710
11711            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11712                resourceFile.delete();
11713            }
11714
11715            return true;
11716        }
11717
11718        void cleanUpResourcesLI() {
11719            // Try enumerating all code paths before deleting
11720            List<String> allCodePaths = Collections.EMPTY_LIST;
11721            if (codeFile != null && codeFile.exists()) {
11722                try {
11723                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11724                    allCodePaths = pkg.getAllCodePaths();
11725                } catch (PackageParserException e) {
11726                    // Ignored; we tried our best
11727                }
11728            }
11729
11730            cleanUp();
11731            removeDexFiles(allCodePaths, instructionSets);
11732        }
11733
11734        boolean doPostDeleteLI(boolean delete) {
11735            // XXX err, shouldn't we respect the delete flag?
11736            cleanUpResourcesLI();
11737            return true;
11738        }
11739    }
11740
11741    private boolean isAsecExternal(String cid) {
11742        final String asecPath = PackageHelper.getSdFilesystem(cid);
11743        return !asecPath.startsWith(mAsecInternalPath);
11744    }
11745
11746    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11747            PackageManagerException {
11748        if (copyRet < 0) {
11749            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11750                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11751                throw new PackageManagerException(copyRet, message);
11752            }
11753        }
11754    }
11755
11756    /**
11757     * Extract the MountService "container ID" from the full code path of an
11758     * .apk.
11759     */
11760    static String cidFromCodePath(String fullCodePath) {
11761        int eidx = fullCodePath.lastIndexOf("/");
11762        String subStr1 = fullCodePath.substring(0, eidx);
11763        int sidx = subStr1.lastIndexOf("/");
11764        return subStr1.substring(sidx+1, eidx);
11765    }
11766
11767    /**
11768     * Logic to handle installation of ASEC applications, including copying and
11769     * renaming logic.
11770     */
11771    class AsecInstallArgs extends InstallArgs {
11772        static final String RES_FILE_NAME = "pkg.apk";
11773        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11774
11775        String cid;
11776        String packagePath;
11777        String resourcePath;
11778
11779        /** New install */
11780        AsecInstallArgs(InstallParams params) {
11781            super(params.origin, params.move, params.observer, params.installFlags,
11782                    params.installerPackageName, params.volumeUuid,
11783                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11784                    params.grantedRuntimePermissions,
11785                    params.traceMethod, params.traceCookie);
11786        }
11787
11788        /** Existing install */
11789        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11790                        boolean isExternal, boolean isForwardLocked) {
11791            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11792                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11793                    instructionSets, null, null, null, 0);
11794            // Hackily pretend we're still looking at a full code path
11795            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11796                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11797            }
11798
11799            // Extract cid from fullCodePath
11800            int eidx = fullCodePath.lastIndexOf("/");
11801            String subStr1 = fullCodePath.substring(0, eidx);
11802            int sidx = subStr1.lastIndexOf("/");
11803            cid = subStr1.substring(sidx+1, eidx);
11804            setMountPath(subStr1);
11805        }
11806
11807        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11808            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11809                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11810                    instructionSets, null, null, null, 0);
11811            this.cid = cid;
11812            setMountPath(PackageHelper.getSdDir(cid));
11813        }
11814
11815        void createCopyFile() {
11816            cid = mInstallerService.allocateExternalStageCidLegacy();
11817        }
11818
11819        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11820            if (origin.staged && origin.cid != null) {
11821                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11822                cid = origin.cid;
11823                setMountPath(PackageHelper.getSdDir(cid));
11824                return PackageManager.INSTALL_SUCCEEDED;
11825            }
11826
11827            if (temp) {
11828                createCopyFile();
11829            } else {
11830                /*
11831                 * Pre-emptively destroy the container since it's destroyed if
11832                 * copying fails due to it existing anyway.
11833                 */
11834                PackageHelper.destroySdDir(cid);
11835            }
11836
11837            final String newMountPath = imcs.copyPackageToContainer(
11838                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11839                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11840
11841            if (newMountPath != null) {
11842                setMountPath(newMountPath);
11843                return PackageManager.INSTALL_SUCCEEDED;
11844            } else {
11845                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11846            }
11847        }
11848
11849        @Override
11850        String getCodePath() {
11851            return packagePath;
11852        }
11853
11854        @Override
11855        String getResourcePath() {
11856            return resourcePath;
11857        }
11858
11859        int doPreInstall(int status) {
11860            if (status != PackageManager.INSTALL_SUCCEEDED) {
11861                // Destroy container
11862                PackageHelper.destroySdDir(cid);
11863            } else {
11864                boolean mounted = PackageHelper.isContainerMounted(cid);
11865                if (!mounted) {
11866                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11867                            Process.SYSTEM_UID);
11868                    if (newMountPath != null) {
11869                        setMountPath(newMountPath);
11870                    } else {
11871                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11872                    }
11873                }
11874            }
11875            return status;
11876        }
11877
11878        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11879            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11880            String newMountPath = null;
11881            if (PackageHelper.isContainerMounted(cid)) {
11882                // Unmount the container
11883                if (!PackageHelper.unMountSdDir(cid)) {
11884                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11885                    return false;
11886                }
11887            }
11888            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11889                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11890                        " which might be stale. Will try to clean up.");
11891                // Clean up the stale container and proceed to recreate.
11892                if (!PackageHelper.destroySdDir(newCacheId)) {
11893                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11894                    return false;
11895                }
11896                // Successfully cleaned up stale container. Try to rename again.
11897                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11898                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11899                            + " inspite of cleaning it up.");
11900                    return false;
11901                }
11902            }
11903            if (!PackageHelper.isContainerMounted(newCacheId)) {
11904                Slog.w(TAG, "Mounting container " + newCacheId);
11905                newMountPath = PackageHelper.mountSdDir(newCacheId,
11906                        getEncryptKey(), Process.SYSTEM_UID);
11907            } else {
11908                newMountPath = PackageHelper.getSdDir(newCacheId);
11909            }
11910            if (newMountPath == null) {
11911                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11912                return false;
11913            }
11914            Log.i(TAG, "Succesfully renamed " + cid +
11915                    " to " + newCacheId +
11916                    " at new path: " + newMountPath);
11917            cid = newCacheId;
11918
11919            final File beforeCodeFile = new File(packagePath);
11920            setMountPath(newMountPath);
11921            final File afterCodeFile = new File(packagePath);
11922
11923            // Reflect the rename in scanned details
11924            pkg.codePath = afterCodeFile.getAbsolutePath();
11925            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11926                    pkg.baseCodePath);
11927            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11928                    pkg.splitCodePaths);
11929
11930            // Reflect the rename in app info
11931            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11932            pkg.applicationInfo.setCodePath(pkg.codePath);
11933            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11934            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11935            pkg.applicationInfo.setResourcePath(pkg.codePath);
11936            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11937            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11938
11939            return true;
11940        }
11941
11942        private void setMountPath(String mountPath) {
11943            final File mountFile = new File(mountPath);
11944
11945            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11946            if (monolithicFile.exists()) {
11947                packagePath = monolithicFile.getAbsolutePath();
11948                if (isFwdLocked()) {
11949                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11950                } else {
11951                    resourcePath = packagePath;
11952                }
11953            } else {
11954                packagePath = mountFile.getAbsolutePath();
11955                resourcePath = packagePath;
11956            }
11957        }
11958
11959        int doPostInstall(int status, int uid) {
11960            if (status != PackageManager.INSTALL_SUCCEEDED) {
11961                cleanUp();
11962            } else {
11963                final int groupOwner;
11964                final String protectedFile;
11965                if (isFwdLocked()) {
11966                    groupOwner = UserHandle.getSharedAppGid(uid);
11967                    protectedFile = RES_FILE_NAME;
11968                } else {
11969                    groupOwner = -1;
11970                    protectedFile = null;
11971                }
11972
11973                if (uid < Process.FIRST_APPLICATION_UID
11974                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11975                    Slog.e(TAG, "Failed to finalize " + cid);
11976                    PackageHelper.destroySdDir(cid);
11977                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11978                }
11979
11980                boolean mounted = PackageHelper.isContainerMounted(cid);
11981                if (!mounted) {
11982                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11983                }
11984            }
11985            return status;
11986        }
11987
11988        private void cleanUp() {
11989            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11990
11991            // Destroy secure container
11992            PackageHelper.destroySdDir(cid);
11993        }
11994
11995        private List<String> getAllCodePaths() {
11996            final File codeFile = new File(getCodePath());
11997            if (codeFile != null && codeFile.exists()) {
11998                try {
11999                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12000                    return pkg.getAllCodePaths();
12001                } catch (PackageParserException e) {
12002                    // Ignored; we tried our best
12003                }
12004            }
12005            return Collections.EMPTY_LIST;
12006        }
12007
12008        void cleanUpResourcesLI() {
12009            // Enumerate all code paths before deleting
12010            cleanUpResourcesLI(getAllCodePaths());
12011        }
12012
12013        private void cleanUpResourcesLI(List<String> allCodePaths) {
12014            cleanUp();
12015            removeDexFiles(allCodePaths, instructionSets);
12016        }
12017
12018        String getPackageName() {
12019            return getAsecPackageName(cid);
12020        }
12021
12022        boolean doPostDeleteLI(boolean delete) {
12023            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12024            final List<String> allCodePaths = getAllCodePaths();
12025            boolean mounted = PackageHelper.isContainerMounted(cid);
12026            if (mounted) {
12027                // Unmount first
12028                if (PackageHelper.unMountSdDir(cid)) {
12029                    mounted = false;
12030                }
12031            }
12032            if (!mounted && delete) {
12033                cleanUpResourcesLI(allCodePaths);
12034            }
12035            return !mounted;
12036        }
12037
12038        @Override
12039        int doPreCopy() {
12040            if (isFwdLocked()) {
12041                if (!PackageHelper.fixSdPermissions(cid,
12042                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12043                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12044                }
12045            }
12046
12047            return PackageManager.INSTALL_SUCCEEDED;
12048        }
12049
12050        @Override
12051        int doPostCopy(int uid) {
12052            if (isFwdLocked()) {
12053                if (uid < Process.FIRST_APPLICATION_UID
12054                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12055                                RES_FILE_NAME)) {
12056                    Slog.e(TAG, "Failed to finalize " + cid);
12057                    PackageHelper.destroySdDir(cid);
12058                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12059                }
12060            }
12061
12062            return PackageManager.INSTALL_SUCCEEDED;
12063        }
12064    }
12065
12066    /**
12067     * Logic to handle movement of existing installed applications.
12068     */
12069    class MoveInstallArgs extends InstallArgs {
12070        private File codeFile;
12071        private File resourceFile;
12072
12073        /** New install */
12074        MoveInstallArgs(InstallParams params) {
12075            super(params.origin, params.move, params.observer, params.installFlags,
12076                    params.installerPackageName, params.volumeUuid,
12077                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12078                    params.grantedRuntimePermissions,
12079                    params.traceMethod, params.traceCookie);
12080        }
12081
12082        int copyApk(IMediaContainerService imcs, boolean temp) {
12083            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12084                    + move.fromUuid + " to " + move.toUuid);
12085            synchronized (mInstaller) {
12086                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12087                        move.dataAppName, move.appId, move.seinfo) != 0) {
12088                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12089                }
12090            }
12091
12092            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12093            resourceFile = codeFile;
12094            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12095
12096            return PackageManager.INSTALL_SUCCEEDED;
12097        }
12098
12099        int doPreInstall(int status) {
12100            if (status != PackageManager.INSTALL_SUCCEEDED) {
12101                cleanUp(move.toUuid);
12102            }
12103            return status;
12104        }
12105
12106        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12107            if (status != PackageManager.INSTALL_SUCCEEDED) {
12108                cleanUp(move.toUuid);
12109                return false;
12110            }
12111
12112            // Reflect the move in app info
12113            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12114            pkg.applicationInfo.setCodePath(pkg.codePath);
12115            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12116            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12117            pkg.applicationInfo.setResourcePath(pkg.codePath);
12118            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12119            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12120
12121            return true;
12122        }
12123
12124        int doPostInstall(int status, int uid) {
12125            if (status == PackageManager.INSTALL_SUCCEEDED) {
12126                cleanUp(move.fromUuid);
12127            } else {
12128                cleanUp(move.toUuid);
12129            }
12130            return status;
12131        }
12132
12133        @Override
12134        String getCodePath() {
12135            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12136        }
12137
12138        @Override
12139        String getResourcePath() {
12140            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12141        }
12142
12143        private boolean cleanUp(String volumeUuid) {
12144            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12145                    move.dataAppName);
12146            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12147            synchronized (mInstallLock) {
12148                // Clean up both app data and code
12149                removeDataDirsLI(volumeUuid, move.packageName);
12150                if (codeFile.isDirectory()) {
12151                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12152                } else {
12153                    codeFile.delete();
12154                }
12155            }
12156            return true;
12157        }
12158
12159        void cleanUpResourcesLI() {
12160            throw new UnsupportedOperationException();
12161        }
12162
12163        boolean doPostDeleteLI(boolean delete) {
12164            throw new UnsupportedOperationException();
12165        }
12166    }
12167
12168    static String getAsecPackageName(String packageCid) {
12169        int idx = packageCid.lastIndexOf("-");
12170        if (idx == -1) {
12171            return packageCid;
12172        }
12173        return packageCid.substring(0, idx);
12174    }
12175
12176    // Utility method used to create code paths based on package name and available index.
12177    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12178        String idxStr = "";
12179        int idx = 1;
12180        // Fall back to default value of idx=1 if prefix is not
12181        // part of oldCodePath
12182        if (oldCodePath != null) {
12183            String subStr = oldCodePath;
12184            // Drop the suffix right away
12185            if (suffix != null && subStr.endsWith(suffix)) {
12186                subStr = subStr.substring(0, subStr.length() - suffix.length());
12187            }
12188            // If oldCodePath already contains prefix find out the
12189            // ending index to either increment or decrement.
12190            int sidx = subStr.lastIndexOf(prefix);
12191            if (sidx != -1) {
12192                subStr = subStr.substring(sidx + prefix.length());
12193                if (subStr != null) {
12194                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12195                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12196                    }
12197                    try {
12198                        idx = Integer.parseInt(subStr);
12199                        if (idx <= 1) {
12200                            idx++;
12201                        } else {
12202                            idx--;
12203                        }
12204                    } catch(NumberFormatException e) {
12205                    }
12206                }
12207            }
12208        }
12209        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12210        return prefix + idxStr;
12211    }
12212
12213    private File getNextCodePath(File targetDir, String packageName) {
12214        int suffix = 1;
12215        File result;
12216        do {
12217            result = new File(targetDir, packageName + "-" + suffix);
12218            suffix++;
12219        } while (result.exists());
12220        return result;
12221    }
12222
12223    // Utility method that returns the relative package path with respect
12224    // to the installation directory. Like say for /data/data/com.test-1.apk
12225    // string com.test-1 is returned.
12226    static String deriveCodePathName(String codePath) {
12227        if (codePath == null) {
12228            return null;
12229        }
12230        final File codeFile = new File(codePath);
12231        final String name = codeFile.getName();
12232        if (codeFile.isDirectory()) {
12233            return name;
12234        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12235            final int lastDot = name.lastIndexOf('.');
12236            return name.substring(0, lastDot);
12237        } else {
12238            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12239            return null;
12240        }
12241    }
12242
12243    static class PackageInstalledInfo {
12244        String name;
12245        int uid;
12246        // The set of users that originally had this package installed.
12247        int[] origUsers;
12248        // The set of users that now have this package installed.
12249        int[] newUsers;
12250        PackageParser.Package pkg;
12251        int returnCode;
12252        String returnMsg;
12253        PackageRemovedInfo removedInfo;
12254
12255        public void setError(int code, String msg) {
12256            returnCode = code;
12257            returnMsg = msg;
12258            Slog.w(TAG, msg);
12259        }
12260
12261        public void setError(String msg, PackageParserException e) {
12262            returnCode = e.error;
12263            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12264            Slog.w(TAG, msg, e);
12265        }
12266
12267        public void setError(String msg, PackageManagerException e) {
12268            returnCode = e.error;
12269            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12270            Slog.w(TAG, msg, e);
12271        }
12272
12273        // In some error cases we want to convey more info back to the observer
12274        String origPackage;
12275        String origPermission;
12276    }
12277
12278    /*
12279     * Install a non-existing package.
12280     */
12281    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12282            UserHandle user, String installerPackageName, String volumeUuid,
12283            PackageInstalledInfo res) {
12284        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12285
12286        // Remember this for later, in case we need to rollback this install
12287        String pkgName = pkg.packageName;
12288
12289        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12290        // TODO: b/23350563
12291        final boolean dataDirExists = Environment
12292                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12293
12294        synchronized(mPackages) {
12295            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12296                // A package with the same name is already installed, though
12297                // it has been renamed to an older name.  The package we
12298                // are trying to install should be installed as an update to
12299                // the existing one, but that has not been requested, so bail.
12300                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12301                        + " without first uninstalling package running as "
12302                        + mSettings.mRenamedPackages.get(pkgName));
12303                return;
12304            }
12305            if (mPackages.containsKey(pkgName)) {
12306                // Don't allow installation over an existing package with the same name.
12307                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12308                        + " without first uninstalling.");
12309                return;
12310            }
12311        }
12312
12313        try {
12314            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12315                    System.currentTimeMillis(), user);
12316
12317            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12318            // delete the partially installed application. the data directory will have to be
12319            // restored if it was already existing
12320            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12321                // remove package from internal structures.  Note that we want deletePackageX to
12322                // delete the package data and cache directories that it created in
12323                // scanPackageLocked, unless those directories existed before we even tried to
12324                // install.
12325                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12326                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12327                                res.removedInfo, true);
12328            }
12329
12330        } catch (PackageManagerException e) {
12331            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12332        }
12333
12334        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12335    }
12336
12337    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12338        // Can't rotate keys during boot or if sharedUser.
12339        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12340                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12341            return false;
12342        }
12343        // app is using upgradeKeySets; make sure all are valid
12344        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12345        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12346        for (int i = 0; i < upgradeKeySets.length; i++) {
12347            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12348                Slog.wtf(TAG, "Package "
12349                         + (oldPs.name != null ? oldPs.name : "<null>")
12350                         + " contains upgrade-key-set reference to unknown key-set: "
12351                         + upgradeKeySets[i]
12352                         + " reverting to signatures check.");
12353                return false;
12354            }
12355        }
12356        return true;
12357    }
12358
12359    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12360        // Upgrade keysets are being used.  Determine if new package has a superset of the
12361        // required keys.
12362        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12363        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12364        for (int i = 0; i < upgradeKeySets.length; i++) {
12365            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12366            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12367                return true;
12368            }
12369        }
12370        return false;
12371    }
12372
12373    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12374            UserHandle user, String installerPackageName, String volumeUuid,
12375            PackageInstalledInfo res) {
12376        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12377
12378        final PackageParser.Package oldPackage;
12379        final String pkgName = pkg.packageName;
12380        final int[] allUsers;
12381        final boolean[] perUserInstalled;
12382
12383        // First find the old package info and check signatures
12384        synchronized(mPackages) {
12385            oldPackage = mPackages.get(pkgName);
12386            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12387            if (isEphemeral && !oldIsEphemeral) {
12388                // can't downgrade from full to ephemeral
12389                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12390                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12391                return;
12392            }
12393            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12394            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12395            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12396                if(!checkUpgradeKeySetLP(ps, pkg)) {
12397                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12398                            "New package not signed by keys specified by upgrade-keysets: "
12399                            + pkgName);
12400                    return;
12401                }
12402            } else {
12403                // default to original signature matching
12404                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12405                    != PackageManager.SIGNATURE_MATCH) {
12406                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12407                            "New package has a different signature: " + pkgName);
12408                    return;
12409                }
12410            }
12411
12412            // In case of rollback, remember per-user/profile install state
12413            allUsers = sUserManager.getUserIds();
12414            perUserInstalled = new boolean[allUsers.length];
12415            for (int i = 0; i < allUsers.length; i++) {
12416                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12417            }
12418        }
12419
12420        boolean sysPkg = (isSystemApp(oldPackage));
12421        if (sysPkg) {
12422            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12423                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12424        } else {
12425            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12426                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12427        }
12428    }
12429
12430    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12431            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12432            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12433            String volumeUuid, PackageInstalledInfo res) {
12434        String pkgName = deletedPackage.packageName;
12435        boolean deletedPkg = true;
12436        boolean updatedSettings = false;
12437
12438        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12439                + deletedPackage);
12440        long origUpdateTime;
12441        if (pkg.mExtras != null) {
12442            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12443        } else {
12444            origUpdateTime = 0;
12445        }
12446
12447        // First delete the existing package while retaining the data directory
12448        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12449                res.removedInfo, true)) {
12450            // If the existing package wasn't successfully deleted
12451            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12452            deletedPkg = false;
12453        } else {
12454            // Successfully deleted the old package; proceed with replace.
12455
12456            // If deleted package lived in a container, give users a chance to
12457            // relinquish resources before killing.
12458            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12459                if (DEBUG_INSTALL) {
12460                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12461                }
12462                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12463                final ArrayList<String> pkgList = new ArrayList<String>(1);
12464                pkgList.add(deletedPackage.applicationInfo.packageName);
12465                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12466            }
12467
12468            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12469            try {
12470                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12471                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12472                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12473                        perUserInstalled, res, user);
12474                updatedSettings = true;
12475            } catch (PackageManagerException e) {
12476                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12477            }
12478        }
12479
12480        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12481            // remove package from internal structures.  Note that we want deletePackageX to
12482            // delete the package data and cache directories that it created in
12483            // scanPackageLocked, unless those directories existed before we even tried to
12484            // install.
12485            if(updatedSettings) {
12486                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12487                deletePackageLI(
12488                        pkgName, null, true, allUsers, perUserInstalled,
12489                        PackageManager.DELETE_KEEP_DATA,
12490                                res.removedInfo, true);
12491            }
12492            // Since we failed to install the new package we need to restore the old
12493            // package that we deleted.
12494            if (deletedPkg) {
12495                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12496                File restoreFile = new File(deletedPackage.codePath);
12497                // Parse old package
12498                boolean oldExternal = isExternal(deletedPackage);
12499                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12500                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12501                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12502                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12503                try {
12504                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12505                            null);
12506                } catch (PackageManagerException e) {
12507                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12508                            + e.getMessage());
12509                    return;
12510                }
12511                // Restore of old package succeeded. Update permissions.
12512                // writer
12513                synchronized (mPackages) {
12514                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12515                            UPDATE_PERMISSIONS_ALL);
12516                    // can downgrade to reader
12517                    mSettings.writeLPr();
12518                }
12519                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12520            }
12521        }
12522    }
12523
12524    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12525            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12526            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12527            String volumeUuid, PackageInstalledInfo res) {
12528        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12529                + ", old=" + deletedPackage);
12530        boolean disabledSystem = false;
12531        boolean updatedSettings = false;
12532        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12533        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12534                != 0) {
12535            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12536        }
12537        String packageName = deletedPackage.packageName;
12538        if (packageName == null) {
12539            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12540                    "Attempt to delete null packageName.");
12541            return;
12542        }
12543        PackageParser.Package oldPkg;
12544        PackageSetting oldPkgSetting;
12545        // reader
12546        synchronized (mPackages) {
12547            oldPkg = mPackages.get(packageName);
12548            oldPkgSetting = mSettings.mPackages.get(packageName);
12549            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12550                    (oldPkgSetting == null)) {
12551                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12552                        "Couldn't find package " + packageName + " information");
12553                return;
12554            }
12555        }
12556
12557        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12558
12559        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12560        res.removedInfo.removedPackage = packageName;
12561        // Remove existing system package
12562        removePackageLI(oldPkgSetting, true);
12563        // writer
12564        synchronized (mPackages) {
12565            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12566            if (!disabledSystem && deletedPackage != null) {
12567                // We didn't need to disable the .apk as a current system package,
12568                // which means we are replacing another update that is already
12569                // installed.  We need to make sure to delete the older one's .apk.
12570                res.removedInfo.args = createInstallArgsForExisting(0,
12571                        deletedPackage.applicationInfo.getCodePath(),
12572                        deletedPackage.applicationInfo.getResourcePath(),
12573                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12574            } else {
12575                res.removedInfo.args = null;
12576            }
12577        }
12578
12579        // Successfully disabled the old package. Now proceed with re-installation
12580        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12581
12582        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12583        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12584
12585        PackageParser.Package newPackage = null;
12586        try {
12587            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12588            if (newPackage.mExtras != null) {
12589                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12590                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12591                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12592
12593                // is the update attempting to change shared user? that isn't going to work...
12594                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12595                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12596                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12597                            + " to " + newPkgSetting.sharedUser);
12598                    updatedSettings = true;
12599                }
12600            }
12601
12602            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12603                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12604                        perUserInstalled, res, user);
12605                updatedSettings = true;
12606            }
12607
12608        } catch (PackageManagerException e) {
12609            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12610        }
12611
12612        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12613            // Re installation failed. Restore old information
12614            // Remove new pkg information
12615            if (newPackage != null) {
12616                removeInstalledPackageLI(newPackage, true);
12617            }
12618            // Add back the old system package
12619            try {
12620                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12621            } catch (PackageManagerException e) {
12622                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12623            }
12624            // Restore the old system information in Settings
12625            synchronized (mPackages) {
12626                if (disabledSystem) {
12627                    mSettings.enableSystemPackageLPw(packageName);
12628                }
12629                if (updatedSettings) {
12630                    mSettings.setInstallerPackageName(packageName,
12631                            oldPkgSetting.installerPackageName);
12632                }
12633                mSettings.writeLPr();
12634            }
12635        }
12636    }
12637
12638    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12639        // Collect all used permissions in the UID
12640        ArraySet<String> usedPermissions = new ArraySet<>();
12641        final int packageCount = su.packages.size();
12642        for (int i = 0; i < packageCount; i++) {
12643            PackageSetting ps = su.packages.valueAt(i);
12644            if (ps.pkg == null) {
12645                continue;
12646            }
12647            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12648            for (int j = 0; j < requestedPermCount; j++) {
12649                String permission = ps.pkg.requestedPermissions.get(j);
12650                BasePermission bp = mSettings.mPermissions.get(permission);
12651                if (bp != null) {
12652                    usedPermissions.add(permission);
12653                }
12654            }
12655        }
12656
12657        PermissionsState permissionsState = su.getPermissionsState();
12658        // Prune install permissions
12659        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12660        final int installPermCount = installPermStates.size();
12661        for (int i = installPermCount - 1; i >= 0;  i--) {
12662            PermissionState permissionState = installPermStates.get(i);
12663            if (!usedPermissions.contains(permissionState.getName())) {
12664                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12665                if (bp != null) {
12666                    permissionsState.revokeInstallPermission(bp);
12667                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12668                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12669                }
12670            }
12671        }
12672
12673        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12674
12675        // Prune runtime permissions
12676        for (int userId : allUserIds) {
12677            List<PermissionState> runtimePermStates = permissionsState
12678                    .getRuntimePermissionStates(userId);
12679            final int runtimePermCount = runtimePermStates.size();
12680            for (int i = runtimePermCount - 1; i >= 0; i--) {
12681                PermissionState permissionState = runtimePermStates.get(i);
12682                if (!usedPermissions.contains(permissionState.getName())) {
12683                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12684                    if (bp != null) {
12685                        permissionsState.revokeRuntimePermission(bp, userId);
12686                        permissionsState.updatePermissionFlags(bp, userId,
12687                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12688                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12689                                runtimePermissionChangedUserIds, userId);
12690                    }
12691                }
12692            }
12693        }
12694
12695        return runtimePermissionChangedUserIds;
12696    }
12697
12698    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12699            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12700            UserHandle user) {
12701        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12702
12703        String pkgName = newPackage.packageName;
12704        synchronized (mPackages) {
12705            //write settings. the installStatus will be incomplete at this stage.
12706            //note that the new package setting would have already been
12707            //added to mPackages. It hasn't been persisted yet.
12708            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12709            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12710            mSettings.writeLPr();
12711            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12712        }
12713
12714        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12715        synchronized (mPackages) {
12716            updatePermissionsLPw(newPackage.packageName, newPackage,
12717                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12718                            ? UPDATE_PERMISSIONS_ALL : 0));
12719            // For system-bundled packages, we assume that installing an upgraded version
12720            // of the package implies that the user actually wants to run that new code,
12721            // so we enable the package.
12722            PackageSetting ps = mSettings.mPackages.get(pkgName);
12723            if (ps != null) {
12724                if (isSystemApp(newPackage)) {
12725                    // NB: implicit assumption that system package upgrades apply to all users
12726                    if (DEBUG_INSTALL) {
12727                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12728                    }
12729                    if (res.origUsers != null) {
12730                        for (int userHandle : res.origUsers) {
12731                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12732                                    userHandle, installerPackageName);
12733                        }
12734                    }
12735                    // Also convey the prior install/uninstall state
12736                    if (allUsers != null && perUserInstalled != null) {
12737                        for (int i = 0; i < allUsers.length; i++) {
12738                            if (DEBUG_INSTALL) {
12739                                Slog.d(TAG, "    user " + allUsers[i]
12740                                        + " => " + perUserInstalled[i]);
12741                            }
12742                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12743                        }
12744                        // these install state changes will be persisted in the
12745                        // upcoming call to mSettings.writeLPr().
12746                    }
12747                }
12748                // It's implied that when a user requests installation, they want the app to be
12749                // installed and enabled.
12750                int userId = user.getIdentifier();
12751                if (userId != UserHandle.USER_ALL) {
12752                    ps.setInstalled(true, userId);
12753                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12754                }
12755            }
12756            res.name = pkgName;
12757            res.uid = newPackage.applicationInfo.uid;
12758            res.pkg = newPackage;
12759            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12760            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12761            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12762            //to update install status
12763            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12764            mSettings.writeLPr();
12765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12766        }
12767
12768        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12769    }
12770
12771    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12772        try {
12773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12774            installPackageLI(args, res);
12775        } finally {
12776            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12777        }
12778    }
12779
12780    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12781        final int installFlags = args.installFlags;
12782        final String installerPackageName = args.installerPackageName;
12783        final String volumeUuid = args.volumeUuid;
12784        final File tmpPackageFile = new File(args.getCodePath());
12785        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12786        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12787                || (args.volumeUuid != null));
12788        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12789        boolean replace = false;
12790        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12791        if (args.move != null) {
12792            // moving a complete application; perfom an initial scan on the new install location
12793            scanFlags |= SCAN_INITIAL;
12794        }
12795        // Result object to be returned
12796        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12797
12798        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12799
12800        // Sanity check
12801        if (ephemeral && (forwardLocked || onExternal)) {
12802            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12803                    + " external=" + onExternal);
12804            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12805            return;
12806        }
12807
12808        // Retrieve PackageSettings and parse package
12809        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12810                | PackageParser.PARSE_ENFORCE_CODE
12811                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12812                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12813                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12814        PackageParser pp = new PackageParser();
12815        pp.setSeparateProcesses(mSeparateProcesses);
12816        pp.setDisplayMetrics(mMetrics);
12817
12818        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12819        final PackageParser.Package pkg;
12820        try {
12821            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12822        } catch (PackageParserException e) {
12823            res.setError("Failed parse during installPackageLI", e);
12824            return;
12825        } finally {
12826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12827        }
12828
12829        // Mark that we have an install time CPU ABI override.
12830        pkg.cpuAbiOverride = args.abiOverride;
12831
12832        String pkgName = res.name = pkg.packageName;
12833        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12834            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12835                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12836                return;
12837            }
12838        }
12839
12840        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12841        try {
12842            pp.collectCertificates(pkg, parseFlags);
12843        } catch (PackageParserException e) {
12844            res.setError("Failed collect during installPackageLI", e);
12845            return;
12846        } finally {
12847            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12848        }
12849
12850        // Get rid of all references to package scan path via parser.
12851        pp = null;
12852        String oldCodePath = null;
12853        boolean systemApp = false;
12854        synchronized (mPackages) {
12855            // Check if installing already existing package
12856            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12857                String oldName = mSettings.mRenamedPackages.get(pkgName);
12858                if (pkg.mOriginalPackages != null
12859                        && pkg.mOriginalPackages.contains(oldName)
12860                        && mPackages.containsKey(oldName)) {
12861                    // This package is derived from an original package,
12862                    // and this device has been updating from that original
12863                    // name.  We must continue using the original name, so
12864                    // rename the new package here.
12865                    pkg.setPackageName(oldName);
12866                    pkgName = pkg.packageName;
12867                    replace = true;
12868                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12869                            + oldName + " pkgName=" + pkgName);
12870                } else if (mPackages.containsKey(pkgName)) {
12871                    // This package, under its official name, already exists
12872                    // on the device; we should replace it.
12873                    replace = true;
12874                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12875                }
12876
12877                // Prevent apps opting out from runtime permissions
12878                if (replace) {
12879                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12880                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12881                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12882                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12883                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12884                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12885                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12886                                        + " doesn't support runtime permissions but the old"
12887                                        + " target SDK " + oldTargetSdk + " does.");
12888                        return;
12889                    }
12890                }
12891            }
12892
12893            PackageSetting ps = mSettings.mPackages.get(pkgName);
12894            if (ps != null) {
12895                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12896
12897                // Quick sanity check that we're signed correctly if updating;
12898                // we'll check this again later when scanning, but we want to
12899                // bail early here before tripping over redefined permissions.
12900                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12901                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12902                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12903                                + pkg.packageName + " upgrade keys do not match the "
12904                                + "previously installed version");
12905                        return;
12906                    }
12907                } else {
12908                    try {
12909                        verifySignaturesLP(ps, pkg);
12910                    } catch (PackageManagerException e) {
12911                        res.setError(e.error, e.getMessage());
12912                        return;
12913                    }
12914                }
12915
12916                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12917                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12918                    systemApp = (ps.pkg.applicationInfo.flags &
12919                            ApplicationInfo.FLAG_SYSTEM) != 0;
12920                }
12921                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12922            }
12923
12924            // Check whether the newly-scanned package wants to define an already-defined perm
12925            int N = pkg.permissions.size();
12926            for (int i = N-1; i >= 0; i--) {
12927                PackageParser.Permission perm = pkg.permissions.get(i);
12928                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12929                if (bp != null) {
12930                    // If the defining package is signed with our cert, it's okay.  This
12931                    // also includes the "updating the same package" case, of course.
12932                    // "updating same package" could also involve key-rotation.
12933                    final boolean sigsOk;
12934                    if (bp.sourcePackage.equals(pkg.packageName)
12935                            && (bp.packageSetting instanceof PackageSetting)
12936                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12937                                    scanFlags))) {
12938                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12939                    } else {
12940                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12941                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12942                    }
12943                    if (!sigsOk) {
12944                        // If the owning package is the system itself, we log but allow
12945                        // install to proceed; we fail the install on all other permission
12946                        // redefinitions.
12947                        if (!bp.sourcePackage.equals("android")) {
12948                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12949                                    + pkg.packageName + " attempting to redeclare permission "
12950                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12951                            res.origPermission = perm.info.name;
12952                            res.origPackage = bp.sourcePackage;
12953                            return;
12954                        } else {
12955                            Slog.w(TAG, "Package " + pkg.packageName
12956                                    + " attempting to redeclare system permission "
12957                                    + perm.info.name + "; ignoring new declaration");
12958                            pkg.permissions.remove(i);
12959                        }
12960                    }
12961                }
12962            }
12963
12964        }
12965
12966        if (systemApp) {
12967            if (onExternal) {
12968                // Abort update; system app can't be replaced with app on sdcard
12969                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12970                        "Cannot install updates to system apps on sdcard");
12971                return;
12972            } else if (ephemeral) {
12973                // Abort update; system app can't be replaced with an ephemeral app
12974                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12975                        "Cannot update a system app with an ephemeral app");
12976                return;
12977            }
12978        }
12979
12980        if (args.move != null) {
12981            // We did an in-place move, so dex is ready to roll
12982            scanFlags |= SCAN_NO_DEX;
12983            scanFlags |= SCAN_MOVE;
12984
12985            synchronized (mPackages) {
12986                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12987                if (ps == null) {
12988                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12989                            "Missing settings for moved package " + pkgName);
12990                }
12991
12992                // We moved the entire application as-is, so bring over the
12993                // previously derived ABI information.
12994                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12995                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12996            }
12997
12998        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12999            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13000            scanFlags |= SCAN_NO_DEX;
13001
13002            try {
13003                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13004                        true /* extract libs */);
13005            } catch (PackageManagerException pme) {
13006                Slog.e(TAG, "Error deriving application ABI", pme);
13007                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13008                return;
13009            }
13010        }
13011
13012        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13013            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13014            return;
13015        }
13016
13017        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13018
13019        if (replace) {
13020            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13021                    installerPackageName, volumeUuid, res);
13022        } else {
13023            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13024                    args.user, installerPackageName, volumeUuid, res);
13025        }
13026        synchronized (mPackages) {
13027            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13028            if (ps != null) {
13029                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13030            }
13031        }
13032    }
13033
13034    private void startIntentFilterVerifications(int userId, boolean replacing,
13035            PackageParser.Package pkg) {
13036        if (mIntentFilterVerifierComponent == null) {
13037            Slog.w(TAG, "No IntentFilter verification will not be done as "
13038                    + "there is no IntentFilterVerifier available!");
13039            return;
13040        }
13041
13042        final int verifierUid = getPackageUid(
13043                mIntentFilterVerifierComponent.getPackageName(),
13044                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13045
13046        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13047        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13048        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13049        mHandler.sendMessage(msg);
13050    }
13051
13052    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13053            PackageParser.Package pkg) {
13054        int size = pkg.activities.size();
13055        if (size == 0) {
13056            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13057                    "No activity, so no need to verify any IntentFilter!");
13058            return;
13059        }
13060
13061        final boolean hasDomainURLs = hasDomainURLs(pkg);
13062        if (!hasDomainURLs) {
13063            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13064                    "No domain URLs, so no need to verify any IntentFilter!");
13065            return;
13066        }
13067
13068        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13069                + " if any IntentFilter from the " + size
13070                + " Activities needs verification ...");
13071
13072        int count = 0;
13073        final String packageName = pkg.packageName;
13074
13075        synchronized (mPackages) {
13076            // If this is a new install and we see that we've already run verification for this
13077            // package, we have nothing to do: it means the state was restored from backup.
13078            if (!replacing) {
13079                IntentFilterVerificationInfo ivi =
13080                        mSettings.getIntentFilterVerificationLPr(packageName);
13081                if (ivi != null) {
13082                    if (DEBUG_DOMAIN_VERIFICATION) {
13083                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13084                                + ivi.getStatusString());
13085                    }
13086                    return;
13087                }
13088            }
13089
13090            // If any filters need to be verified, then all need to be.
13091            boolean needToVerify = false;
13092            for (PackageParser.Activity a : pkg.activities) {
13093                for (ActivityIntentInfo filter : a.intents) {
13094                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13095                        if (DEBUG_DOMAIN_VERIFICATION) {
13096                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13097                        }
13098                        needToVerify = true;
13099                        break;
13100                    }
13101                }
13102            }
13103
13104            if (needToVerify) {
13105                final int verificationId = mIntentFilterVerificationToken++;
13106                for (PackageParser.Activity a : pkg.activities) {
13107                    for (ActivityIntentInfo filter : a.intents) {
13108                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13109                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13110                                    "Verification needed for IntentFilter:" + filter.toString());
13111                            mIntentFilterVerifier.addOneIntentFilterVerification(
13112                                    verifierUid, userId, verificationId, filter, packageName);
13113                            count++;
13114                        }
13115                    }
13116                }
13117            }
13118        }
13119
13120        if (count > 0) {
13121            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13122                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13123                    +  " for userId:" + userId);
13124            mIntentFilterVerifier.startVerifications(userId);
13125        } else {
13126            if (DEBUG_DOMAIN_VERIFICATION) {
13127                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13128            }
13129        }
13130    }
13131
13132    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13133        final ComponentName cn  = filter.activity.getComponentName();
13134        final String packageName = cn.getPackageName();
13135
13136        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13137                packageName);
13138        if (ivi == null) {
13139            return true;
13140        }
13141        int status = ivi.getStatus();
13142        switch (status) {
13143            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13144            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13145                return true;
13146
13147            default:
13148                // Nothing to do
13149                return false;
13150        }
13151    }
13152
13153    private static boolean isMultiArch(ApplicationInfo info) {
13154        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13155    }
13156
13157    private static boolean isExternal(PackageParser.Package pkg) {
13158        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13159    }
13160
13161    private static boolean isExternal(PackageSetting ps) {
13162        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13163    }
13164
13165    private static boolean isEphemeral(PackageParser.Package pkg) {
13166        return pkg.applicationInfo.isEphemeralApp();
13167    }
13168
13169    private static boolean isEphemeral(PackageSetting ps) {
13170        return ps.pkg != null && isEphemeral(ps.pkg);
13171    }
13172
13173    private static boolean isSystemApp(PackageParser.Package pkg) {
13174        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13175    }
13176
13177    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13178        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13179    }
13180
13181    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13182        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13183    }
13184
13185    private static boolean isSystemApp(PackageSetting ps) {
13186        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13187    }
13188
13189    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13190        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13191    }
13192
13193    private int packageFlagsToInstallFlags(PackageSetting ps) {
13194        int installFlags = 0;
13195        if (isEphemeral(ps)) {
13196            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13197        }
13198        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13199            // This existing package was an external ASEC install when we have
13200            // the external flag without a UUID
13201            installFlags |= PackageManager.INSTALL_EXTERNAL;
13202        }
13203        if (ps.isForwardLocked()) {
13204            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13205        }
13206        return installFlags;
13207    }
13208
13209    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13210        if (isExternal(pkg)) {
13211            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13212                return StorageManager.UUID_PRIMARY_PHYSICAL;
13213            } else {
13214                return pkg.volumeUuid;
13215            }
13216        } else {
13217            return StorageManager.UUID_PRIVATE_INTERNAL;
13218        }
13219    }
13220
13221    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13222        if (isExternal(pkg)) {
13223            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13224                return mSettings.getExternalVersion();
13225            } else {
13226                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13227            }
13228        } else {
13229            return mSettings.getInternalVersion();
13230        }
13231    }
13232
13233    private void deleteTempPackageFiles() {
13234        final FilenameFilter filter = new FilenameFilter() {
13235            public boolean accept(File dir, String name) {
13236                return name.startsWith("vmdl") && name.endsWith(".tmp");
13237            }
13238        };
13239        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13240            file.delete();
13241        }
13242    }
13243
13244    @Override
13245    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13246            int flags) {
13247        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13248                flags);
13249    }
13250
13251    @Override
13252    public void deletePackage(final String packageName,
13253            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13254        mContext.enforceCallingOrSelfPermission(
13255                android.Manifest.permission.DELETE_PACKAGES, null);
13256        Preconditions.checkNotNull(packageName);
13257        Preconditions.checkNotNull(observer);
13258        final int uid = Binder.getCallingUid();
13259        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13260        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13261        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13262            mContext.enforceCallingOrSelfPermission(
13263                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13264                    "deletePackage for user " + userId);
13265        }
13266
13267        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13268            try {
13269                observer.onPackageDeleted(packageName,
13270                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13271            } catch (RemoteException re) {
13272            }
13273            return;
13274        }
13275
13276        for (int currentUserId : users) {
13277            if (getBlockUninstallForUser(packageName, currentUserId)) {
13278                try {
13279                    observer.onPackageDeleted(packageName,
13280                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13281                } catch (RemoteException re) {
13282                }
13283                return;
13284            }
13285        }
13286
13287        if (DEBUG_REMOVE) {
13288            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13289        }
13290        // Queue up an async operation since the package deletion may take a little while.
13291        mHandler.post(new Runnable() {
13292            public void run() {
13293                mHandler.removeCallbacks(this);
13294                final int returnCode = deletePackageX(packageName, userId, flags);
13295                try {
13296                    observer.onPackageDeleted(packageName, returnCode, null);
13297                } catch (RemoteException e) {
13298                    Log.i(TAG, "Observer no longer exists.");
13299                } //end catch
13300            } //end run
13301        });
13302    }
13303
13304    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13305        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13306                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13307        try {
13308            if (dpm != null) {
13309                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13310                        /* callingUserOnly =*/ false);
13311                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13312                        : deviceOwnerComponentName.getPackageName();
13313                // Does the package contains the device owner?
13314                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13315                // this check is probably not needed, since DO should be registered as a device
13316                // admin on some user too. (Original bug for this: b/17657954)
13317                if (packageName.equals(deviceOwnerPackageName)) {
13318                    return true;
13319                }
13320                // Does it contain a device admin for any user?
13321                int[] users;
13322                if (userId == UserHandle.USER_ALL) {
13323                    users = sUserManager.getUserIds();
13324                } else {
13325                    users = new int[]{userId};
13326                }
13327                for (int i = 0; i < users.length; ++i) {
13328                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13329                        return true;
13330                    }
13331                }
13332            }
13333        } catch (RemoteException e) {
13334        }
13335        return false;
13336    }
13337
13338    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13339        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13340    }
13341
13342    /**
13343     *  This method is an internal method that could be get invoked either
13344     *  to delete an installed package or to clean up a failed installation.
13345     *  After deleting an installed package, a broadcast is sent to notify any
13346     *  listeners that the package has been installed. For cleaning up a failed
13347     *  installation, the broadcast is not necessary since the package's
13348     *  installation wouldn't have sent the initial broadcast either
13349     *  The key steps in deleting a package are
13350     *  deleting the package information in internal structures like mPackages,
13351     *  deleting the packages base directories through installd
13352     *  updating mSettings to reflect current status
13353     *  persisting settings for later use
13354     *  sending a broadcast if necessary
13355     */
13356    private int deletePackageX(String packageName, int userId, int flags) {
13357        final PackageRemovedInfo info = new PackageRemovedInfo();
13358        final boolean res;
13359
13360        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13361                ? UserHandle.ALL : new UserHandle(userId);
13362
13363        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13364            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13365            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13366        }
13367
13368        boolean removedForAllUsers = false;
13369        boolean systemUpdate = false;
13370
13371        PackageParser.Package uninstalledPkg;
13372
13373        // for the uninstall-updates case and restricted profiles, remember the per-
13374        // userhandle installed state
13375        int[] allUsers;
13376        boolean[] perUserInstalled;
13377        synchronized (mPackages) {
13378            uninstalledPkg = mPackages.get(packageName);
13379            PackageSetting ps = mSettings.mPackages.get(packageName);
13380            allUsers = sUserManager.getUserIds();
13381            perUserInstalled = new boolean[allUsers.length];
13382            for (int i = 0; i < allUsers.length; i++) {
13383                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13384            }
13385        }
13386
13387        synchronized (mInstallLock) {
13388            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13389            res = deletePackageLI(packageName, removeForUser,
13390                    true, allUsers, perUserInstalled,
13391                    flags | REMOVE_CHATTY, info, true);
13392            systemUpdate = info.isRemovedPackageSystemUpdate;
13393            synchronized (mPackages) {
13394                if (res) {
13395                    if (!systemUpdate && mPackages.get(packageName) == null) {
13396                        removedForAllUsers = true;
13397                    }
13398                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13399                }
13400            }
13401            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13402                    + " removedForAllUsers=" + removedForAllUsers);
13403        }
13404
13405        if (res) {
13406            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13407
13408            // If the removed package was a system update, the old system package
13409            // was re-enabled; we need to broadcast this information
13410            if (systemUpdate) {
13411                Bundle extras = new Bundle(1);
13412                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13413                        ? info.removedAppId : info.uid);
13414                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13415
13416                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13417                        extras, 0, null, null, null);
13418                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13419                        extras, 0, null, null, null);
13420                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13421                        null, 0, packageName, null, null);
13422            }
13423        }
13424        // Force a gc here.
13425        Runtime.getRuntime().gc();
13426        // Delete the resources here after sending the broadcast to let
13427        // other processes clean up before deleting resources.
13428        if (info.args != null) {
13429            synchronized (mInstallLock) {
13430                info.args.doPostDeleteLI(true);
13431            }
13432        }
13433
13434        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13435    }
13436
13437    class PackageRemovedInfo {
13438        String removedPackage;
13439        int uid = -1;
13440        int removedAppId = -1;
13441        int[] removedUsers = null;
13442        boolean isRemovedPackageSystemUpdate = false;
13443        // Clean up resources deleted packages.
13444        InstallArgs args = null;
13445
13446        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13447            Bundle extras = new Bundle(1);
13448            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13449            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13450            if (replacing) {
13451                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13452            }
13453            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13454            if (removedPackage != null) {
13455                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13456                        extras, 0, null, null, removedUsers);
13457                if (fullRemove && !replacing) {
13458                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13459                            extras, 0, null, null, removedUsers);
13460                }
13461            }
13462            if (removedAppId >= 0) {
13463                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13464                        removedUsers);
13465            }
13466        }
13467    }
13468
13469    /*
13470     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13471     * flag is not set, the data directory is removed as well.
13472     * make sure this flag is set for partially installed apps. If not its meaningless to
13473     * delete a partially installed application.
13474     */
13475    private void removePackageDataLI(PackageSetting ps,
13476            int[] allUserHandles, boolean[] perUserInstalled,
13477            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13478        String packageName = ps.name;
13479        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13480        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13481        // Retrieve object to delete permissions for shared user later on
13482        final PackageSetting deletedPs;
13483        // reader
13484        synchronized (mPackages) {
13485            deletedPs = mSettings.mPackages.get(packageName);
13486            if (outInfo != null) {
13487                outInfo.removedPackage = packageName;
13488                outInfo.removedUsers = deletedPs != null
13489                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13490                        : null;
13491            }
13492        }
13493        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13494            removeDataDirsLI(ps.volumeUuid, packageName);
13495            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13496        }
13497        // writer
13498        synchronized (mPackages) {
13499            if (deletedPs != null) {
13500                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13501                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13502                    clearDefaultBrowserIfNeeded(packageName);
13503                    if (outInfo != null) {
13504                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13505                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13506                    }
13507                    updatePermissionsLPw(deletedPs.name, null, 0);
13508                    if (deletedPs.sharedUser != null) {
13509                        // Remove permissions associated with package. Since runtime
13510                        // permissions are per user we have to kill the removed package
13511                        // or packages running under the shared user of the removed
13512                        // package if revoking the permissions requested only by the removed
13513                        // package is successful and this causes a change in gids.
13514                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13515                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13516                                    userId);
13517                            if (userIdToKill == UserHandle.USER_ALL
13518                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13519                                // If gids changed for this user, kill all affected packages.
13520                                mHandler.post(new Runnable() {
13521                                    @Override
13522                                    public void run() {
13523                                        // This has to happen with no lock held.
13524                                        killApplication(deletedPs.name, deletedPs.appId,
13525                                                KILL_APP_REASON_GIDS_CHANGED);
13526                                    }
13527                                });
13528                                break;
13529                            }
13530                        }
13531                    }
13532                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13533                }
13534                // make sure to preserve per-user disabled state if this removal was just
13535                // a downgrade of a system app to the factory package
13536                if (allUserHandles != null && perUserInstalled != null) {
13537                    if (DEBUG_REMOVE) {
13538                        Slog.d(TAG, "Propagating install state across downgrade");
13539                    }
13540                    for (int i = 0; i < allUserHandles.length; i++) {
13541                        if (DEBUG_REMOVE) {
13542                            Slog.d(TAG, "    user " + allUserHandles[i]
13543                                    + " => " + perUserInstalled[i]);
13544                        }
13545                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13546                    }
13547                }
13548            }
13549            // can downgrade to reader
13550            if (writeSettings) {
13551                // Save settings now
13552                mSettings.writeLPr();
13553            }
13554        }
13555        if (outInfo != null) {
13556            // A user ID was deleted here. Go through all users and remove it
13557            // from KeyStore.
13558            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13559        }
13560    }
13561
13562    static boolean locationIsPrivileged(File path) {
13563        try {
13564            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13565                    .getCanonicalPath();
13566            return path.getCanonicalPath().startsWith(privilegedAppDir);
13567        } catch (IOException e) {
13568            Slog.e(TAG, "Unable to access code path " + path);
13569        }
13570        return false;
13571    }
13572
13573    /*
13574     * Tries to delete system package.
13575     */
13576    private boolean deleteSystemPackageLI(PackageSetting newPs,
13577            int[] allUserHandles, boolean[] perUserInstalled,
13578            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13579        final boolean applyUserRestrictions
13580                = (allUserHandles != null) && (perUserInstalled != null);
13581        PackageSetting disabledPs = null;
13582        // Confirm if the system package has been updated
13583        // An updated system app can be deleted. This will also have to restore
13584        // the system pkg from system partition
13585        // reader
13586        synchronized (mPackages) {
13587            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13588        }
13589        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13590                + " disabledPs=" + disabledPs);
13591        if (disabledPs == null) {
13592            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13593            return false;
13594        } else if (DEBUG_REMOVE) {
13595            Slog.d(TAG, "Deleting system pkg from data partition");
13596        }
13597        if (DEBUG_REMOVE) {
13598            if (applyUserRestrictions) {
13599                Slog.d(TAG, "Remembering install states:");
13600                for (int i = 0; i < allUserHandles.length; i++) {
13601                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13602                }
13603            }
13604        }
13605        // Delete the updated package
13606        outInfo.isRemovedPackageSystemUpdate = true;
13607        if (disabledPs.versionCode < newPs.versionCode) {
13608            // Delete data for downgrades
13609            flags &= ~PackageManager.DELETE_KEEP_DATA;
13610        } else {
13611            // Preserve data by setting flag
13612            flags |= PackageManager.DELETE_KEEP_DATA;
13613        }
13614        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13615                allUserHandles, perUserInstalled, outInfo, writeSettings);
13616        if (!ret) {
13617            return false;
13618        }
13619        // writer
13620        synchronized (mPackages) {
13621            // Reinstate the old system package
13622            mSettings.enableSystemPackageLPw(newPs.name);
13623            // Remove any native libraries from the upgraded package.
13624            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13625        }
13626        // Install the system package
13627        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13628        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13629        if (locationIsPrivileged(disabledPs.codePath)) {
13630            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13631        }
13632
13633        final PackageParser.Package newPkg;
13634        try {
13635            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13636        } catch (PackageManagerException e) {
13637            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13638            return false;
13639        }
13640
13641        // writer
13642        synchronized (mPackages) {
13643            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13644
13645            // Propagate the permissions state as we do not want to drop on the floor
13646            // runtime permissions. The update permissions method below will take
13647            // care of removing obsolete permissions and grant install permissions.
13648            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13649            updatePermissionsLPw(newPkg.packageName, newPkg,
13650                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13651
13652            if (applyUserRestrictions) {
13653                if (DEBUG_REMOVE) {
13654                    Slog.d(TAG, "Propagating install state across reinstall");
13655                }
13656                for (int i = 0; i < allUserHandles.length; i++) {
13657                    if (DEBUG_REMOVE) {
13658                        Slog.d(TAG, "    user " + allUserHandles[i]
13659                                + " => " + perUserInstalled[i]);
13660                    }
13661                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13662
13663                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13664                }
13665                // Regardless of writeSettings we need to ensure that this restriction
13666                // state propagation is persisted
13667                mSettings.writeAllUsersPackageRestrictionsLPr();
13668            }
13669            // can downgrade to reader here
13670            if (writeSettings) {
13671                mSettings.writeLPr();
13672            }
13673        }
13674        return true;
13675    }
13676
13677    private boolean deleteInstalledPackageLI(PackageSetting ps,
13678            boolean deleteCodeAndResources, int flags,
13679            int[] allUserHandles, boolean[] perUserInstalled,
13680            PackageRemovedInfo outInfo, boolean writeSettings) {
13681        if (outInfo != null) {
13682            outInfo.uid = ps.appId;
13683        }
13684
13685        // Delete package data from internal structures and also remove data if flag is set
13686        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13687
13688        // Delete application code and resources
13689        if (deleteCodeAndResources && (outInfo != null)) {
13690            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13691                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13692            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13693        }
13694        return true;
13695    }
13696
13697    @Override
13698    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13699            int userId) {
13700        mContext.enforceCallingOrSelfPermission(
13701                android.Manifest.permission.DELETE_PACKAGES, null);
13702        synchronized (mPackages) {
13703            PackageSetting ps = mSettings.mPackages.get(packageName);
13704            if (ps == null) {
13705                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13706                return false;
13707            }
13708            if (!ps.getInstalled(userId)) {
13709                // Can't block uninstall for an app that is not installed or enabled.
13710                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13711                return false;
13712            }
13713            ps.setBlockUninstall(blockUninstall, userId);
13714            mSettings.writePackageRestrictionsLPr(userId);
13715        }
13716        return true;
13717    }
13718
13719    @Override
13720    public boolean getBlockUninstallForUser(String packageName, int userId) {
13721        synchronized (mPackages) {
13722            PackageSetting ps = mSettings.mPackages.get(packageName);
13723            if (ps == null) {
13724                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13725                return false;
13726            }
13727            return ps.getBlockUninstall(userId);
13728        }
13729    }
13730
13731    @Override
13732    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13733        int callingUid = Binder.getCallingUid();
13734        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13735            throw new SecurityException(
13736                    "setRequiredForSystemUser can only be run by the system or root");
13737        }
13738        synchronized (mPackages) {
13739            PackageSetting ps = mSettings.mPackages.get(packageName);
13740            if (ps == null) {
13741                Log.w(TAG, "Package doesn't exist: " + packageName);
13742                return false;
13743            }
13744            if (systemUserApp) {
13745                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13746            } else {
13747                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13748            }
13749            mSettings.writeLPr();
13750        }
13751        return true;
13752    }
13753
13754    /*
13755     * This method handles package deletion in general
13756     */
13757    private boolean deletePackageLI(String packageName, UserHandle user,
13758            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13759            int flags, PackageRemovedInfo outInfo,
13760            boolean writeSettings) {
13761        if (packageName == null) {
13762            Slog.w(TAG, "Attempt to delete null packageName.");
13763            return false;
13764        }
13765        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13766        PackageSetting ps;
13767        boolean dataOnly = false;
13768        int removeUser = -1;
13769        int appId = -1;
13770        synchronized (mPackages) {
13771            ps = mSettings.mPackages.get(packageName);
13772            if (ps == null) {
13773                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13774                return false;
13775            }
13776            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13777                    && user.getIdentifier() != UserHandle.USER_ALL) {
13778                // The caller is asking that the package only be deleted for a single
13779                // user.  To do this, we just mark its uninstalled state and delete
13780                // its data.  If this is a system app, we only allow this to happen if
13781                // they have set the special DELETE_SYSTEM_APP which requests different
13782                // semantics than normal for uninstalling system apps.
13783                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13784                final int userId = user.getIdentifier();
13785                ps.setUserState(userId,
13786                        COMPONENT_ENABLED_STATE_DEFAULT,
13787                        false, //installed
13788                        true,  //stopped
13789                        true,  //notLaunched
13790                        false, //hidden
13791                        false, //suspended
13792                        null, null, null,
13793                        false, // blockUninstall
13794                        ps.readUserState(userId).domainVerificationStatus, 0);
13795                if (!isSystemApp(ps)) {
13796                    // Do not uninstall the APK if an app should be cached
13797                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13798                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13799                        // Other user still have this package installed, so all
13800                        // we need to do is clear this user's data and save that
13801                        // it is uninstalled.
13802                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13803                        removeUser = user.getIdentifier();
13804                        appId = ps.appId;
13805                        scheduleWritePackageRestrictionsLocked(removeUser);
13806                    } else {
13807                        // We need to set it back to 'installed' so the uninstall
13808                        // broadcasts will be sent correctly.
13809                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13810                        ps.setInstalled(true, user.getIdentifier());
13811                    }
13812                } else {
13813                    // This is a system app, so we assume that the
13814                    // other users still have this package installed, so all
13815                    // we need to do is clear this user's data and save that
13816                    // it is uninstalled.
13817                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13818                    removeUser = user.getIdentifier();
13819                    appId = ps.appId;
13820                    scheduleWritePackageRestrictionsLocked(removeUser);
13821                }
13822            }
13823        }
13824
13825        if (removeUser >= 0) {
13826            // From above, we determined that we are deleting this only
13827            // for a single user.  Continue the work here.
13828            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13829            if (outInfo != null) {
13830                outInfo.removedPackage = packageName;
13831                outInfo.removedAppId = appId;
13832                outInfo.removedUsers = new int[] {removeUser};
13833            }
13834            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13835            removeKeystoreDataIfNeeded(removeUser, appId);
13836            schedulePackageCleaning(packageName, removeUser, false);
13837            synchronized (mPackages) {
13838                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13839                    scheduleWritePackageRestrictionsLocked(removeUser);
13840                }
13841                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13842            }
13843            return true;
13844        }
13845
13846        if (dataOnly) {
13847            // Delete application data first
13848            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13849            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13850            return true;
13851        }
13852
13853        boolean ret = false;
13854        if (isSystemApp(ps)) {
13855            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13856            // When an updated system application is deleted we delete the existing resources as well and
13857            // fall back to existing code in system partition
13858            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13859                    flags, outInfo, writeSettings);
13860        } else {
13861            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13862            // Kill application pre-emptively especially for apps on sd.
13863            killApplication(packageName, ps.appId, "uninstall pkg");
13864            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13865                    allUserHandles, perUserInstalled,
13866                    outInfo, writeSettings);
13867        }
13868
13869        return ret;
13870    }
13871
13872    private final static class ClearStorageConnection implements ServiceConnection {
13873        IMediaContainerService mContainerService;
13874
13875        @Override
13876        public void onServiceConnected(ComponentName name, IBinder service) {
13877            synchronized (this) {
13878                mContainerService = IMediaContainerService.Stub.asInterface(service);
13879                notifyAll();
13880            }
13881        }
13882
13883        @Override
13884        public void onServiceDisconnected(ComponentName name) {
13885        }
13886    }
13887
13888    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13889        final boolean mounted;
13890        if (Environment.isExternalStorageEmulated()) {
13891            mounted = true;
13892        } else {
13893            final String status = Environment.getExternalStorageState();
13894
13895            mounted = status.equals(Environment.MEDIA_MOUNTED)
13896                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13897        }
13898
13899        if (!mounted) {
13900            return;
13901        }
13902
13903        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13904        int[] users;
13905        if (userId == UserHandle.USER_ALL) {
13906            users = sUserManager.getUserIds();
13907        } else {
13908            users = new int[] { userId };
13909        }
13910        final ClearStorageConnection conn = new ClearStorageConnection();
13911        if (mContext.bindServiceAsUser(
13912                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13913            try {
13914                for (int curUser : users) {
13915                    long timeout = SystemClock.uptimeMillis() + 5000;
13916                    synchronized (conn) {
13917                        long now = SystemClock.uptimeMillis();
13918                        while (conn.mContainerService == null && now < timeout) {
13919                            try {
13920                                conn.wait(timeout - now);
13921                            } catch (InterruptedException e) {
13922                            }
13923                        }
13924                    }
13925                    if (conn.mContainerService == null) {
13926                        return;
13927                    }
13928
13929                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13930                    clearDirectory(conn.mContainerService,
13931                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13932                    if (allData) {
13933                        clearDirectory(conn.mContainerService,
13934                                userEnv.buildExternalStorageAppDataDirs(packageName));
13935                        clearDirectory(conn.mContainerService,
13936                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13937                    }
13938                }
13939            } finally {
13940                mContext.unbindService(conn);
13941            }
13942        }
13943    }
13944
13945    @Override
13946    public void clearApplicationUserData(final String packageName,
13947            final IPackageDataObserver observer, final int userId) {
13948        mContext.enforceCallingOrSelfPermission(
13949                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13950        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13951        // Queue up an async operation since the package deletion may take a little while.
13952        mHandler.post(new Runnable() {
13953            public void run() {
13954                mHandler.removeCallbacks(this);
13955                final boolean succeeded;
13956                synchronized (mInstallLock) {
13957                    succeeded = clearApplicationUserDataLI(packageName, userId);
13958                }
13959                clearExternalStorageDataSync(packageName, userId, true);
13960                if (succeeded) {
13961                    // invoke DeviceStorageMonitor's update method to clear any notifications
13962                    DeviceStorageMonitorInternal
13963                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13964                    if (dsm != null) {
13965                        dsm.checkMemory();
13966                    }
13967                }
13968                if(observer != null) {
13969                    try {
13970                        observer.onRemoveCompleted(packageName, succeeded);
13971                    } catch (RemoteException e) {
13972                        Log.i(TAG, "Observer no longer exists.");
13973                    }
13974                } //end if observer
13975            } //end run
13976        });
13977    }
13978
13979    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13980        if (packageName == null) {
13981            Slog.w(TAG, "Attempt to delete null packageName.");
13982            return false;
13983        }
13984
13985        // Try finding details about the requested package
13986        PackageParser.Package pkg;
13987        synchronized (mPackages) {
13988            pkg = mPackages.get(packageName);
13989            if (pkg == null) {
13990                final PackageSetting ps = mSettings.mPackages.get(packageName);
13991                if (ps != null) {
13992                    pkg = ps.pkg;
13993                }
13994            }
13995
13996            if (pkg == null) {
13997                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13998                return false;
13999            }
14000
14001            PackageSetting ps = (PackageSetting) pkg.mExtras;
14002            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14003        }
14004
14005        // Always delete data directories for package, even if we found no other
14006        // record of app. This helps users recover from UID mismatches without
14007        // resorting to a full data wipe.
14008        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14009        if (retCode < 0) {
14010            Slog.w(TAG, "Couldn't remove cache files for package " + packageName);
14011            return false;
14012        }
14013
14014        final int appId = pkg.applicationInfo.uid;
14015        removeKeystoreDataIfNeeded(userId, appId);
14016
14017        // Create a native library symlink only if we have native libraries
14018        // and if the native libraries are 32 bit libraries. We do not provide
14019        // this symlink for 64 bit libraries.
14020        if (pkg.applicationInfo.primaryCpuAbi != null &&
14021                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14022            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14023            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14024                    nativeLibPath, userId) < 0) {
14025                Slog.w(TAG, "Failed linking native library dir");
14026                return false;
14027            }
14028        }
14029
14030        return true;
14031    }
14032
14033    /**
14034     * Reverts user permission state changes (permissions and flags) in
14035     * all packages for a given user.
14036     *
14037     * @param userId The device user for which to do a reset.
14038     */
14039    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14040        final int packageCount = mPackages.size();
14041        for (int i = 0; i < packageCount; i++) {
14042            PackageParser.Package pkg = mPackages.valueAt(i);
14043            PackageSetting ps = (PackageSetting) pkg.mExtras;
14044            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14045        }
14046    }
14047
14048    /**
14049     * Reverts user permission state changes (permissions and flags).
14050     *
14051     * @param ps The package for which to reset.
14052     * @param userId The device user for which to do a reset.
14053     */
14054    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14055            final PackageSetting ps, final int userId) {
14056        if (ps.pkg == null) {
14057            return;
14058        }
14059
14060        // These are flags that can change base on user actions.
14061        final int userSettableMask = FLAG_PERMISSION_USER_SET
14062                | FLAG_PERMISSION_USER_FIXED
14063                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14064                | FLAG_PERMISSION_REVIEW_REQUIRED;
14065
14066        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14067                | FLAG_PERMISSION_POLICY_FIXED;
14068
14069        boolean writeInstallPermissions = false;
14070        boolean writeRuntimePermissions = false;
14071
14072        final int permissionCount = ps.pkg.requestedPermissions.size();
14073        for (int i = 0; i < permissionCount; i++) {
14074            String permission = ps.pkg.requestedPermissions.get(i);
14075
14076            BasePermission bp = mSettings.mPermissions.get(permission);
14077            if (bp == null) {
14078                continue;
14079            }
14080
14081            // If shared user we just reset the state to which only this app contributed.
14082            if (ps.sharedUser != null) {
14083                boolean used = false;
14084                final int packageCount = ps.sharedUser.packages.size();
14085                for (int j = 0; j < packageCount; j++) {
14086                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14087                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14088                            && pkg.pkg.requestedPermissions.contains(permission)) {
14089                        used = true;
14090                        break;
14091                    }
14092                }
14093                if (used) {
14094                    continue;
14095                }
14096            }
14097
14098            PermissionsState permissionsState = ps.getPermissionsState();
14099
14100            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14101
14102            // Always clear the user settable flags.
14103            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14104                    bp.name) != null;
14105            // If permission review is enabled and this is a legacy app, mark the
14106            // permission as requiring a review as this is the initial state.
14107            int flags = 0;
14108            if (Build.PERMISSIONS_REVIEW_REQUIRED
14109                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14110                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14111            }
14112            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14113                if (hasInstallState) {
14114                    writeInstallPermissions = true;
14115                } else {
14116                    writeRuntimePermissions = true;
14117                }
14118            }
14119
14120            // Below is only runtime permission handling.
14121            if (!bp.isRuntime()) {
14122                continue;
14123            }
14124
14125            // Never clobber system or policy.
14126            if ((oldFlags & policyOrSystemFlags) != 0) {
14127                continue;
14128            }
14129
14130            // If this permission was granted by default, make sure it is.
14131            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14132                if (permissionsState.grantRuntimePermission(bp, userId)
14133                        != PERMISSION_OPERATION_FAILURE) {
14134                    writeRuntimePermissions = true;
14135                }
14136            // If permission review is enabled the permissions for a legacy apps
14137            // are represented as constantly granted runtime ones, so don't revoke.
14138            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14139                // Otherwise, reset the permission.
14140                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14141                switch (revokeResult) {
14142                    case PERMISSION_OPERATION_SUCCESS: {
14143                        writeRuntimePermissions = true;
14144                    } break;
14145
14146                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14147                        writeRuntimePermissions = true;
14148                        final int appId = ps.appId;
14149                        mHandler.post(new Runnable() {
14150                            @Override
14151                            public void run() {
14152                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14153                            }
14154                        });
14155                    } break;
14156                }
14157            }
14158        }
14159
14160        // Synchronously write as we are taking permissions away.
14161        if (writeRuntimePermissions) {
14162            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14163        }
14164
14165        // Synchronously write as we are taking permissions away.
14166        if (writeInstallPermissions) {
14167            mSettings.writeLPr();
14168        }
14169    }
14170
14171    /**
14172     * Remove entries from the keystore daemon. Will only remove it if the
14173     * {@code appId} is valid.
14174     */
14175    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14176        if (appId < 0) {
14177            return;
14178        }
14179
14180        final KeyStore keyStore = KeyStore.getInstance();
14181        if (keyStore != null) {
14182            if (userId == UserHandle.USER_ALL) {
14183                for (final int individual : sUserManager.getUserIds()) {
14184                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14185                }
14186            } else {
14187                keyStore.clearUid(UserHandle.getUid(userId, appId));
14188            }
14189        } else {
14190            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14191        }
14192    }
14193
14194    @Override
14195    public void deleteApplicationCacheFiles(final String packageName,
14196            final IPackageDataObserver observer) {
14197        mContext.enforceCallingOrSelfPermission(
14198                android.Manifest.permission.DELETE_CACHE_FILES, null);
14199        // Queue up an async operation since the package deletion may take a little while.
14200        final int userId = UserHandle.getCallingUserId();
14201        mHandler.post(new Runnable() {
14202            public void run() {
14203                mHandler.removeCallbacks(this);
14204                final boolean succeded;
14205                synchronized (mInstallLock) {
14206                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14207                }
14208                clearExternalStorageDataSync(packageName, userId, false);
14209                if (observer != null) {
14210                    try {
14211                        observer.onRemoveCompleted(packageName, succeded);
14212                    } catch (RemoteException e) {
14213                        Log.i(TAG, "Observer no longer exists.");
14214                    }
14215                } //end if observer
14216            } //end run
14217        });
14218    }
14219
14220    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14221        if (packageName == null) {
14222            Slog.w(TAG, "Attempt to delete null packageName.");
14223            return false;
14224        }
14225        PackageParser.Package p;
14226        synchronized (mPackages) {
14227            p = mPackages.get(packageName);
14228        }
14229        if (p == null) {
14230            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14231            return false;
14232        }
14233        final ApplicationInfo applicationInfo = p.applicationInfo;
14234        if (applicationInfo == null) {
14235            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14236            return false;
14237        }
14238        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14239        if (retCode < 0) {
14240            Slog.w(TAG, "Couldn't remove cache files for package "
14241                       + packageName + " u" + userId);
14242            return false;
14243        }
14244        return true;
14245    }
14246
14247    @Override
14248    public void getPackageSizeInfo(final String packageName, int userHandle,
14249            final IPackageStatsObserver observer) {
14250        mContext.enforceCallingOrSelfPermission(
14251                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14252        if (packageName == null) {
14253            throw new IllegalArgumentException("Attempt to get size of null packageName");
14254        }
14255
14256        PackageStats stats = new PackageStats(packageName, userHandle);
14257
14258        /*
14259         * Queue up an async operation since the package measurement may take a
14260         * little while.
14261         */
14262        Message msg = mHandler.obtainMessage(INIT_COPY);
14263        msg.obj = new MeasureParams(stats, observer);
14264        mHandler.sendMessage(msg);
14265    }
14266
14267    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14268            PackageStats pStats) {
14269        if (packageName == null) {
14270            Slog.w(TAG, "Attempt to get size of null packageName.");
14271            return false;
14272        }
14273        PackageParser.Package p;
14274        boolean dataOnly = false;
14275        String libDirRoot = null;
14276        String asecPath = null;
14277        PackageSetting ps = null;
14278        synchronized (mPackages) {
14279            p = mPackages.get(packageName);
14280            ps = mSettings.mPackages.get(packageName);
14281            if(p == null) {
14282                dataOnly = true;
14283                if((ps == null) || (ps.pkg == null)) {
14284                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14285                    return false;
14286                }
14287                p = ps.pkg;
14288            }
14289            if (ps != null) {
14290                libDirRoot = ps.legacyNativeLibraryPathString;
14291            }
14292            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14293                final long token = Binder.clearCallingIdentity();
14294                try {
14295                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14296                    if (secureContainerId != null) {
14297                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14298                    }
14299                } finally {
14300                    Binder.restoreCallingIdentity(token);
14301                }
14302            }
14303        }
14304        String publicSrcDir = null;
14305        if(!dataOnly) {
14306            final ApplicationInfo applicationInfo = p.applicationInfo;
14307            if (applicationInfo == null) {
14308                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14309                return false;
14310            }
14311            if (p.isForwardLocked()) {
14312                publicSrcDir = applicationInfo.getBaseResourcePath();
14313            }
14314        }
14315        // TODO: extend to measure size of split APKs
14316        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14317        // not just the first level.
14318        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14319        // just the primary.
14320        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14321
14322        String apkPath;
14323        File packageDir = new File(p.codePath);
14324
14325        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14326            apkPath = packageDir.getAbsolutePath();
14327            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14328            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14329                libDirRoot = null;
14330            }
14331        } else {
14332            apkPath = p.baseCodePath;
14333        }
14334
14335        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14336                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14337        if (res < 0) {
14338            return false;
14339        }
14340
14341        // Fix-up for forward-locked applications in ASEC containers.
14342        if (!isExternal(p)) {
14343            pStats.codeSize += pStats.externalCodeSize;
14344            pStats.externalCodeSize = 0L;
14345        }
14346
14347        return true;
14348    }
14349
14350
14351    @Override
14352    public void addPackageToPreferred(String packageName) {
14353        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14354    }
14355
14356    @Override
14357    public void removePackageFromPreferred(String packageName) {
14358        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14359    }
14360
14361    @Override
14362    public List<PackageInfo> getPreferredPackages(int flags) {
14363        return new ArrayList<PackageInfo>();
14364    }
14365
14366    private int getUidTargetSdkVersionLockedLPr(int uid) {
14367        Object obj = mSettings.getUserIdLPr(uid);
14368        if (obj instanceof SharedUserSetting) {
14369            final SharedUserSetting sus = (SharedUserSetting) obj;
14370            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14371            final Iterator<PackageSetting> it = sus.packages.iterator();
14372            while (it.hasNext()) {
14373                final PackageSetting ps = it.next();
14374                if (ps.pkg != null) {
14375                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14376                    if (v < vers) vers = v;
14377                }
14378            }
14379            return vers;
14380        } else if (obj instanceof PackageSetting) {
14381            final PackageSetting ps = (PackageSetting) obj;
14382            if (ps.pkg != null) {
14383                return ps.pkg.applicationInfo.targetSdkVersion;
14384            }
14385        }
14386        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14387    }
14388
14389    @Override
14390    public void addPreferredActivity(IntentFilter filter, int match,
14391            ComponentName[] set, ComponentName activity, int userId) {
14392        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14393                "Adding preferred");
14394    }
14395
14396    private void addPreferredActivityInternal(IntentFilter filter, int match,
14397            ComponentName[] set, ComponentName activity, boolean always, int userId,
14398            String opname) {
14399        // writer
14400        int callingUid = Binder.getCallingUid();
14401        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14402        if (filter.countActions() == 0) {
14403            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14404            return;
14405        }
14406        synchronized (mPackages) {
14407            if (mContext.checkCallingOrSelfPermission(
14408                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14409                    != PackageManager.PERMISSION_GRANTED) {
14410                if (getUidTargetSdkVersionLockedLPr(callingUid)
14411                        < Build.VERSION_CODES.FROYO) {
14412                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14413                            + callingUid);
14414                    return;
14415                }
14416                mContext.enforceCallingOrSelfPermission(
14417                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14418            }
14419
14420            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14421            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14422                    + userId + ":");
14423            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14424            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14425            scheduleWritePackageRestrictionsLocked(userId);
14426        }
14427    }
14428
14429    @Override
14430    public void replacePreferredActivity(IntentFilter filter, int match,
14431            ComponentName[] set, ComponentName activity, int userId) {
14432        if (filter.countActions() != 1) {
14433            throw new IllegalArgumentException(
14434                    "replacePreferredActivity expects filter to have only 1 action.");
14435        }
14436        if (filter.countDataAuthorities() != 0
14437                || filter.countDataPaths() != 0
14438                || filter.countDataSchemes() > 1
14439                || filter.countDataTypes() != 0) {
14440            throw new IllegalArgumentException(
14441                    "replacePreferredActivity expects filter to have no data authorities, " +
14442                    "paths, or types; and at most one scheme.");
14443        }
14444
14445        final int callingUid = Binder.getCallingUid();
14446        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14447        synchronized (mPackages) {
14448            if (mContext.checkCallingOrSelfPermission(
14449                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14450                    != PackageManager.PERMISSION_GRANTED) {
14451                if (getUidTargetSdkVersionLockedLPr(callingUid)
14452                        < Build.VERSION_CODES.FROYO) {
14453                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14454                            + Binder.getCallingUid());
14455                    return;
14456                }
14457                mContext.enforceCallingOrSelfPermission(
14458                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14459            }
14460
14461            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14462            if (pir != null) {
14463                // Get all of the existing entries that exactly match this filter.
14464                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14465                if (existing != null && existing.size() == 1) {
14466                    PreferredActivity cur = existing.get(0);
14467                    if (DEBUG_PREFERRED) {
14468                        Slog.i(TAG, "Checking replace of preferred:");
14469                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14470                        if (!cur.mPref.mAlways) {
14471                            Slog.i(TAG, "  -- CUR; not mAlways!");
14472                        } else {
14473                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14474                            Slog.i(TAG, "  -- CUR: mSet="
14475                                    + Arrays.toString(cur.mPref.mSetComponents));
14476                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14477                            Slog.i(TAG, "  -- NEW: mMatch="
14478                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14479                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14480                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14481                        }
14482                    }
14483                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14484                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14485                            && cur.mPref.sameSet(set)) {
14486                        // Setting the preferred activity to what it happens to be already
14487                        if (DEBUG_PREFERRED) {
14488                            Slog.i(TAG, "Replacing with same preferred activity "
14489                                    + cur.mPref.mShortComponent + " for user "
14490                                    + userId + ":");
14491                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14492                        }
14493                        return;
14494                    }
14495                }
14496
14497                if (existing != null) {
14498                    if (DEBUG_PREFERRED) {
14499                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14500                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14501                    }
14502                    for (int i = 0; i < existing.size(); i++) {
14503                        PreferredActivity pa = existing.get(i);
14504                        if (DEBUG_PREFERRED) {
14505                            Slog.i(TAG, "Removing existing preferred activity "
14506                                    + pa.mPref.mComponent + ":");
14507                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14508                        }
14509                        pir.removeFilter(pa);
14510                    }
14511                }
14512            }
14513            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14514                    "Replacing preferred");
14515        }
14516    }
14517
14518    @Override
14519    public void clearPackagePreferredActivities(String packageName) {
14520        final int uid = Binder.getCallingUid();
14521        // writer
14522        synchronized (mPackages) {
14523            PackageParser.Package pkg = mPackages.get(packageName);
14524            if (pkg == null || pkg.applicationInfo.uid != uid) {
14525                if (mContext.checkCallingOrSelfPermission(
14526                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14527                        != PackageManager.PERMISSION_GRANTED) {
14528                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14529                            < Build.VERSION_CODES.FROYO) {
14530                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14531                                + Binder.getCallingUid());
14532                        return;
14533                    }
14534                    mContext.enforceCallingOrSelfPermission(
14535                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14536                }
14537            }
14538
14539            int user = UserHandle.getCallingUserId();
14540            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14541                scheduleWritePackageRestrictionsLocked(user);
14542            }
14543        }
14544    }
14545
14546    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14547    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14548        ArrayList<PreferredActivity> removed = null;
14549        boolean changed = false;
14550        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14551            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14552            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14553            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14554                continue;
14555            }
14556            Iterator<PreferredActivity> it = pir.filterIterator();
14557            while (it.hasNext()) {
14558                PreferredActivity pa = it.next();
14559                // Mark entry for removal only if it matches the package name
14560                // and the entry is of type "always".
14561                if (packageName == null ||
14562                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14563                                && pa.mPref.mAlways)) {
14564                    if (removed == null) {
14565                        removed = new ArrayList<PreferredActivity>();
14566                    }
14567                    removed.add(pa);
14568                }
14569            }
14570            if (removed != null) {
14571                for (int j=0; j<removed.size(); j++) {
14572                    PreferredActivity pa = removed.get(j);
14573                    pir.removeFilter(pa);
14574                }
14575                changed = true;
14576            }
14577        }
14578        return changed;
14579    }
14580
14581    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14582    private void clearIntentFilterVerificationsLPw(int userId) {
14583        final int packageCount = mPackages.size();
14584        for (int i = 0; i < packageCount; i++) {
14585            PackageParser.Package pkg = mPackages.valueAt(i);
14586            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14587        }
14588    }
14589
14590    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14591    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14592        if (userId == UserHandle.USER_ALL) {
14593            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14594                    sUserManager.getUserIds())) {
14595                for (int oneUserId : sUserManager.getUserIds()) {
14596                    scheduleWritePackageRestrictionsLocked(oneUserId);
14597                }
14598            }
14599        } else {
14600            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14601                scheduleWritePackageRestrictionsLocked(userId);
14602            }
14603        }
14604    }
14605
14606    void clearDefaultBrowserIfNeeded(String packageName) {
14607        for (int oneUserId : sUserManager.getUserIds()) {
14608            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14609            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14610            if (packageName.equals(defaultBrowserPackageName)) {
14611                setDefaultBrowserPackageName(null, oneUserId);
14612            }
14613        }
14614    }
14615
14616    @Override
14617    public void resetApplicationPreferences(int userId) {
14618        mContext.enforceCallingOrSelfPermission(
14619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14620        // writer
14621        synchronized (mPackages) {
14622            final long identity = Binder.clearCallingIdentity();
14623            try {
14624                clearPackagePreferredActivitiesLPw(null, userId);
14625                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14626                // TODO: We have to reset the default SMS and Phone. This requires
14627                // significant refactoring to keep all default apps in the package
14628                // manager (cleaner but more work) or have the services provide
14629                // callbacks to the package manager to request a default app reset.
14630                applyFactoryDefaultBrowserLPw(userId);
14631                clearIntentFilterVerificationsLPw(userId);
14632                primeDomainVerificationsLPw(userId);
14633                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14634                scheduleWritePackageRestrictionsLocked(userId);
14635            } finally {
14636                Binder.restoreCallingIdentity(identity);
14637            }
14638        }
14639    }
14640
14641    @Override
14642    public int getPreferredActivities(List<IntentFilter> outFilters,
14643            List<ComponentName> outActivities, String packageName) {
14644
14645        int num = 0;
14646        final int userId = UserHandle.getCallingUserId();
14647        // reader
14648        synchronized (mPackages) {
14649            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14650            if (pir != null) {
14651                final Iterator<PreferredActivity> it = pir.filterIterator();
14652                while (it.hasNext()) {
14653                    final PreferredActivity pa = it.next();
14654                    if (packageName == null
14655                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14656                                    && pa.mPref.mAlways)) {
14657                        if (outFilters != null) {
14658                            outFilters.add(new IntentFilter(pa));
14659                        }
14660                        if (outActivities != null) {
14661                            outActivities.add(pa.mPref.mComponent);
14662                        }
14663                    }
14664                }
14665            }
14666        }
14667
14668        return num;
14669    }
14670
14671    @Override
14672    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14673            int userId) {
14674        int callingUid = Binder.getCallingUid();
14675        if (callingUid != Process.SYSTEM_UID) {
14676            throw new SecurityException(
14677                    "addPersistentPreferredActivity can only be run by the system");
14678        }
14679        if (filter.countActions() == 0) {
14680            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14681            return;
14682        }
14683        synchronized (mPackages) {
14684            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14685                    ":");
14686            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14687            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14688                    new PersistentPreferredActivity(filter, activity));
14689            scheduleWritePackageRestrictionsLocked(userId);
14690        }
14691    }
14692
14693    @Override
14694    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14695        int callingUid = Binder.getCallingUid();
14696        if (callingUid != Process.SYSTEM_UID) {
14697            throw new SecurityException(
14698                    "clearPackagePersistentPreferredActivities can only be run by the system");
14699        }
14700        ArrayList<PersistentPreferredActivity> removed = null;
14701        boolean changed = false;
14702        synchronized (mPackages) {
14703            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14704                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14705                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14706                        .valueAt(i);
14707                if (userId != thisUserId) {
14708                    continue;
14709                }
14710                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14711                while (it.hasNext()) {
14712                    PersistentPreferredActivity ppa = it.next();
14713                    // Mark entry for removal only if it matches the package name.
14714                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14715                        if (removed == null) {
14716                            removed = new ArrayList<PersistentPreferredActivity>();
14717                        }
14718                        removed.add(ppa);
14719                    }
14720                }
14721                if (removed != null) {
14722                    for (int j=0; j<removed.size(); j++) {
14723                        PersistentPreferredActivity ppa = removed.get(j);
14724                        ppir.removeFilter(ppa);
14725                    }
14726                    changed = true;
14727                }
14728            }
14729
14730            if (changed) {
14731                scheduleWritePackageRestrictionsLocked(userId);
14732            }
14733        }
14734    }
14735
14736    /**
14737     * Common machinery for picking apart a restored XML blob and passing
14738     * it to a caller-supplied functor to be applied to the running system.
14739     */
14740    private void restoreFromXml(XmlPullParser parser, int userId,
14741            String expectedStartTag, BlobXmlRestorer functor)
14742            throws IOException, XmlPullParserException {
14743        int type;
14744        while ((type = parser.next()) != XmlPullParser.START_TAG
14745                && type != XmlPullParser.END_DOCUMENT) {
14746        }
14747        if (type != XmlPullParser.START_TAG) {
14748            // oops didn't find a start tag?!
14749            if (DEBUG_BACKUP) {
14750                Slog.e(TAG, "Didn't find start tag during restore");
14751            }
14752            return;
14753        }
14754
14755        // this is supposed to be TAG_PREFERRED_BACKUP
14756        if (!expectedStartTag.equals(parser.getName())) {
14757            if (DEBUG_BACKUP) {
14758                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14759            }
14760            return;
14761        }
14762
14763        // skip interfering stuff, then we're aligned with the backing implementation
14764        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14765        functor.apply(parser, userId);
14766    }
14767
14768    private interface BlobXmlRestorer {
14769        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14770    }
14771
14772    /**
14773     * Non-Binder method, support for the backup/restore mechanism: write the
14774     * full set of preferred activities in its canonical XML format.  Returns the
14775     * XML output as a byte array, or null if there is none.
14776     */
14777    @Override
14778    public byte[] getPreferredActivityBackup(int userId) {
14779        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14780            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14781        }
14782
14783        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14784        try {
14785            final XmlSerializer serializer = new FastXmlSerializer();
14786            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14787            serializer.startDocument(null, true);
14788            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14789
14790            synchronized (mPackages) {
14791                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14792            }
14793
14794            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14795            serializer.endDocument();
14796            serializer.flush();
14797        } catch (Exception e) {
14798            if (DEBUG_BACKUP) {
14799                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14800            }
14801            return null;
14802        }
14803
14804        return dataStream.toByteArray();
14805    }
14806
14807    @Override
14808    public void restorePreferredActivities(byte[] backup, int userId) {
14809        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14810            throw new SecurityException("Only the system may call restorePreferredActivities()");
14811        }
14812
14813        try {
14814            final XmlPullParser parser = Xml.newPullParser();
14815            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14816            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14817                    new BlobXmlRestorer() {
14818                        @Override
14819                        public void apply(XmlPullParser parser, int userId)
14820                                throws XmlPullParserException, IOException {
14821                            synchronized (mPackages) {
14822                                mSettings.readPreferredActivitiesLPw(parser, userId);
14823                            }
14824                        }
14825                    } );
14826        } catch (Exception e) {
14827            if (DEBUG_BACKUP) {
14828                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14829            }
14830        }
14831    }
14832
14833    /**
14834     * Non-Binder method, support for the backup/restore mechanism: write the
14835     * default browser (etc) settings in its canonical XML format.  Returns the default
14836     * browser XML representation as a byte array, or null if there is none.
14837     */
14838    @Override
14839    public byte[] getDefaultAppsBackup(int userId) {
14840        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14841            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14842        }
14843
14844        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14845        try {
14846            final XmlSerializer serializer = new FastXmlSerializer();
14847            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14848            serializer.startDocument(null, true);
14849            serializer.startTag(null, TAG_DEFAULT_APPS);
14850
14851            synchronized (mPackages) {
14852                mSettings.writeDefaultAppsLPr(serializer, userId);
14853            }
14854
14855            serializer.endTag(null, TAG_DEFAULT_APPS);
14856            serializer.endDocument();
14857            serializer.flush();
14858        } catch (Exception e) {
14859            if (DEBUG_BACKUP) {
14860                Slog.e(TAG, "Unable to write default apps for backup", e);
14861            }
14862            return null;
14863        }
14864
14865        return dataStream.toByteArray();
14866    }
14867
14868    @Override
14869    public void restoreDefaultApps(byte[] backup, int userId) {
14870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14871            throw new SecurityException("Only the system may call restoreDefaultApps()");
14872        }
14873
14874        try {
14875            final XmlPullParser parser = Xml.newPullParser();
14876            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14877            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14878                    new BlobXmlRestorer() {
14879                        @Override
14880                        public void apply(XmlPullParser parser, int userId)
14881                                throws XmlPullParserException, IOException {
14882                            synchronized (mPackages) {
14883                                mSettings.readDefaultAppsLPw(parser, userId);
14884                            }
14885                        }
14886                    } );
14887        } catch (Exception e) {
14888            if (DEBUG_BACKUP) {
14889                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14890            }
14891        }
14892    }
14893
14894    @Override
14895    public byte[] getIntentFilterVerificationBackup(int userId) {
14896        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14897            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14898        }
14899
14900        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14901        try {
14902            final XmlSerializer serializer = new FastXmlSerializer();
14903            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14904            serializer.startDocument(null, true);
14905            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14906
14907            synchronized (mPackages) {
14908                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14909            }
14910
14911            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14912            serializer.endDocument();
14913            serializer.flush();
14914        } catch (Exception e) {
14915            if (DEBUG_BACKUP) {
14916                Slog.e(TAG, "Unable to write default apps for backup", e);
14917            }
14918            return null;
14919        }
14920
14921        return dataStream.toByteArray();
14922    }
14923
14924    @Override
14925    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14926        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14927            throw new SecurityException("Only the system may call restorePreferredActivities()");
14928        }
14929
14930        try {
14931            final XmlPullParser parser = Xml.newPullParser();
14932            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14933            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14934                    new BlobXmlRestorer() {
14935                        @Override
14936                        public void apply(XmlPullParser parser, int userId)
14937                                throws XmlPullParserException, IOException {
14938                            synchronized (mPackages) {
14939                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14940                                mSettings.writeLPr();
14941                            }
14942                        }
14943                    } );
14944        } catch (Exception e) {
14945            if (DEBUG_BACKUP) {
14946                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14947            }
14948        }
14949    }
14950
14951    @Override
14952    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14953            int sourceUserId, int targetUserId, int flags) {
14954        mContext.enforceCallingOrSelfPermission(
14955                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14956        int callingUid = Binder.getCallingUid();
14957        enforceOwnerRights(ownerPackage, callingUid);
14958        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14959        if (intentFilter.countActions() == 0) {
14960            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14961            return;
14962        }
14963        synchronized (mPackages) {
14964            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14965                    ownerPackage, targetUserId, flags);
14966            CrossProfileIntentResolver resolver =
14967                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14968            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14969            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14970            if (existing != null) {
14971                int size = existing.size();
14972                for (int i = 0; i < size; i++) {
14973                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14974                        return;
14975                    }
14976                }
14977            }
14978            resolver.addFilter(newFilter);
14979            scheduleWritePackageRestrictionsLocked(sourceUserId);
14980        }
14981    }
14982
14983    @Override
14984    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14985        mContext.enforceCallingOrSelfPermission(
14986                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14987        int callingUid = Binder.getCallingUid();
14988        enforceOwnerRights(ownerPackage, callingUid);
14989        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14990        synchronized (mPackages) {
14991            CrossProfileIntentResolver resolver =
14992                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14993            ArraySet<CrossProfileIntentFilter> set =
14994                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14995            for (CrossProfileIntentFilter filter : set) {
14996                if (filter.getOwnerPackage().equals(ownerPackage)) {
14997                    resolver.removeFilter(filter);
14998                }
14999            }
15000            scheduleWritePackageRestrictionsLocked(sourceUserId);
15001        }
15002    }
15003
15004    // Enforcing that callingUid is owning pkg on userId
15005    private void enforceOwnerRights(String pkg, int callingUid) {
15006        // The system owns everything.
15007        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15008            return;
15009        }
15010        int callingUserId = UserHandle.getUserId(callingUid);
15011        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15012        if (pi == null) {
15013            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15014                    + callingUserId);
15015        }
15016        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15017            throw new SecurityException("Calling uid " + callingUid
15018                    + " does not own package " + pkg);
15019        }
15020    }
15021
15022    @Override
15023    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15024        Intent intent = new Intent(Intent.ACTION_MAIN);
15025        intent.addCategory(Intent.CATEGORY_HOME);
15026
15027        final int callingUserId = UserHandle.getCallingUserId();
15028        List<ResolveInfo> list = queryIntentActivities(intent, null,
15029                PackageManager.GET_META_DATA, callingUserId);
15030        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15031                true, false, false, callingUserId);
15032
15033        allHomeCandidates.clear();
15034        if (list != null) {
15035            for (ResolveInfo ri : list) {
15036                allHomeCandidates.add(ri);
15037            }
15038        }
15039        return (preferred == null || preferred.activityInfo == null)
15040                ? null
15041                : new ComponentName(preferred.activityInfo.packageName,
15042                        preferred.activityInfo.name);
15043    }
15044
15045    @Override
15046    public void setApplicationEnabledSetting(String appPackageName,
15047            int newState, int flags, int userId, String callingPackage) {
15048        if (!sUserManager.exists(userId)) return;
15049        if (callingPackage == null) {
15050            callingPackage = Integer.toString(Binder.getCallingUid());
15051        }
15052        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15053    }
15054
15055    @Override
15056    public void setComponentEnabledSetting(ComponentName componentName,
15057            int newState, int flags, int userId) {
15058        if (!sUserManager.exists(userId)) return;
15059        setEnabledSetting(componentName.getPackageName(),
15060                componentName.getClassName(), newState, flags, userId, null);
15061    }
15062
15063    private void setEnabledSetting(final String packageName, String className, int newState,
15064            final int flags, int userId, String callingPackage) {
15065        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15066              || newState == COMPONENT_ENABLED_STATE_ENABLED
15067              || newState == COMPONENT_ENABLED_STATE_DISABLED
15068              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15069              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15070            throw new IllegalArgumentException("Invalid new component state: "
15071                    + newState);
15072        }
15073        PackageSetting pkgSetting;
15074        final int uid = Binder.getCallingUid();
15075        final int permission = mContext.checkCallingOrSelfPermission(
15076                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15077        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15078        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15079        boolean sendNow = false;
15080        boolean isApp = (className == null);
15081        String componentName = isApp ? packageName : className;
15082        int packageUid = -1;
15083        ArrayList<String> components;
15084
15085        // writer
15086        synchronized (mPackages) {
15087            pkgSetting = mSettings.mPackages.get(packageName);
15088            if (pkgSetting == null) {
15089                if (className == null) {
15090                    throw new IllegalArgumentException("Unknown package: " + packageName);
15091                }
15092                throw new IllegalArgumentException(
15093                        "Unknown component: " + packageName + "/" + className);
15094            }
15095            // Allow root and verify that userId is not being specified by a different user
15096            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15097                throw new SecurityException(
15098                        "Permission Denial: attempt to change component state from pid="
15099                        + Binder.getCallingPid()
15100                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15101            }
15102            if (className == null) {
15103                // We're dealing with an application/package level state change
15104                if (pkgSetting.getEnabled(userId) == newState) {
15105                    // Nothing to do
15106                    return;
15107                }
15108                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15109                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15110                    // Don't care about who enables an app.
15111                    callingPackage = null;
15112                }
15113                pkgSetting.setEnabled(newState, userId, callingPackage);
15114                // pkgSetting.pkg.mSetEnabled = newState;
15115            } else {
15116                // We're dealing with a component level state change
15117                // First, verify that this is a valid class name.
15118                PackageParser.Package pkg = pkgSetting.pkg;
15119                if (pkg == null || !pkg.hasComponentClassName(className)) {
15120                    if (pkg != null &&
15121                            pkg.applicationInfo.targetSdkVersion >=
15122                                    Build.VERSION_CODES.JELLY_BEAN) {
15123                        throw new IllegalArgumentException("Component class " + className
15124                                + " does not exist in " + packageName);
15125                    } else {
15126                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15127                                + className + " does not exist in " + packageName);
15128                    }
15129                }
15130                switch (newState) {
15131                case COMPONENT_ENABLED_STATE_ENABLED:
15132                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15133                        return;
15134                    }
15135                    break;
15136                case COMPONENT_ENABLED_STATE_DISABLED:
15137                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15138                        return;
15139                    }
15140                    break;
15141                case COMPONENT_ENABLED_STATE_DEFAULT:
15142                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15143                        return;
15144                    }
15145                    break;
15146                default:
15147                    Slog.e(TAG, "Invalid new component state: " + newState);
15148                    return;
15149                }
15150            }
15151            scheduleWritePackageRestrictionsLocked(userId);
15152            components = mPendingBroadcasts.get(userId, packageName);
15153            final boolean newPackage = components == null;
15154            if (newPackage) {
15155                components = new ArrayList<String>();
15156            }
15157            if (!components.contains(componentName)) {
15158                components.add(componentName);
15159            }
15160            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15161                sendNow = true;
15162                // Purge entry from pending broadcast list if another one exists already
15163                // since we are sending one right away.
15164                mPendingBroadcasts.remove(userId, packageName);
15165            } else {
15166                if (newPackage) {
15167                    mPendingBroadcasts.put(userId, packageName, components);
15168                }
15169                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15170                    // Schedule a message
15171                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15172                }
15173            }
15174        }
15175
15176        long callingId = Binder.clearCallingIdentity();
15177        try {
15178            if (sendNow) {
15179                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15180                sendPackageChangedBroadcast(packageName,
15181                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15182            }
15183        } finally {
15184            Binder.restoreCallingIdentity(callingId);
15185        }
15186    }
15187
15188    private void sendPackageChangedBroadcast(String packageName,
15189            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15190        if (DEBUG_INSTALL)
15191            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15192                    + componentNames);
15193        Bundle extras = new Bundle(4);
15194        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15195        String nameList[] = new String[componentNames.size()];
15196        componentNames.toArray(nameList);
15197        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15198        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15199        extras.putInt(Intent.EXTRA_UID, packageUid);
15200        // If this is not reporting a change of the overall package, then only send it
15201        // to registered receivers.  We don't want to launch a swath of apps for every
15202        // little component state change.
15203        final int flags = !componentNames.contains(packageName)
15204                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15205        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15206                new int[] {UserHandle.getUserId(packageUid)});
15207    }
15208
15209    @Override
15210    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15211        if (!sUserManager.exists(userId)) return;
15212        final int uid = Binder.getCallingUid();
15213        final int permission = mContext.checkCallingOrSelfPermission(
15214                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15215        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15216        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15217        // writer
15218        synchronized (mPackages) {
15219            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15220                    allowedByPermission, uid, userId)) {
15221                scheduleWritePackageRestrictionsLocked(userId);
15222            }
15223        }
15224    }
15225
15226    @Override
15227    public String getInstallerPackageName(String packageName) {
15228        // reader
15229        synchronized (mPackages) {
15230            return mSettings.getInstallerPackageNameLPr(packageName);
15231        }
15232    }
15233
15234    @Override
15235    public int getApplicationEnabledSetting(String packageName, int userId) {
15236        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15237        int uid = Binder.getCallingUid();
15238        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15239        // reader
15240        synchronized (mPackages) {
15241            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15242        }
15243    }
15244
15245    @Override
15246    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15247        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15248        int uid = Binder.getCallingUid();
15249        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15250        // reader
15251        synchronized (mPackages) {
15252            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15253        }
15254    }
15255
15256    @Override
15257    public void enterSafeMode() {
15258        enforceSystemOrRoot("Only the system can request entering safe mode");
15259
15260        if (!mSystemReady) {
15261            mSafeMode = true;
15262        }
15263    }
15264
15265    @Override
15266    public void systemReady() {
15267        mSystemReady = true;
15268
15269        // Read the compatibilty setting when the system is ready.
15270        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15271                mContext.getContentResolver(),
15272                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15273        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15274        if (DEBUG_SETTINGS) {
15275            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15276        }
15277
15278        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15279
15280        synchronized (mPackages) {
15281            // Verify that all of the preferred activity components actually
15282            // exist.  It is possible for applications to be updated and at
15283            // that point remove a previously declared activity component that
15284            // had been set as a preferred activity.  We try to clean this up
15285            // the next time we encounter that preferred activity, but it is
15286            // possible for the user flow to never be able to return to that
15287            // situation so here we do a sanity check to make sure we haven't
15288            // left any junk around.
15289            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15290            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15291                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15292                removed.clear();
15293                for (PreferredActivity pa : pir.filterSet()) {
15294                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15295                        removed.add(pa);
15296                    }
15297                }
15298                if (removed.size() > 0) {
15299                    for (int r=0; r<removed.size(); r++) {
15300                        PreferredActivity pa = removed.get(r);
15301                        Slog.w(TAG, "Removing dangling preferred activity: "
15302                                + pa.mPref.mComponent);
15303                        pir.removeFilter(pa);
15304                    }
15305                    mSettings.writePackageRestrictionsLPr(
15306                            mSettings.mPreferredActivities.keyAt(i));
15307                }
15308            }
15309
15310            for (int userId : UserManagerService.getInstance().getUserIds()) {
15311                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15312                    grantPermissionsUserIds = ArrayUtils.appendInt(
15313                            grantPermissionsUserIds, userId);
15314                }
15315            }
15316        }
15317        sUserManager.systemReady();
15318
15319        // If we upgraded grant all default permissions before kicking off.
15320        for (int userId : grantPermissionsUserIds) {
15321            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15322        }
15323
15324        // Kick off any messages waiting for system ready
15325        if (mPostSystemReadyMessages != null) {
15326            for (Message msg : mPostSystemReadyMessages) {
15327                msg.sendToTarget();
15328            }
15329            mPostSystemReadyMessages = null;
15330        }
15331
15332        // Watch for external volumes that come and go over time
15333        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15334        storage.registerListener(mStorageListener);
15335
15336        mInstallerService.systemReady();
15337        mPackageDexOptimizer.systemReady();
15338
15339        MountServiceInternal mountServiceInternal = LocalServices.getService(
15340                MountServiceInternal.class);
15341        mountServiceInternal.addExternalStoragePolicy(
15342                new MountServiceInternal.ExternalStorageMountPolicy() {
15343            @Override
15344            public int getMountMode(int uid, String packageName) {
15345                if (Process.isIsolated(uid)) {
15346                    return Zygote.MOUNT_EXTERNAL_NONE;
15347                }
15348                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15349                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15350                }
15351                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15352                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15353                }
15354                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15355                    return Zygote.MOUNT_EXTERNAL_READ;
15356                }
15357                return Zygote.MOUNT_EXTERNAL_WRITE;
15358            }
15359
15360            @Override
15361            public boolean hasExternalStorage(int uid, String packageName) {
15362                return true;
15363            }
15364        });
15365    }
15366
15367    @Override
15368    public boolean isSafeMode() {
15369        return mSafeMode;
15370    }
15371
15372    @Override
15373    public boolean hasSystemUidErrors() {
15374        return mHasSystemUidErrors;
15375    }
15376
15377    static String arrayToString(int[] array) {
15378        StringBuffer buf = new StringBuffer(128);
15379        buf.append('[');
15380        if (array != null) {
15381            for (int i=0; i<array.length; i++) {
15382                if (i > 0) buf.append(", ");
15383                buf.append(array[i]);
15384            }
15385        }
15386        buf.append(']');
15387        return buf.toString();
15388    }
15389
15390    static class DumpState {
15391        public static final int DUMP_LIBS = 1 << 0;
15392        public static final int DUMP_FEATURES = 1 << 1;
15393        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15394        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15395        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15396        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15397        public static final int DUMP_PERMISSIONS = 1 << 6;
15398        public static final int DUMP_PACKAGES = 1 << 7;
15399        public static final int DUMP_SHARED_USERS = 1 << 8;
15400        public static final int DUMP_MESSAGES = 1 << 9;
15401        public static final int DUMP_PROVIDERS = 1 << 10;
15402        public static final int DUMP_VERIFIERS = 1 << 11;
15403        public static final int DUMP_PREFERRED = 1 << 12;
15404        public static final int DUMP_PREFERRED_XML = 1 << 13;
15405        public static final int DUMP_KEYSETS = 1 << 14;
15406        public static final int DUMP_VERSION = 1 << 15;
15407        public static final int DUMP_INSTALLS = 1 << 16;
15408        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15409        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15410
15411        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15412
15413        private int mTypes;
15414
15415        private int mOptions;
15416
15417        private boolean mTitlePrinted;
15418
15419        private SharedUserSetting mSharedUser;
15420
15421        public boolean isDumping(int type) {
15422            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15423                return true;
15424            }
15425
15426            return (mTypes & type) != 0;
15427        }
15428
15429        public void setDump(int type) {
15430            mTypes |= type;
15431        }
15432
15433        public boolean isOptionEnabled(int option) {
15434            return (mOptions & option) != 0;
15435        }
15436
15437        public void setOptionEnabled(int option) {
15438            mOptions |= option;
15439        }
15440
15441        public boolean onTitlePrinted() {
15442            final boolean printed = mTitlePrinted;
15443            mTitlePrinted = true;
15444            return printed;
15445        }
15446
15447        public boolean getTitlePrinted() {
15448            return mTitlePrinted;
15449        }
15450
15451        public void setTitlePrinted(boolean enabled) {
15452            mTitlePrinted = enabled;
15453        }
15454
15455        public SharedUserSetting getSharedUser() {
15456            return mSharedUser;
15457        }
15458
15459        public void setSharedUser(SharedUserSetting user) {
15460            mSharedUser = user;
15461        }
15462    }
15463
15464    @Override
15465    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15466            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15467        (new PackageManagerShellCommand(this)).exec(
15468                this, in, out, err, args, resultReceiver);
15469    }
15470
15471    @Override
15472    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15473        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15474                != PackageManager.PERMISSION_GRANTED) {
15475            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15476                    + Binder.getCallingPid()
15477                    + ", uid=" + Binder.getCallingUid()
15478                    + " without permission "
15479                    + android.Manifest.permission.DUMP);
15480            return;
15481        }
15482
15483        DumpState dumpState = new DumpState();
15484        boolean fullPreferred = false;
15485        boolean checkin = false;
15486
15487        String packageName = null;
15488        ArraySet<String> permissionNames = null;
15489
15490        int opti = 0;
15491        while (opti < args.length) {
15492            String opt = args[opti];
15493            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15494                break;
15495            }
15496            opti++;
15497
15498            if ("-a".equals(opt)) {
15499                // Right now we only know how to print all.
15500            } else if ("-h".equals(opt)) {
15501                pw.println("Package manager dump options:");
15502                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15503                pw.println("    --checkin: dump for a checkin");
15504                pw.println("    -f: print details of intent filters");
15505                pw.println("    -h: print this help");
15506                pw.println("  cmd may be one of:");
15507                pw.println("    l[ibraries]: list known shared libraries");
15508                pw.println("    f[eatures]: list device features");
15509                pw.println("    k[eysets]: print known keysets");
15510                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15511                pw.println("    perm[issions]: dump permissions");
15512                pw.println("    permission [name ...]: dump declaration and use of given permission");
15513                pw.println("    pref[erred]: print preferred package settings");
15514                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15515                pw.println("    prov[iders]: dump content providers");
15516                pw.println("    p[ackages]: dump installed packages");
15517                pw.println("    s[hared-users]: dump shared user IDs");
15518                pw.println("    m[essages]: print collected runtime messages");
15519                pw.println("    v[erifiers]: print package verifier info");
15520                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15521                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15522                pw.println("    version: print database version info");
15523                pw.println("    write: write current settings now");
15524                pw.println("    installs: details about install sessions");
15525                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15526                pw.println("    <package.name>: info about given package");
15527                return;
15528            } else if ("--checkin".equals(opt)) {
15529                checkin = true;
15530            } else if ("-f".equals(opt)) {
15531                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15532            } else {
15533                pw.println("Unknown argument: " + opt + "; use -h for help");
15534            }
15535        }
15536
15537        // Is the caller requesting to dump a particular piece of data?
15538        if (opti < args.length) {
15539            String cmd = args[opti];
15540            opti++;
15541            // Is this a package name?
15542            if ("android".equals(cmd) || cmd.contains(".")) {
15543                packageName = cmd;
15544                // When dumping a single package, we always dump all of its
15545                // filter information since the amount of data will be reasonable.
15546                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15547            } else if ("check-permission".equals(cmd)) {
15548                if (opti >= args.length) {
15549                    pw.println("Error: check-permission missing permission argument");
15550                    return;
15551                }
15552                String perm = args[opti];
15553                opti++;
15554                if (opti >= args.length) {
15555                    pw.println("Error: check-permission missing package argument");
15556                    return;
15557                }
15558                String pkg = args[opti];
15559                opti++;
15560                int user = UserHandle.getUserId(Binder.getCallingUid());
15561                if (opti < args.length) {
15562                    try {
15563                        user = Integer.parseInt(args[opti]);
15564                    } catch (NumberFormatException e) {
15565                        pw.println("Error: check-permission user argument is not a number: "
15566                                + args[opti]);
15567                        return;
15568                    }
15569                }
15570                pw.println(checkPermission(perm, pkg, user));
15571                return;
15572            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15573                dumpState.setDump(DumpState.DUMP_LIBS);
15574            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15575                dumpState.setDump(DumpState.DUMP_FEATURES);
15576            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15577                if (opti >= args.length) {
15578                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15579                            | DumpState.DUMP_SERVICE_RESOLVERS
15580                            | DumpState.DUMP_RECEIVER_RESOLVERS
15581                            | DumpState.DUMP_CONTENT_RESOLVERS);
15582                } else {
15583                    while (opti < args.length) {
15584                        String name = args[opti];
15585                        if ("a".equals(name) || "activity".equals(name)) {
15586                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15587                        } else if ("s".equals(name) || "service".equals(name)) {
15588                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15589                        } else if ("r".equals(name) || "receiver".equals(name)) {
15590                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15591                        } else if ("c".equals(name) || "content".equals(name)) {
15592                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15593                        } else {
15594                            pw.println("Error: unknown resolver table type: " + name);
15595                            return;
15596                        }
15597                        opti++;
15598                    }
15599                }
15600            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15601                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15602            } else if ("permission".equals(cmd)) {
15603                if (opti >= args.length) {
15604                    pw.println("Error: permission requires permission name");
15605                    return;
15606                }
15607                permissionNames = new ArraySet<>();
15608                while (opti < args.length) {
15609                    permissionNames.add(args[opti]);
15610                    opti++;
15611                }
15612                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15613                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15614            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15615                dumpState.setDump(DumpState.DUMP_PREFERRED);
15616            } else if ("preferred-xml".equals(cmd)) {
15617                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15618                if (opti < args.length && "--full".equals(args[opti])) {
15619                    fullPreferred = true;
15620                    opti++;
15621                }
15622            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15623                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15624            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15625                dumpState.setDump(DumpState.DUMP_PACKAGES);
15626            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15627                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15628            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15629                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15630            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15631                dumpState.setDump(DumpState.DUMP_MESSAGES);
15632            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15633                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15634            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15635                    || "intent-filter-verifiers".equals(cmd)) {
15636                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15637            } else if ("version".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_VERSION);
15639            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_KEYSETS);
15641            } else if ("installs".equals(cmd)) {
15642                dumpState.setDump(DumpState.DUMP_INSTALLS);
15643            } else if ("write".equals(cmd)) {
15644                synchronized (mPackages) {
15645                    mSettings.writeLPr();
15646                    pw.println("Settings written.");
15647                    return;
15648                }
15649            }
15650        }
15651
15652        if (checkin) {
15653            pw.println("vers,1");
15654        }
15655
15656        // reader
15657        synchronized (mPackages) {
15658            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15659                if (!checkin) {
15660                    if (dumpState.onTitlePrinted())
15661                        pw.println();
15662                    pw.println("Database versions:");
15663                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15664                }
15665            }
15666
15667            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15668                if (!checkin) {
15669                    if (dumpState.onTitlePrinted())
15670                        pw.println();
15671                    pw.println("Verifiers:");
15672                    pw.print("  Required: ");
15673                    pw.print(mRequiredVerifierPackage);
15674                    pw.print(" (uid=");
15675                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15676                    pw.println(")");
15677                } else if (mRequiredVerifierPackage != null) {
15678                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15679                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15680                }
15681            }
15682
15683            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15684                    packageName == null) {
15685                if (mIntentFilterVerifierComponent != null) {
15686                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15687                    if (!checkin) {
15688                        if (dumpState.onTitlePrinted())
15689                            pw.println();
15690                        pw.println("Intent Filter Verifier:");
15691                        pw.print("  Using: ");
15692                        pw.print(verifierPackageName);
15693                        pw.print(" (uid=");
15694                        pw.print(getPackageUid(verifierPackageName, 0));
15695                        pw.println(")");
15696                    } else if (verifierPackageName != null) {
15697                        pw.print("ifv,"); pw.print(verifierPackageName);
15698                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15699                    }
15700                } else {
15701                    pw.println();
15702                    pw.println("No Intent Filter Verifier available!");
15703                }
15704            }
15705
15706            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15707                boolean printedHeader = false;
15708                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15709                while (it.hasNext()) {
15710                    String name = it.next();
15711                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15712                    if (!checkin) {
15713                        if (!printedHeader) {
15714                            if (dumpState.onTitlePrinted())
15715                                pw.println();
15716                            pw.println("Libraries:");
15717                            printedHeader = true;
15718                        }
15719                        pw.print("  ");
15720                    } else {
15721                        pw.print("lib,");
15722                    }
15723                    pw.print(name);
15724                    if (!checkin) {
15725                        pw.print(" -> ");
15726                    }
15727                    if (ent.path != null) {
15728                        if (!checkin) {
15729                            pw.print("(jar) ");
15730                            pw.print(ent.path);
15731                        } else {
15732                            pw.print(",jar,");
15733                            pw.print(ent.path);
15734                        }
15735                    } else {
15736                        if (!checkin) {
15737                            pw.print("(apk) ");
15738                            pw.print(ent.apk);
15739                        } else {
15740                            pw.print(",apk,");
15741                            pw.print(ent.apk);
15742                        }
15743                    }
15744                    pw.println();
15745                }
15746            }
15747
15748            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15749                if (dumpState.onTitlePrinted())
15750                    pw.println();
15751                if (!checkin) {
15752                    pw.println("Features:");
15753                }
15754                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15755                while (it.hasNext()) {
15756                    String name = it.next();
15757                    if (!checkin) {
15758                        pw.print("  ");
15759                    } else {
15760                        pw.print("feat,");
15761                    }
15762                    pw.println(name);
15763                }
15764            }
15765
15766            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15767                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15768                        : "Activity Resolver Table:", "  ", packageName,
15769                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15770                    dumpState.setTitlePrinted(true);
15771                }
15772            }
15773            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15774                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15775                        : "Receiver Resolver Table:", "  ", packageName,
15776                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15777                    dumpState.setTitlePrinted(true);
15778                }
15779            }
15780            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15781                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15782                        : "Service Resolver Table:", "  ", packageName,
15783                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15784                    dumpState.setTitlePrinted(true);
15785                }
15786            }
15787            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15788                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15789                        : "Provider Resolver Table:", "  ", packageName,
15790                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15791                    dumpState.setTitlePrinted(true);
15792                }
15793            }
15794
15795            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15796                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15797                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15798                    int user = mSettings.mPreferredActivities.keyAt(i);
15799                    if (pir.dump(pw,
15800                            dumpState.getTitlePrinted()
15801                                ? "\nPreferred Activities User " + user + ":"
15802                                : "Preferred Activities User " + user + ":", "  ",
15803                            packageName, true, false)) {
15804                        dumpState.setTitlePrinted(true);
15805                    }
15806                }
15807            }
15808
15809            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15810                pw.flush();
15811                FileOutputStream fout = new FileOutputStream(fd);
15812                BufferedOutputStream str = new BufferedOutputStream(fout);
15813                XmlSerializer serializer = new FastXmlSerializer();
15814                try {
15815                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15816                    serializer.startDocument(null, true);
15817                    serializer.setFeature(
15818                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15819                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15820                    serializer.endDocument();
15821                    serializer.flush();
15822                } catch (IllegalArgumentException e) {
15823                    pw.println("Failed writing: " + e);
15824                } catch (IllegalStateException e) {
15825                    pw.println("Failed writing: " + e);
15826                } catch (IOException e) {
15827                    pw.println("Failed writing: " + e);
15828                }
15829            }
15830
15831            if (!checkin
15832                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15833                    && packageName == null) {
15834                pw.println();
15835                int count = mSettings.mPackages.size();
15836                if (count == 0) {
15837                    pw.println("No applications!");
15838                    pw.println();
15839                } else {
15840                    final String prefix = "  ";
15841                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15842                    if (allPackageSettings.size() == 0) {
15843                        pw.println("No domain preferred apps!");
15844                        pw.println();
15845                    } else {
15846                        pw.println("App verification status:");
15847                        pw.println();
15848                        count = 0;
15849                        for (PackageSetting ps : allPackageSettings) {
15850                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15851                            if (ivi == null || ivi.getPackageName() == null) continue;
15852                            pw.println(prefix + "Package: " + ivi.getPackageName());
15853                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15854                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15855                            pw.println();
15856                            count++;
15857                        }
15858                        if (count == 0) {
15859                            pw.println(prefix + "No app verification established.");
15860                            pw.println();
15861                        }
15862                        for (int userId : sUserManager.getUserIds()) {
15863                            pw.println("App linkages for user " + userId + ":");
15864                            pw.println();
15865                            count = 0;
15866                            for (PackageSetting ps : allPackageSettings) {
15867                                final long status = ps.getDomainVerificationStatusForUser(userId);
15868                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15869                                    continue;
15870                                }
15871                                pw.println(prefix + "Package: " + ps.name);
15872                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15873                                String statusStr = IntentFilterVerificationInfo.
15874                                        getStatusStringFromValue(status);
15875                                pw.println(prefix + "Status:  " + statusStr);
15876                                pw.println();
15877                                count++;
15878                            }
15879                            if (count == 0) {
15880                                pw.println(prefix + "No configured app linkages.");
15881                                pw.println();
15882                            }
15883                        }
15884                    }
15885                }
15886            }
15887
15888            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15889                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15890                if (packageName == null && permissionNames == null) {
15891                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15892                        if (iperm == 0) {
15893                            if (dumpState.onTitlePrinted())
15894                                pw.println();
15895                            pw.println("AppOp Permissions:");
15896                        }
15897                        pw.print("  AppOp Permission ");
15898                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15899                        pw.println(":");
15900                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15901                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15902                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15903                        }
15904                    }
15905                }
15906            }
15907
15908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15909                boolean printedSomething = false;
15910                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15911                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15912                        continue;
15913                    }
15914                    if (!printedSomething) {
15915                        if (dumpState.onTitlePrinted())
15916                            pw.println();
15917                        pw.println("Registered ContentProviders:");
15918                        printedSomething = true;
15919                    }
15920                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15921                    pw.print("    "); pw.println(p.toString());
15922                }
15923                printedSomething = false;
15924                for (Map.Entry<String, PackageParser.Provider> entry :
15925                        mProvidersByAuthority.entrySet()) {
15926                    PackageParser.Provider p = entry.getValue();
15927                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15928                        continue;
15929                    }
15930                    if (!printedSomething) {
15931                        if (dumpState.onTitlePrinted())
15932                            pw.println();
15933                        pw.println("ContentProvider Authorities:");
15934                        printedSomething = true;
15935                    }
15936                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15937                    pw.print("    "); pw.println(p.toString());
15938                    if (p.info != null && p.info.applicationInfo != null) {
15939                        final String appInfo = p.info.applicationInfo.toString();
15940                        pw.print("      applicationInfo="); pw.println(appInfo);
15941                    }
15942                }
15943            }
15944
15945            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15946                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15947            }
15948
15949            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15950                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15951            }
15952
15953            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15954                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15955            }
15956
15957            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15958                // XXX should handle packageName != null by dumping only install data that
15959                // the given package is involved with.
15960                if (dumpState.onTitlePrinted()) pw.println();
15961                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15962            }
15963
15964            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15965                if (dumpState.onTitlePrinted()) pw.println();
15966                mSettings.dumpReadMessagesLPr(pw, dumpState);
15967
15968                pw.println();
15969                pw.println("Package warning messages:");
15970                BufferedReader in = null;
15971                String line = null;
15972                try {
15973                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15974                    while ((line = in.readLine()) != null) {
15975                        if (line.contains("ignored: updated version")) continue;
15976                        pw.println(line);
15977                    }
15978                } catch (IOException ignored) {
15979                } finally {
15980                    IoUtils.closeQuietly(in);
15981                }
15982            }
15983
15984            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15985                BufferedReader in = null;
15986                String line = null;
15987                try {
15988                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15989                    while ((line = in.readLine()) != null) {
15990                        if (line.contains("ignored: updated version")) continue;
15991                        pw.print("msg,");
15992                        pw.println(line);
15993                    }
15994                } catch (IOException ignored) {
15995                } finally {
15996                    IoUtils.closeQuietly(in);
15997                }
15998            }
15999        }
16000    }
16001
16002    private String dumpDomainString(String packageName) {
16003        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16004        List<IntentFilter> filters = getAllIntentFilters(packageName);
16005
16006        ArraySet<String> result = new ArraySet<>();
16007        if (iviList.size() > 0) {
16008            for (IntentFilterVerificationInfo ivi : iviList) {
16009                for (String host : ivi.getDomains()) {
16010                    result.add(host);
16011                }
16012            }
16013        }
16014        if (filters != null && filters.size() > 0) {
16015            for (IntentFilter filter : filters) {
16016                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16017                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16018                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16019                    result.addAll(filter.getHostsList());
16020                }
16021            }
16022        }
16023
16024        StringBuilder sb = new StringBuilder(result.size() * 16);
16025        for (String domain : result) {
16026            if (sb.length() > 0) sb.append(" ");
16027            sb.append(domain);
16028        }
16029        return sb.toString();
16030    }
16031
16032    // ------- apps on sdcard specific code -------
16033    static final boolean DEBUG_SD_INSTALL = false;
16034
16035    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16036
16037    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16038
16039    private boolean mMediaMounted = false;
16040
16041    static String getEncryptKey() {
16042        try {
16043            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16044                    SD_ENCRYPTION_KEYSTORE_NAME);
16045            if (sdEncKey == null) {
16046                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16047                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16048                if (sdEncKey == null) {
16049                    Slog.e(TAG, "Failed to create encryption keys");
16050                    return null;
16051                }
16052            }
16053            return sdEncKey;
16054        } catch (NoSuchAlgorithmException nsae) {
16055            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16056            return null;
16057        } catch (IOException ioe) {
16058            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16059            return null;
16060        }
16061    }
16062
16063    /*
16064     * Update media status on PackageManager.
16065     */
16066    @Override
16067    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16068        int callingUid = Binder.getCallingUid();
16069        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16070            throw new SecurityException("Media status can only be updated by the system");
16071        }
16072        // reader; this apparently protects mMediaMounted, but should probably
16073        // be a different lock in that case.
16074        synchronized (mPackages) {
16075            Log.i(TAG, "Updating external media status from "
16076                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16077                    + (mediaStatus ? "mounted" : "unmounted"));
16078            if (DEBUG_SD_INSTALL)
16079                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16080                        + ", mMediaMounted=" + mMediaMounted);
16081            if (mediaStatus == mMediaMounted) {
16082                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16083                        : 0, -1);
16084                mHandler.sendMessage(msg);
16085                return;
16086            }
16087            mMediaMounted = mediaStatus;
16088        }
16089        // Queue up an async operation since the package installation may take a
16090        // little while.
16091        mHandler.post(new Runnable() {
16092            public void run() {
16093                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16094            }
16095        });
16096    }
16097
16098    /**
16099     * Called by MountService when the initial ASECs to scan are available.
16100     * Should block until all the ASEC containers are finished being scanned.
16101     */
16102    public void scanAvailableAsecs() {
16103        updateExternalMediaStatusInner(true, false, false);
16104        if (mShouldRestoreconData) {
16105            SELinuxMMAC.setRestoreconDone();
16106            mShouldRestoreconData = false;
16107        }
16108    }
16109
16110    /*
16111     * Collect information of applications on external media, map them against
16112     * existing containers and update information based on current mount status.
16113     * Please note that we always have to report status if reportStatus has been
16114     * set to true especially when unloading packages.
16115     */
16116    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16117            boolean externalStorage) {
16118        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16119        int[] uidArr = EmptyArray.INT;
16120
16121        final String[] list = PackageHelper.getSecureContainerList();
16122        if (ArrayUtils.isEmpty(list)) {
16123            Log.i(TAG, "No secure containers found");
16124        } else {
16125            // Process list of secure containers and categorize them
16126            // as active or stale based on their package internal state.
16127
16128            // reader
16129            synchronized (mPackages) {
16130                for (String cid : list) {
16131                    // Leave stages untouched for now; installer service owns them
16132                    if (PackageInstallerService.isStageName(cid)) continue;
16133
16134                    if (DEBUG_SD_INSTALL)
16135                        Log.i(TAG, "Processing container " + cid);
16136                    String pkgName = getAsecPackageName(cid);
16137                    if (pkgName == null) {
16138                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16139                        continue;
16140                    }
16141                    if (DEBUG_SD_INSTALL)
16142                        Log.i(TAG, "Looking for pkg : " + pkgName);
16143
16144                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16145                    if (ps == null) {
16146                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16147                        continue;
16148                    }
16149
16150                    /*
16151                     * Skip packages that are not external if we're unmounting
16152                     * external storage.
16153                     */
16154                    if (externalStorage && !isMounted && !isExternal(ps)) {
16155                        continue;
16156                    }
16157
16158                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16159                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16160                    // The package status is changed only if the code path
16161                    // matches between settings and the container id.
16162                    if (ps.codePathString != null
16163                            && ps.codePathString.startsWith(args.getCodePath())) {
16164                        if (DEBUG_SD_INSTALL) {
16165                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16166                                    + " at code path: " + ps.codePathString);
16167                        }
16168
16169                        // We do have a valid package installed on sdcard
16170                        processCids.put(args, ps.codePathString);
16171                        final int uid = ps.appId;
16172                        if (uid != -1) {
16173                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16174                        }
16175                    } else {
16176                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16177                                + ps.codePathString);
16178                    }
16179                }
16180            }
16181
16182            Arrays.sort(uidArr);
16183        }
16184
16185        // Process packages with valid entries.
16186        if (isMounted) {
16187            if (DEBUG_SD_INSTALL)
16188                Log.i(TAG, "Loading packages");
16189            loadMediaPackages(processCids, uidArr, externalStorage);
16190            startCleaningPackages();
16191            mInstallerService.onSecureContainersAvailable();
16192        } else {
16193            if (DEBUG_SD_INSTALL)
16194                Log.i(TAG, "Unloading packages");
16195            unloadMediaPackages(processCids, uidArr, reportStatus);
16196        }
16197    }
16198
16199    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16200            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16201        final int size = infos.size();
16202        final String[] packageNames = new String[size];
16203        final int[] packageUids = new int[size];
16204        for (int i = 0; i < size; i++) {
16205            final ApplicationInfo info = infos.get(i);
16206            packageNames[i] = info.packageName;
16207            packageUids[i] = info.uid;
16208        }
16209        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16210                finishedReceiver);
16211    }
16212
16213    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16214            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16215        sendResourcesChangedBroadcast(mediaStatus, replacing,
16216                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16217    }
16218
16219    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16220            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16221        int size = pkgList.length;
16222        if (size > 0) {
16223            // Send broadcasts here
16224            Bundle extras = new Bundle();
16225            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16226            if (uidArr != null) {
16227                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16228            }
16229            if (replacing) {
16230                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16231            }
16232            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16233                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16234            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16235        }
16236    }
16237
16238   /*
16239     * Look at potentially valid container ids from processCids If package
16240     * information doesn't match the one on record or package scanning fails,
16241     * the cid is added to list of removeCids. We currently don't delete stale
16242     * containers.
16243     */
16244    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16245            boolean externalStorage) {
16246        ArrayList<String> pkgList = new ArrayList<String>();
16247        Set<AsecInstallArgs> keys = processCids.keySet();
16248
16249        for (AsecInstallArgs args : keys) {
16250            String codePath = processCids.get(args);
16251            if (DEBUG_SD_INSTALL)
16252                Log.i(TAG, "Loading container : " + args.cid);
16253            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16254            try {
16255                // Make sure there are no container errors first.
16256                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16257                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16258                            + " when installing from sdcard");
16259                    continue;
16260                }
16261                // Check code path here.
16262                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16263                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16264                            + " does not match one in settings " + codePath);
16265                    continue;
16266                }
16267                // Parse package
16268                int parseFlags = mDefParseFlags;
16269                if (args.isExternalAsec()) {
16270                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16271                }
16272                if (args.isFwdLocked()) {
16273                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16274                }
16275
16276                synchronized (mInstallLock) {
16277                    PackageParser.Package pkg = null;
16278                    try {
16279                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16280                    } catch (PackageManagerException e) {
16281                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16282                    }
16283                    // Scan the package
16284                    if (pkg != null) {
16285                        /*
16286                         * TODO why is the lock being held? doPostInstall is
16287                         * called in other places without the lock. This needs
16288                         * to be straightened out.
16289                         */
16290                        // writer
16291                        synchronized (mPackages) {
16292                            retCode = PackageManager.INSTALL_SUCCEEDED;
16293                            pkgList.add(pkg.packageName);
16294                            // Post process args
16295                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16296                                    pkg.applicationInfo.uid);
16297                        }
16298                    } else {
16299                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16300                    }
16301                }
16302
16303            } finally {
16304                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16305                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16306                }
16307            }
16308        }
16309        // writer
16310        synchronized (mPackages) {
16311            // If the platform SDK has changed since the last time we booted,
16312            // we need to re-grant app permission to catch any new ones that
16313            // appear. This is really a hack, and means that apps can in some
16314            // cases get permissions that the user didn't initially explicitly
16315            // allow... it would be nice to have some better way to handle
16316            // this situation.
16317            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16318                    : mSettings.getInternalVersion();
16319            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16320                    : StorageManager.UUID_PRIVATE_INTERNAL;
16321
16322            int updateFlags = UPDATE_PERMISSIONS_ALL;
16323            if (ver.sdkVersion != mSdkVersion) {
16324                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16325                        + mSdkVersion + "; regranting permissions for external");
16326                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16327            }
16328            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16329
16330            // Yay, everything is now upgraded
16331            ver.forceCurrent();
16332
16333            // can downgrade to reader
16334            // Persist settings
16335            mSettings.writeLPr();
16336        }
16337        // Send a broadcast to let everyone know we are done processing
16338        if (pkgList.size() > 0) {
16339            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16340        }
16341    }
16342
16343   /*
16344     * Utility method to unload a list of specified containers
16345     */
16346    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16347        // Just unmount all valid containers.
16348        for (AsecInstallArgs arg : cidArgs) {
16349            synchronized (mInstallLock) {
16350                arg.doPostDeleteLI(false);
16351           }
16352       }
16353   }
16354
16355    /*
16356     * Unload packages mounted on external media. This involves deleting package
16357     * data from internal structures, sending broadcasts about diabled packages,
16358     * gc'ing to free up references, unmounting all secure containers
16359     * corresponding to packages on external media, and posting a
16360     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16361     * that we always have to post this message if status has been requested no
16362     * matter what.
16363     */
16364    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16365            final boolean reportStatus) {
16366        if (DEBUG_SD_INSTALL)
16367            Log.i(TAG, "unloading media packages");
16368        ArrayList<String> pkgList = new ArrayList<String>();
16369        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16370        final Set<AsecInstallArgs> keys = processCids.keySet();
16371        for (AsecInstallArgs args : keys) {
16372            String pkgName = args.getPackageName();
16373            if (DEBUG_SD_INSTALL)
16374                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16375            // Delete package internally
16376            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16377            synchronized (mInstallLock) {
16378                boolean res = deletePackageLI(pkgName, null, false, null, null,
16379                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16380                if (res) {
16381                    pkgList.add(pkgName);
16382                } else {
16383                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16384                    failedList.add(args);
16385                }
16386            }
16387        }
16388
16389        // reader
16390        synchronized (mPackages) {
16391            // We didn't update the settings after removing each package;
16392            // write them now for all packages.
16393            mSettings.writeLPr();
16394        }
16395
16396        // We have to absolutely send UPDATED_MEDIA_STATUS only
16397        // after confirming that all the receivers processed the ordered
16398        // broadcast when packages get disabled, force a gc to clean things up.
16399        // and unload all the containers.
16400        if (pkgList.size() > 0) {
16401            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16402                    new IIntentReceiver.Stub() {
16403                public void performReceive(Intent intent, int resultCode, String data,
16404                        Bundle extras, boolean ordered, boolean sticky,
16405                        int sendingUser) throws RemoteException {
16406                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16407                            reportStatus ? 1 : 0, 1, keys);
16408                    mHandler.sendMessage(msg);
16409                }
16410            });
16411        } else {
16412            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16413                    keys);
16414            mHandler.sendMessage(msg);
16415        }
16416    }
16417
16418    private void loadPrivatePackages(final VolumeInfo vol) {
16419        mHandler.post(new Runnable() {
16420            @Override
16421            public void run() {
16422                loadPrivatePackagesInner(vol);
16423            }
16424        });
16425    }
16426
16427    private void loadPrivatePackagesInner(VolumeInfo vol) {
16428        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16429        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16430
16431        final VersionInfo ver;
16432        final List<PackageSetting> packages;
16433        synchronized (mPackages) {
16434            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16435            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16436        }
16437
16438        for (PackageSetting ps : packages) {
16439            synchronized (mInstallLock) {
16440                final PackageParser.Package pkg;
16441                try {
16442                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16443                    loaded.add(pkg.applicationInfo);
16444                } catch (PackageManagerException e) {
16445                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16446                }
16447
16448                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16449                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16450                }
16451            }
16452        }
16453
16454        synchronized (mPackages) {
16455            int updateFlags = UPDATE_PERMISSIONS_ALL;
16456            if (ver.sdkVersion != mSdkVersion) {
16457                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16458                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16459                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16460            }
16461            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16462
16463            // Yay, everything is now upgraded
16464            ver.forceCurrent();
16465
16466            mSettings.writeLPr();
16467        }
16468
16469        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16470        sendResourcesChangedBroadcast(true, false, loaded, null);
16471    }
16472
16473    private void unloadPrivatePackages(final VolumeInfo vol) {
16474        mHandler.post(new Runnable() {
16475            @Override
16476            public void run() {
16477                unloadPrivatePackagesInner(vol);
16478            }
16479        });
16480    }
16481
16482    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16483        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16484        synchronized (mInstallLock) {
16485        synchronized (mPackages) {
16486            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16487            for (PackageSetting ps : packages) {
16488                if (ps.pkg == null) continue;
16489
16490                final ApplicationInfo info = ps.pkg.applicationInfo;
16491                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16492                if (deletePackageLI(ps.name, null, false, null, null,
16493                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16494                    unloaded.add(info);
16495                } else {
16496                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16497                }
16498            }
16499
16500            mSettings.writeLPr();
16501        }
16502        }
16503
16504        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16505        sendResourcesChangedBroadcast(false, false, unloaded, null);
16506    }
16507
16508    /**
16509     * Examine all users present on given mounted volume, and destroy data
16510     * belonging to users that are no longer valid, or whose user ID has been
16511     * recycled.
16512     */
16513    private void reconcileUsers(String volumeUuid) {
16514        final File[] files = FileUtils
16515                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16516        for (File file : files) {
16517            if (!file.isDirectory()) continue;
16518
16519            final int userId;
16520            final UserInfo info;
16521            try {
16522                userId = Integer.parseInt(file.getName());
16523                info = sUserManager.getUserInfo(userId);
16524            } catch (NumberFormatException e) {
16525                Slog.w(TAG, "Invalid user directory " + file);
16526                continue;
16527            }
16528
16529            boolean destroyUser = false;
16530            if (info == null) {
16531                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16532                        + " because no matching user was found");
16533                destroyUser = true;
16534            } else {
16535                try {
16536                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16537                } catch (IOException e) {
16538                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16539                            + " because we failed to enforce serial number: " + e);
16540                    destroyUser = true;
16541                }
16542            }
16543
16544            if (destroyUser) {
16545                synchronized (mInstallLock) {
16546                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16547                }
16548            }
16549        }
16550
16551        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16552        final UserManager um = mContext.getSystemService(UserManager.class);
16553        for (UserInfo user : um.getUsers()) {
16554            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16555            if (userDir.exists()) continue;
16556
16557            try {
16558                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16559                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16560            } catch (IOException e) {
16561                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16562            }
16563        }
16564    }
16565
16566    /**
16567     * Examine all apps present on given mounted volume, and destroy apps that
16568     * aren't expected, either due to uninstallation or reinstallation on
16569     * another volume.
16570     */
16571    private void reconcileApps(String volumeUuid) {
16572        final File[] files = FileUtils
16573                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16574        for (File file : files) {
16575            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16576                    && !PackageInstallerService.isStageName(file.getName());
16577            if (!isPackage) {
16578                // Ignore entries which are not packages
16579                continue;
16580            }
16581
16582            boolean destroyApp = false;
16583            String packageName = null;
16584            try {
16585                final PackageLite pkg = PackageParser.parsePackageLite(file,
16586                        PackageParser.PARSE_MUST_BE_APK);
16587                packageName = pkg.packageName;
16588
16589                synchronized (mPackages) {
16590                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16591                    if (ps == null) {
16592                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16593                                + volumeUuid + " because we found no install record");
16594                        destroyApp = true;
16595                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16596                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16597                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16598                        destroyApp = true;
16599                    }
16600                }
16601
16602            } catch (PackageParserException e) {
16603                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16604                destroyApp = true;
16605            }
16606
16607            if (destroyApp) {
16608                synchronized (mInstallLock) {
16609                    if (packageName != null) {
16610                        removeDataDirsLI(volumeUuid, packageName);
16611                    }
16612                    if (file.isDirectory()) {
16613                        mInstaller.rmPackageDir(file.getAbsolutePath());
16614                    } else {
16615                        file.delete();
16616                    }
16617                }
16618            }
16619        }
16620    }
16621
16622    private void unfreezePackage(String packageName) {
16623        synchronized (mPackages) {
16624            final PackageSetting ps = mSettings.mPackages.get(packageName);
16625            if (ps != null) {
16626                ps.frozen = false;
16627            }
16628        }
16629    }
16630
16631    @Override
16632    public int movePackage(final String packageName, final String volumeUuid) {
16633        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16634
16635        final int moveId = mNextMoveId.getAndIncrement();
16636        mHandler.post(new Runnable() {
16637            @Override
16638            public void run() {
16639                try {
16640                    movePackageInternal(packageName, volumeUuid, moveId);
16641                } catch (PackageManagerException e) {
16642                    Slog.w(TAG, "Failed to move " + packageName, e);
16643                    mMoveCallbacks.notifyStatusChanged(moveId,
16644                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16645                }
16646            }
16647        });
16648        return moveId;
16649    }
16650
16651    private void movePackageInternal(final String packageName, final String volumeUuid,
16652            final int moveId) throws PackageManagerException {
16653        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16654        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16655        final PackageManager pm = mContext.getPackageManager();
16656
16657        final boolean currentAsec;
16658        final String currentVolumeUuid;
16659        final File codeFile;
16660        final String installerPackageName;
16661        final String packageAbiOverride;
16662        final int appId;
16663        final String seinfo;
16664        final String label;
16665
16666        // reader
16667        synchronized (mPackages) {
16668            final PackageParser.Package pkg = mPackages.get(packageName);
16669            final PackageSetting ps = mSettings.mPackages.get(packageName);
16670            if (pkg == null || ps == null) {
16671                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16672            }
16673
16674            if (pkg.applicationInfo.isSystemApp()) {
16675                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16676                        "Cannot move system application");
16677            }
16678
16679            if (pkg.applicationInfo.isExternalAsec()) {
16680                currentAsec = true;
16681                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16682            } else if (pkg.applicationInfo.isForwardLocked()) {
16683                currentAsec = true;
16684                currentVolumeUuid = "forward_locked";
16685            } else {
16686                currentAsec = false;
16687                currentVolumeUuid = ps.volumeUuid;
16688
16689                final File probe = new File(pkg.codePath);
16690                final File probeOat = new File(probe, "oat");
16691                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16692                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16693                            "Move only supported for modern cluster style installs");
16694                }
16695            }
16696
16697            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16698                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16699                        "Package already moved to " + volumeUuid);
16700            }
16701
16702            if (ps.frozen) {
16703                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16704                        "Failed to move already frozen package");
16705            }
16706            ps.frozen = true;
16707
16708            codeFile = new File(pkg.codePath);
16709            installerPackageName = ps.installerPackageName;
16710            packageAbiOverride = ps.cpuAbiOverrideString;
16711            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16712            seinfo = pkg.applicationInfo.seinfo;
16713            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16714        }
16715
16716        // Now that we're guarded by frozen state, kill app during move
16717        final long token = Binder.clearCallingIdentity();
16718        try {
16719            killApplication(packageName, appId, "move pkg");
16720        } finally {
16721            Binder.restoreCallingIdentity(token);
16722        }
16723
16724        final Bundle extras = new Bundle();
16725        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16726        extras.putString(Intent.EXTRA_TITLE, label);
16727        mMoveCallbacks.notifyCreated(moveId, extras);
16728
16729        int installFlags;
16730        final boolean moveCompleteApp;
16731        final File measurePath;
16732
16733        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16734            installFlags = INSTALL_INTERNAL;
16735            moveCompleteApp = !currentAsec;
16736            measurePath = Environment.getDataAppDirectory(volumeUuid);
16737        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16738            installFlags = INSTALL_EXTERNAL;
16739            moveCompleteApp = false;
16740            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16741        } else {
16742            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16743            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16744                    || !volume.isMountedWritable()) {
16745                unfreezePackage(packageName);
16746                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16747                        "Move location not mounted private volume");
16748            }
16749
16750            Preconditions.checkState(!currentAsec);
16751
16752            installFlags = INSTALL_INTERNAL;
16753            moveCompleteApp = true;
16754            measurePath = Environment.getDataAppDirectory(volumeUuid);
16755        }
16756
16757        final PackageStats stats = new PackageStats(null, -1);
16758        synchronized (mInstaller) {
16759            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16760                unfreezePackage(packageName);
16761                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16762                        "Failed to measure package size");
16763            }
16764        }
16765
16766        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16767                + stats.dataSize);
16768
16769        final long startFreeBytes = measurePath.getFreeSpace();
16770        final long sizeBytes;
16771        if (moveCompleteApp) {
16772            sizeBytes = stats.codeSize + stats.dataSize;
16773        } else {
16774            sizeBytes = stats.codeSize;
16775        }
16776
16777        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16778            unfreezePackage(packageName);
16779            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16780                    "Not enough free space to move");
16781        }
16782
16783        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16784
16785        final CountDownLatch installedLatch = new CountDownLatch(1);
16786        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16787            @Override
16788            public void onUserActionRequired(Intent intent) throws RemoteException {
16789                throw new IllegalStateException();
16790            }
16791
16792            @Override
16793            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16794                    Bundle extras) throws RemoteException {
16795                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16796                        + PackageManager.installStatusToString(returnCode, msg));
16797
16798                installedLatch.countDown();
16799
16800                // Regardless of success or failure of the move operation,
16801                // always unfreeze the package
16802                unfreezePackage(packageName);
16803
16804                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16805                switch (status) {
16806                    case PackageInstaller.STATUS_SUCCESS:
16807                        mMoveCallbacks.notifyStatusChanged(moveId,
16808                                PackageManager.MOVE_SUCCEEDED);
16809                        break;
16810                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16811                        mMoveCallbacks.notifyStatusChanged(moveId,
16812                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16813                        break;
16814                    default:
16815                        mMoveCallbacks.notifyStatusChanged(moveId,
16816                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16817                        break;
16818                }
16819            }
16820        };
16821
16822        final MoveInfo move;
16823        if (moveCompleteApp) {
16824            // Kick off a thread to report progress estimates
16825            new Thread() {
16826                @Override
16827                public void run() {
16828                    while (true) {
16829                        try {
16830                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16831                                break;
16832                            }
16833                        } catch (InterruptedException ignored) {
16834                        }
16835
16836                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16837                        final int progress = 10 + (int) MathUtils.constrain(
16838                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16839                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16840                    }
16841                }
16842            }.start();
16843
16844            final String dataAppName = codeFile.getName();
16845            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16846                    dataAppName, appId, seinfo);
16847        } else {
16848            move = null;
16849        }
16850
16851        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16852
16853        final Message msg = mHandler.obtainMessage(INIT_COPY);
16854        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16855        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16856                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16857        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16858        msg.obj = params;
16859
16860        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16861                System.identityHashCode(msg.obj));
16862        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16863                System.identityHashCode(msg.obj));
16864
16865        mHandler.sendMessage(msg);
16866    }
16867
16868    @Override
16869    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16870        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16871
16872        final int realMoveId = mNextMoveId.getAndIncrement();
16873        final Bundle extras = new Bundle();
16874        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16875        mMoveCallbacks.notifyCreated(realMoveId, extras);
16876
16877        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16878            @Override
16879            public void onCreated(int moveId, Bundle extras) {
16880                // Ignored
16881            }
16882
16883            @Override
16884            public void onStatusChanged(int moveId, int status, long estMillis) {
16885                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16886            }
16887        };
16888
16889        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16890        storage.setPrimaryStorageUuid(volumeUuid, callback);
16891        return realMoveId;
16892    }
16893
16894    @Override
16895    public int getMoveStatus(int moveId) {
16896        mContext.enforceCallingOrSelfPermission(
16897                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16898        return mMoveCallbacks.mLastStatus.get(moveId);
16899    }
16900
16901    @Override
16902    public void registerMoveCallback(IPackageMoveObserver callback) {
16903        mContext.enforceCallingOrSelfPermission(
16904                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16905        mMoveCallbacks.register(callback);
16906    }
16907
16908    @Override
16909    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16910        mContext.enforceCallingOrSelfPermission(
16911                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16912        mMoveCallbacks.unregister(callback);
16913    }
16914
16915    @Override
16916    public boolean setInstallLocation(int loc) {
16917        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16918                null);
16919        if (getInstallLocation() == loc) {
16920            return true;
16921        }
16922        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16923                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16924            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16925                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16926            return true;
16927        }
16928        return false;
16929   }
16930
16931    @Override
16932    public int getInstallLocation() {
16933        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16934                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16935                PackageHelper.APP_INSTALL_AUTO);
16936    }
16937
16938    /** Called by UserManagerService */
16939    void cleanUpUser(UserManagerService userManager, int userHandle) {
16940        synchronized (mPackages) {
16941            mDirtyUsers.remove(userHandle);
16942            mUserNeedsBadging.delete(userHandle);
16943            mSettings.removeUserLPw(userHandle);
16944            mPendingBroadcasts.remove(userHandle);
16945            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16946        }
16947        synchronized (mInstallLock) {
16948            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16949            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16950                final String volumeUuid = vol.getFsUuid();
16951                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16952                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16953            }
16954            synchronized (mPackages) {
16955                removeUnusedPackagesLILPw(userManager, userHandle);
16956            }
16957        }
16958    }
16959
16960    /**
16961     * We're removing userHandle and would like to remove any downloaded packages
16962     * that are no longer in use by any other user.
16963     * @param userHandle the user being removed
16964     */
16965    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16966        final boolean DEBUG_CLEAN_APKS = false;
16967        int [] users = userManager.getUserIds();
16968        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16969        while (psit.hasNext()) {
16970            PackageSetting ps = psit.next();
16971            if (ps.pkg == null) {
16972                continue;
16973            }
16974            final String packageName = ps.pkg.packageName;
16975            // Skip over if system app
16976            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16977                continue;
16978            }
16979            if (DEBUG_CLEAN_APKS) {
16980                Slog.i(TAG, "Checking package " + packageName);
16981            }
16982            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16983            if (keep) {
16984                if (DEBUG_CLEAN_APKS) {
16985                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16986                }
16987            } else {
16988                for (int i = 0; i < users.length; i++) {
16989                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16990                        keep = true;
16991                        if (DEBUG_CLEAN_APKS) {
16992                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16993                                    + users[i]);
16994                        }
16995                        break;
16996                    }
16997                }
16998            }
16999            if (!keep) {
17000                if (DEBUG_CLEAN_APKS) {
17001                    Slog.i(TAG, "  Removing package " + packageName);
17002                }
17003                mHandler.post(new Runnable() {
17004                    public void run() {
17005                        deletePackageX(packageName, userHandle, 0);
17006                    } //end run
17007                });
17008            }
17009        }
17010    }
17011
17012    /** Called by UserManagerService */
17013    void createNewUser(int userHandle) {
17014        synchronized (mInstallLock) {
17015            mInstaller.createUserConfig(userHandle);
17016            mSettings.createNewUserLI(this, mInstaller, userHandle);
17017        }
17018        synchronized (mPackages) {
17019            applyFactoryDefaultBrowserLPw(userHandle);
17020            primeDomainVerificationsLPw(userHandle);
17021        }
17022    }
17023
17024    void newUserCreated(final int userHandle) {
17025        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17026        // If permission review for legacy apps is required, we represent
17027        // dagerous permissions for such apps as always granted runtime
17028        // permissions to keep per user flag state whether review is needed.
17029        // Hence, if a new user is added we have to propagate dangerous
17030        // permission grants for these legacy apps.
17031        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17032            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17033                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17034        }
17035    }
17036
17037    @Override
17038    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17039        mContext.enforceCallingOrSelfPermission(
17040                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17041                "Only package verification agents can read the verifier device identity");
17042
17043        synchronized (mPackages) {
17044            return mSettings.getVerifierDeviceIdentityLPw();
17045        }
17046    }
17047
17048    @Override
17049    public void setPermissionEnforced(String permission, boolean enforced) {
17050        // TODO: Now that we no longer change GID for storage, this should to away.
17051        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17052                "setPermissionEnforced");
17053        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17054            synchronized (mPackages) {
17055                if (mSettings.mReadExternalStorageEnforced == null
17056                        || mSettings.mReadExternalStorageEnforced != enforced) {
17057                    mSettings.mReadExternalStorageEnforced = enforced;
17058                    mSettings.writeLPr();
17059                }
17060            }
17061            // kill any non-foreground processes so we restart them and
17062            // grant/revoke the GID.
17063            final IActivityManager am = ActivityManagerNative.getDefault();
17064            if (am != null) {
17065                final long token = Binder.clearCallingIdentity();
17066                try {
17067                    am.killProcessesBelowForeground("setPermissionEnforcement");
17068                } catch (RemoteException e) {
17069                } finally {
17070                    Binder.restoreCallingIdentity(token);
17071                }
17072            }
17073        } else {
17074            throw new IllegalArgumentException("No selective enforcement for " + permission);
17075        }
17076    }
17077
17078    @Override
17079    @Deprecated
17080    public boolean isPermissionEnforced(String permission) {
17081        return true;
17082    }
17083
17084    @Override
17085    public boolean isStorageLow() {
17086        final long token = Binder.clearCallingIdentity();
17087        try {
17088            final DeviceStorageMonitorInternal
17089                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17090            if (dsm != null) {
17091                return dsm.isMemoryLow();
17092            } else {
17093                return false;
17094            }
17095        } finally {
17096            Binder.restoreCallingIdentity(token);
17097        }
17098    }
17099
17100    @Override
17101    public IPackageInstaller getPackageInstaller() {
17102        return mInstallerService;
17103    }
17104
17105    private boolean userNeedsBadging(int userId) {
17106        int index = mUserNeedsBadging.indexOfKey(userId);
17107        if (index < 0) {
17108            final UserInfo userInfo;
17109            final long token = Binder.clearCallingIdentity();
17110            try {
17111                userInfo = sUserManager.getUserInfo(userId);
17112            } finally {
17113                Binder.restoreCallingIdentity(token);
17114            }
17115            final boolean b;
17116            if (userInfo != null && userInfo.isManagedProfile()) {
17117                b = true;
17118            } else {
17119                b = false;
17120            }
17121            mUserNeedsBadging.put(userId, b);
17122            return b;
17123        }
17124        return mUserNeedsBadging.valueAt(index);
17125    }
17126
17127    @Override
17128    public KeySet getKeySetByAlias(String packageName, String alias) {
17129        if (packageName == null || alias == null) {
17130            return null;
17131        }
17132        synchronized(mPackages) {
17133            final PackageParser.Package pkg = mPackages.get(packageName);
17134            if (pkg == null) {
17135                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17136                throw new IllegalArgumentException("Unknown package: " + packageName);
17137            }
17138            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17139            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17140        }
17141    }
17142
17143    @Override
17144    public KeySet getSigningKeySet(String packageName) {
17145        if (packageName == null) {
17146            return null;
17147        }
17148        synchronized(mPackages) {
17149            final PackageParser.Package pkg = mPackages.get(packageName);
17150            if (pkg == null) {
17151                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17152                throw new IllegalArgumentException("Unknown package: " + packageName);
17153            }
17154            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17155                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17156                throw new SecurityException("May not access signing KeySet of other apps.");
17157            }
17158            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17159            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17160        }
17161    }
17162
17163    @Override
17164    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17165        if (packageName == null || ks == null) {
17166            return false;
17167        }
17168        synchronized(mPackages) {
17169            final PackageParser.Package pkg = mPackages.get(packageName);
17170            if (pkg == null) {
17171                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17172                throw new IllegalArgumentException("Unknown package: " + packageName);
17173            }
17174            IBinder ksh = ks.getToken();
17175            if (ksh instanceof KeySetHandle) {
17176                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17177                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17178            }
17179            return false;
17180        }
17181    }
17182
17183    @Override
17184    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17185        if (packageName == null || ks == null) {
17186            return false;
17187        }
17188        synchronized(mPackages) {
17189            final PackageParser.Package pkg = mPackages.get(packageName);
17190            if (pkg == null) {
17191                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17192                throw new IllegalArgumentException("Unknown package: " + packageName);
17193            }
17194            IBinder ksh = ks.getToken();
17195            if (ksh instanceof KeySetHandle) {
17196                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17197                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17198            }
17199            return false;
17200        }
17201    }
17202
17203    private void deletePackageIfUnusedLPr(final String packageName) {
17204        PackageSetting ps = mSettings.mPackages.get(packageName);
17205        if (ps == null) {
17206            return;
17207        }
17208        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17209            // TODO Implement atomic delete if package is unused
17210            // It is currently possible that the package will be deleted even if it is installed
17211            // after this method returns.
17212            mHandler.post(new Runnable() {
17213                public void run() {
17214                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17215                }
17216            });
17217        }
17218    }
17219
17220    /**
17221     * Check and throw if the given before/after packages would be considered a
17222     * downgrade.
17223     */
17224    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17225            throws PackageManagerException {
17226        if (after.versionCode < before.mVersionCode) {
17227            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17228                    "Update version code " + after.versionCode + " is older than current "
17229                    + before.mVersionCode);
17230        } else if (after.versionCode == before.mVersionCode) {
17231            if (after.baseRevisionCode < before.baseRevisionCode) {
17232                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17233                        "Update base revision code " + after.baseRevisionCode
17234                        + " is older than current " + before.baseRevisionCode);
17235            }
17236
17237            if (!ArrayUtils.isEmpty(after.splitNames)) {
17238                for (int i = 0; i < after.splitNames.length; i++) {
17239                    final String splitName = after.splitNames[i];
17240                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17241                    if (j != -1) {
17242                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17243                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17244                                    "Update split " + splitName + " revision code "
17245                                    + after.splitRevisionCodes[i] + " is older than current "
17246                                    + before.splitRevisionCodes[j]);
17247                        }
17248                    }
17249                }
17250            }
17251        }
17252    }
17253
17254    private static class MoveCallbacks extends Handler {
17255        private static final int MSG_CREATED = 1;
17256        private static final int MSG_STATUS_CHANGED = 2;
17257
17258        private final RemoteCallbackList<IPackageMoveObserver>
17259                mCallbacks = new RemoteCallbackList<>();
17260
17261        private final SparseIntArray mLastStatus = new SparseIntArray();
17262
17263        public MoveCallbacks(Looper looper) {
17264            super(looper);
17265        }
17266
17267        public void register(IPackageMoveObserver callback) {
17268            mCallbacks.register(callback);
17269        }
17270
17271        public void unregister(IPackageMoveObserver callback) {
17272            mCallbacks.unregister(callback);
17273        }
17274
17275        @Override
17276        public void handleMessage(Message msg) {
17277            final SomeArgs args = (SomeArgs) msg.obj;
17278            final int n = mCallbacks.beginBroadcast();
17279            for (int i = 0; i < n; i++) {
17280                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17281                try {
17282                    invokeCallback(callback, msg.what, args);
17283                } catch (RemoteException ignored) {
17284                }
17285            }
17286            mCallbacks.finishBroadcast();
17287            args.recycle();
17288        }
17289
17290        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17291                throws RemoteException {
17292            switch (what) {
17293                case MSG_CREATED: {
17294                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17295                    break;
17296                }
17297                case MSG_STATUS_CHANGED: {
17298                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17299                    break;
17300                }
17301            }
17302        }
17303
17304        private void notifyCreated(int moveId, Bundle extras) {
17305            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17306
17307            final SomeArgs args = SomeArgs.obtain();
17308            args.argi1 = moveId;
17309            args.arg2 = extras;
17310            obtainMessage(MSG_CREATED, args).sendToTarget();
17311        }
17312
17313        private void notifyStatusChanged(int moveId, int status) {
17314            notifyStatusChanged(moveId, status, -1);
17315        }
17316
17317        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17318            Slog.v(TAG, "Move " + moveId + " status " + status);
17319
17320            final SomeArgs args = SomeArgs.obtain();
17321            args.argi1 = moveId;
17322            args.argi2 = status;
17323            args.arg3 = estMillis;
17324            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17325
17326            synchronized (mLastStatus) {
17327                mLastStatus.put(moveId, status);
17328            }
17329        }
17330    }
17331
17332    private final static class OnPermissionChangeListeners extends Handler {
17333        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17334
17335        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17336                new RemoteCallbackList<>();
17337
17338        public OnPermissionChangeListeners(Looper looper) {
17339            super(looper);
17340        }
17341
17342        @Override
17343        public void handleMessage(Message msg) {
17344            switch (msg.what) {
17345                case MSG_ON_PERMISSIONS_CHANGED: {
17346                    final int uid = msg.arg1;
17347                    handleOnPermissionsChanged(uid);
17348                } break;
17349            }
17350        }
17351
17352        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17353            mPermissionListeners.register(listener);
17354
17355        }
17356
17357        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17358            mPermissionListeners.unregister(listener);
17359        }
17360
17361        public void onPermissionsChanged(int uid) {
17362            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17363                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17364            }
17365        }
17366
17367        private void handleOnPermissionsChanged(int uid) {
17368            final int count = mPermissionListeners.beginBroadcast();
17369            try {
17370                for (int i = 0; i < count; i++) {
17371                    IOnPermissionsChangeListener callback = mPermissionListeners
17372                            .getBroadcastItem(i);
17373                    try {
17374                        callback.onPermissionsChanged(uid);
17375                    } catch (RemoteException e) {
17376                        Log.e(TAG, "Permission listener is dead", e);
17377                    }
17378                }
17379            } finally {
17380                mPermissionListeners.finishBroadcast();
17381            }
17382        }
17383    }
17384
17385    private class PackageManagerInternalImpl extends PackageManagerInternal {
17386        @Override
17387        public void setLocationPackagesProvider(PackagesProvider provider) {
17388            synchronized (mPackages) {
17389                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17390            }
17391        }
17392
17393        @Override
17394        public void setImePackagesProvider(PackagesProvider provider) {
17395            synchronized (mPackages) {
17396                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17397            }
17398        }
17399
17400        @Override
17401        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17402            synchronized (mPackages) {
17403                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17404            }
17405        }
17406
17407        @Override
17408        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17409            synchronized (mPackages) {
17410                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17411            }
17412        }
17413
17414        @Override
17415        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17416            synchronized (mPackages) {
17417                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17418            }
17419        }
17420
17421        @Override
17422        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17423            synchronized (mPackages) {
17424                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17425            }
17426        }
17427
17428        @Override
17429        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17430            synchronized (mPackages) {
17431                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17432            }
17433        }
17434
17435        @Override
17436        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17437            synchronized (mPackages) {
17438                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17439                        packageName, userId);
17440            }
17441        }
17442
17443        @Override
17444        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17445            synchronized (mPackages) {
17446                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17447                        packageName, userId);
17448            }
17449        }
17450
17451        @Override
17452        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17453            synchronized (mPackages) {
17454                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17455                        packageName, userId);
17456            }
17457        }
17458
17459        @Override
17460        public void setKeepUninstalledPackages(final List<String> packageList) {
17461            Preconditions.checkNotNull(packageList);
17462            List<String> removedFromList = null;
17463            synchronized (mPackages) {
17464                if (mKeepUninstalledPackages != null) {
17465                    final int packagesCount = mKeepUninstalledPackages.size();
17466                    for (int i = 0; i < packagesCount; i++) {
17467                        String oldPackage = mKeepUninstalledPackages.get(i);
17468                        if (packageList != null && packageList.contains(oldPackage)) {
17469                            continue;
17470                        }
17471                        if (removedFromList == null) {
17472                            removedFromList = new ArrayList<>();
17473                        }
17474                        removedFromList.add(oldPackage);
17475                    }
17476                }
17477                mKeepUninstalledPackages = new ArrayList<>(packageList);
17478                if (removedFromList != null) {
17479                    final int removedCount = removedFromList.size();
17480                    for (int i = 0; i < removedCount; i++) {
17481                        deletePackageIfUnusedLPr(removedFromList.get(i));
17482                    }
17483                }
17484            }
17485        }
17486
17487        @Override
17488        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17489            synchronized (mPackages) {
17490                // If we do not support permission review, done.
17491                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17492                    return false;
17493                }
17494
17495                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17496                if (packageSetting == null) {
17497                    return false;
17498                }
17499
17500                // Permission review applies only to apps not supporting the new permission model.
17501                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17502                    return false;
17503                }
17504
17505                // Legacy apps have the permission and get user consent on launch.
17506                PermissionsState permissionsState = packageSetting.getPermissionsState();
17507                return permissionsState.isPermissionReviewRequired(userId);
17508            }
17509        }
17510    }
17511
17512    @Override
17513    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17514        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17515        synchronized (mPackages) {
17516            final long identity = Binder.clearCallingIdentity();
17517            try {
17518                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17519                        packageNames, userId);
17520            } finally {
17521                Binder.restoreCallingIdentity(identity);
17522            }
17523        }
17524    }
17525
17526    private static void enforceSystemOrPhoneCaller(String tag) {
17527        int callingUid = Binder.getCallingUid();
17528        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17529            throw new SecurityException(
17530                    "Cannot call " + tag + " from UID " + callingUid);
17531        }
17532    }
17533}
17534